diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.ts index 08f62c8d1..24299725b 100644 --- a/apps/server/src/environment/Layers/ServerEnvironment.ts +++ b/apps/server/src/environment/Layers/ServerEnvironment.ts @@ -118,6 +118,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function pushAlerts: true, phoneAlertControls: true, projectLead: true, + childStartSelection: true, deviceNames: true, draftGoalSetup: true, pullRequestSwitchesByNumber: true, diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 591a89f16..489fcc721 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -112,6 +112,10 @@ A project's lead chat is a thread set up to coordinate the project; see the lead Any thread can be the lead. Use "Make this the lead chat" in a thread's menu (right-click its row, or click the title above the chat), or the command palette. The project's menu in the project picker has Open lead chat, or New lead chat, which starts a thread in the project folder and makes it the lead. "Go to lead chat" in the command palette opens it. +The lead can also pass a message to a thread you started by hand in the project. That is one-way: the thread works on it and answers there, not back in the lead, and it can't start threads of its own for it until you write there. The lead can't pass work into a room, a thread another thread still owns, or one you stopped. A pass never runs with more access than the lead had. + +When an agent asks to start several threads, the card has a checkbox per thread, so you can start some and leave the rest; the agent is told which. + Only one thread leads a project; making another the lead replaces it. "Stop using as lead chat" turns it back into an ordinary thread, and the threads it started stay with it. Archiving or deleting the lead ends it. A lead can't move to another computer, and each computer keeps its own lead for a project. The lead's row sits at the top of the sidebar with a flag, says Lead where the project name goes, and never wraps up on its own. The chat shows a Lead chat label beside the title. diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts index d3f611805..2e499656c 100644 --- a/apps/server/src/links/LinkMoves.ts +++ b/apps/server/src/links/LinkMoves.ts @@ -1806,6 +1806,8 @@ const make = Effect.gen(function* () { ...(message.completesTurn !== undefined ? { completesTurn: message.completesTurn } : {}), ...(message.agentModels !== undefined ? { agentModels: message.agentModels } : {}), ...(message.sentFrom !== undefined ? { sentFrom: message.sentFrom } : {}), + // Never reached the agent there: no history here may carry it either. + ...(message.notSent === true ? { notSent: true as const } : {}), createdAt: message.createdAt, })); const activities = row.manifest.thread.activities.map((activity) => ({ diff --git a/apps/server/src/mcp/McpRoomServer.ts b/apps/server/src/mcp/McpRoomServer.ts index b97c87724..539173efa 100644 --- a/apps/server/src/mcp/McpRoomServer.ts +++ b/apps/server/src/mcp/McpRoomServer.ts @@ -16,6 +16,7 @@ * (scheduleTools.ts) are served here too: they need the same caller identity * and the same per-runtime grant. */ +import { PullRequestObservations } from "../pullRequest/PullRequestObservations.ts"; import { agentInvitesMode, agentThreadsMode, @@ -187,6 +188,7 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( const linkClient = yield* Effect.serviceOption(ComputerLinkClient); const linkRepo = yield* Effect.serviceOption(ComputerLinkRepository); const identities = yield* Effect.serviceOption(RepositoryIdentityResolver); + const pullRequestObservations = yield* Effect.serviceOption(PullRequestObservations); const links = Option.isSome(linkClient) && Option.isSome(linkRepo) && Option.isSome(identities) ? makeThreadToolLinks({ @@ -268,6 +270,9 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer( snapshots .getProjectShellById(projectId) .pipe(Effect.map(Option.getOrUndefined), Effect.orDie), + ...(Option.isSome(pullRequestObservations) + ? { knownPullRequests: pullRequestObservations.value.known } + : {}), providers: providers.getProviders, userDefaultModel, threadsMode: settings.getSettings.pipe( diff --git a/apps/server/src/mcp/roomHistory.ts b/apps/server/src/mcp/roomHistory.ts index 3e77ccadf..24dd2b09a 100644 --- a/apps/server/src/mcp/roomHistory.ts +++ b/apps/server/src/mcp/roomHistory.ts @@ -41,6 +41,8 @@ export interface RoomHistoryEntry { readonly text: string; readonly clipped?: boolean; readonly streaming?: boolean; + /** It never reached the agent (OrchestrationMessage.notSent): shown, never acted on. */ + readonly notSent?: boolean; readonly attachments?: ReadonlyArray; } @@ -75,6 +77,7 @@ function labelMessage( ...(message.requestKind !== undefined ? { requestKind: message.requestKind } : {}), ...(onTheSide ? { onTheSide: true } : {}), ...(message.streaming ? { streaming: true } : {}), + ...(message.notSent === true ? { notSent: true } : {}), ...(message.attachments !== undefined && message.attachments.length > 0 ? { attachments: message.attachments.map((attachment) => ({ diff --git a/apps/server/src/mcp/threadToolHandlers.test.ts b/apps/server/src/mcp/threadToolHandlers.test.ts index 26eba1fa3..34685c635 100644 --- a/apps/server/src/mcp/threadToolHandlers.test.ts +++ b/apps/server/src/mcp/threadToolHandlers.test.ts @@ -179,6 +179,8 @@ const shellOf = (thread: OrchestrationThread): OrchestrationThreadShell => pendingChildApproval: false, awaitedChildThreadCount: 0, doneOverride: null, + // Every real thread carries it (decoding defaults it); some fixtures leave it out. + linkedPullRequests: (thread as Partial).linkedPullRequests ?? [], }) as unknown as OrchestrationThreadShell; const mainCaller = (): McpInvocationScope => ({ @@ -210,6 +212,8 @@ const makeTools = (options: { /** The branch checked out in a folder; any other folder has none. */ readonly branches?: Readonly>; readonly moves?: ThreadToolMoves; + /** The project's lead chat (docs/design/lead-chat.md). */ + readonly leadThreadId?: ThreadId; }) => Effect.gen(function* () { let caller = options.caller ?? makeThread(); @@ -259,7 +263,12 @@ const makeTools = (options: { .filter((thread) => thread.projectId === PROJECT) .map(shellOf), ), - readProject: () => Effect.succeed({ kind: "workspace" as const, workspaceRoot: "/project" }), + readProject: () => + Effect.succeed({ + kind: "workspace" as const, + workspaceRoot: "/project", + leadThreadId: options.leadThreadId ?? null, + }), providers: Effect.succeed(PROVIDERS), userDefaultModel: Effect.succeed(options.userDefault ?? null), threadsMode: Effect.succeed(options.mode ?? "auto"), @@ -638,6 +647,47 @@ describe("thread_send", () => { ); }); +describe("thread_send from the project's lead chat", () => { + it.effect("passes a message to a thread the user started, one-way", () => + Effect.gen(function* () { + const handMade = makeChild({ id: STRANGER, parentThreadId: null, attachedToParent: false }); + const tools = yield* makeTools({ others: [handMade], leadThreadId: PARENT }); + const result = yield* tools.handlers.thread_send(mainCaller(), { + threadId: STRANGER, + message: "Fix the flaky test.", + }); + expect(result).toMatchObject({ outcome: "sent", reportsBack: false, threadId: STRANGER }); + const [passed] = ofType(tools.dispatched, "thread.lead.pass"); + expect(passed).toMatchObject({ threadId: PARENT, targetThreadId: STRANGER }); + expect(ofType(tools.dispatched, "thread.child.send")).toHaveLength(0); + }), + ); + + it.effect( + "refuses a thread another thread owns, and anything from a thread that isn't the lead", + () => + Effect.gen(function* () { + const owned = makeChild({ id: STRANGER, parentThreadId: ThreadId.make("someone-else") }); + const lead = yield* makeTools({ others: [owned], leadThreadId: PARENT }); + const refused = yield* lead.handlers.thread_send(mainCaller(), { + threadId: STRANGER, + message: "Fix it.", + }); + expect(refused.outcome).toBe("not_yours"); + expect(refused.detail).toContain("Message the thread that started it"); + + const handMade = makeChild({ id: STRANGER, parentThreadId: null, attachedToParent: false }); + const plain = yield* makeTools({ others: [handMade] }); + const notLead = yield* plain.handlers.thread_send(mainCaller(), { + threadId: STRANGER, + message: "Fix it.", + }); + expect(notLead.outcome).toBe("not_yours"); + expect(lead.dispatched.length + plain.dispatched.length).toBe(0); + }), + ); +}); + describe("an existing checkout", () => { /** A thread the parent started that has finished its work, on its own branch. */ const coder = (patch: Partial = {}) => @@ -942,6 +992,18 @@ describe("thread_read", () => { }), message({ eventSequence: 2, text: "Also look at the index." }), message({ eventSequence: 3, role: "assistant", text: "It is safe." }), + // A lead chat's pass that never ran: shown, labelled. + message({ + eventSequence: 4, + text: "Run the migration.", + notSent: true, + fromThread: { + threadId: PARENT, + requestId: "request-2" as never, + kind: "request", + ceiling: { runtimeMode: "approval-required", interactionMode: "default" }, + }, + }), ], }); const tools = yield* makeTools({ others: [child] }); @@ -951,15 +1013,22 @@ describe("thread_read", () => { ["thread_request", `Request from thread "Parent" (${PARENT})`], ["user", "User"], ["agent", "GPT-6 Astra"], + ["thread_request", `Request from thread "Parent" (${PARENT})`], + ]); + expect(result.messages.map((entry) => entry.notSent ?? false)).toEqual([ + false, + false, + false, + true, ]); expect(result.thread).toMatchObject({ threadId: CHILD, startedBy: "you", attached: true }); - expect(result.next).toBe(3); + expect(result.next).toBe(4); const later = yield* tools.handlers.thread_read(mainCaller(), { threadId: CHILD, after: 2, }); - expect(later.messages.map((entry) => entry.sequence)).toEqual([3]); + expect(later.messages.map((entry) => entry.sequence)).toEqual([3, 4]); }), ); diff --git a/apps/server/src/mcp/threadToolHandlers.ts b/apps/server/src/mcp/threadToolHandlers.ts index afbd4e988..bc572a18f 100644 --- a/apps/server/src/mcp/threadToolHandlers.ts +++ b/apps/server/src/mcp/threadToolHandlers.ts @@ -57,8 +57,10 @@ import { childSendRefusal, childStartRefusal, isAttachedChild, + leadPassRefusal, ownChildRefusal, remoteChildOf, + withinModeCeiling, } from "@threadlines/shared/childThreads"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -130,7 +132,26 @@ export interface ThreadToolDeps { readonly readProject: ( projectId: ProjectId, ) => Effect.Effect< - Pick | undefined + | Pick< + OrchestrationProjectShell, + "kind" | "workspaceRoot" | "leadThreadId" | "repositoryIdentity" + > + | undefined + >; + /** + * A thread's pull requests as this computer already knows them, with no + * call to the host (PullRequestObservations.known). Absent: none listed. + */ + readonly knownPullRequests?: (input: { + readonly repositoryKey: string | null; + readonly branch: string | null; + readonly urls: ReadonlyArray; + }) => Effect.Effect< + ReadonlyArray<{ + readonly number: number; + readonly url: string; + readonly state: "open" | "merged" | "closed"; + }> >; /** The provider snapshots: who a child could run on. */ readonly providers: Effect.Effect>; @@ -1523,20 +1544,55 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { ) : []; const scheduleAnswerWaiting = yield* waitingOnScheduleAnswers; - return { - outcome: "ok", - threads: [ - ...listed.map((shell) => + // Which thread leads the project, and what each listed thread's pull + // requests are as already known here (docs/design/lead-chat.md). + const project = yield* deps.readProject(thread.projectId); + const repositoryKey = project?.repositoryIdentity?.canonicalKey ?? null; + type KnownPullRequest = NonNullable[number]; + const pullRequestsOf = ( + shell: OrchestrationThreadShell, + ): Effect.Effect> => + (deps.knownPullRequests === undefined + ? Effect.succeed([]) + : deps.knownPullRequests({ + repositoryKey, + branch: shell.branch, + urls: shell.linkedPullRequests.map((linked) => linked.url), + }) + ).pipe( + Effect.map((known) => { + const byUrl = new Map( + known.map((entry) => [ + entry.url, + { number: entry.number, url: entry.url, state: entry.state }, + ]), + ); + // One its agent opened that nobody has read yet: no state to say. + for (const linked of shell.linkedPullRequests) { + if (!byUrl.has(linked.url)) { + byUrl.set(linked.url, { number: linked.number, url: linked.url }); + } + } + return [...byUrl.values()]; + }), + ); + const summaries = yield* Effect.forEach(listed, (shell) => + pullRequestsOf(shell).pipe( + Effect.map((pullRequests): ThreadSummary => summarizeThread(shell, { caller: thread, providers, titleOf: (threadId) => titles.get(threadId), scheduleAnswerWaiting, + leadThreadId: project?.leadThreadId ?? null, + pullRequests, }), ), - ...settingUp, - ...remote, - ], + ), + ); + return { + outcome: "ok", + threads: [...summaries, ...settingUp, ...remote], } satisfies ThreadListResult; }); @@ -1720,6 +1776,15 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { } const owned = yield* ownChild(thread, scope, input.threadId); if ("refusal" in owned) { + // The project's lead chat may pass a message to a thread it did not + // start (docs/design/lead-chat.md, "Tools"): one-way, never a move. + if ( + owned.refusal.outcome === "not_yours" && + checkoutReference === undefined && + (yield* isLeadThread(thread)) + ) { + return yield* leadPass(scope, thread, input.threadId, input.message); + } return owned.refusal satisfies ThreadSendResult; } const childThreadId = owned.child.id; @@ -1850,6 +1915,114 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { ); }); + /** + * The lead chat passes `message` to a thread it did not start. Nothing is + * owed back: the thread answers where the user reads it. The decider checks + * the same rules again (leadPassRefusal) and the access ceiling. + */ + const leadPass = ( + scope: McpInvocationScope, + lead: OrchestrationThread, + targetReference: string, + message: string, + ): Effect.Effect => + Effect.gen(function* () { + const targetId = targetReference.trim(); + const text = message.trim(); + if (text.length === 0) { + return { outcome: "refused", detail: "Say what you want from the thread." }; + } + if (text.length > THREAD_PROMPT_CHAR_LIMIT) { + return { + outcome: "refused", + detail: `Keep the message under ${THREAD_PROMPT_CHAR_LIMIT.toLocaleString("en-US")} characters.`, + }; + } + const callerTurnId = lead.session?.activeTurnId ?? NO_TURN; + const key = [ + scope.threadId, + scope.participantId ?? "primary", + callerTurnId, + "thread_send:pass", + targetId, + text, + ].join("\u0000"); + const requestId = ChildRequestId.make(derivedUuid(key, "request")); + const messageId = MessageId.make(derivedUuid(key, "message")); + const passedDetail = { + sent: "Passed on. That thread works on it where the user reads it; nothing comes back to you. Read it later with thread_read if the user asks.", + queued: + "Passed on. That thread is busy and takes it after its current turn; nothing comes back to you. Read it later with thread_read if the user asks.", + } as const; + return yield* deps.requests.join(key, () => + Effect.gen(function* () { + const [caller, target] = yield* Effect.all([ + deps.readThread(scope.threadId), + deps.readThread(ThreadId.make(targetId)), + ]); + if (caller === undefined) { + return { outcome: "refused", detail: GONE } satisfies ThreadSendResult; + } + // The same pass, already made in this turn: that one stands. + if (target?.messages.some((entry) => entry.id === messageId)) { + return { + outcome: "sent", + detail: passedDetail.sent, + threadId: targetId, + reportsBack: false, + } satisfies ThreadSendResult; + } + const refusal = leadPassRefusal(caller, target ?? null, { + from: from(scope), + callerTurnId, + isLead: yield* isLeadThread(caller), + }); + if (refusal !== null || target === undefined) { + return { + outcome: + refusal?.outcome === "limit" + ? ("limit" as const) + : refusal?.outcome === "not_allowed" + ? ("not_yours" as const) + : ("refused" as const), + detail: refusal?.detail ?? NOT_FOUND, + threadId: targetId, + } satisfies ThreadSendResult; + } + if (!withinModeCeiling(target, caller)) { + return { + outcome: "refused", + detail: + "That thread has more access than the lead chat, so it can't take work from it. Tell the user, who can send it there.", + threadId: targetId, + } satisfies ThreadSendResult; + } + const outcome = childIsBusy(target, caller) ? ("queued" as const) : ("sent" as const); + const rejected = yield* dispatch({ + type: "thread.lead.pass", + commandId: childRequestCommandId(requestId, "pass"), + threadId: scope.threadId, + from: from(scope), + callerTurnId, + targetThreadId: target.id, + requestId, + messageId, + text, + createdAt: yield* nowIso, + }); + if (rejected !== undefined) { + return rejected satisfies ThreadSendResult; + } + return { + outcome, + detail: passedDetail[outcome], + threadId: target.id, + reportsBack: false, + } satisfies ThreadSendResult; + }), + ); + }); + const threadStop = ( scope: McpInvocationScope, input: { readonly threadId: string }, diff --git a/apps/server/src/mcp/threadTools.ts b/apps/server/src/mcp/threadTools.ts index b48a958c9..47527101b 100644 --- a/apps/server/src/mcp/threadTools.ts +++ b/apps/server/src/mcp/threadTools.ts @@ -140,6 +140,11 @@ export const ThreadSendResult = Schema.Struct({ ]), detail: Schema.optional(Schema.String), threadId: Schema.optional(Schema.String), + /** + * False for a lead chat's pass to a thread it did not start + * (docs/design/lead-chat.md): nothing comes back from it. + */ + reportsBack: Schema.optional(Schema.Boolean), }); export type ThreadSendResult = typeof ThreadSendResult.Type; @@ -241,7 +246,7 @@ export const ThreadStartTool = loadedOnDemand( drivesThreads( Tool.make("thread_start", { description: - "Start new threads in this project to work in parallel. Each gets its own agent session and its own git worktree off your current commit (in a project without git they share the project folder). Give each a short `title` and a self-contained `prompt`: the new thread sees none of this conversation, only its prompt. `agent` picks a model from thread_agents; leave it out to use your own model and reasoning. Unless the user asked for a model or reasoning, prefer your own model or one already in this room (thread_agents' `room`), here or on another computer: a thread on a room agent's model runs at the reasoning the user set for that agent. `agent.reasoning` sets a level instead. Threads get your current access and interaction modes, never more; `access` asks for less. `runSetup: false` skips the project's setup script, for quick research. `checkout` puts a thread in a checkout that already exists instead of a new worktree, so it sees the files as they are there, uncommitted changes included (a reviewer for work another thread just finished): no worktree or branch is made and the setup script is not run. It shares that folder with the thread it belongs to, so have only one of them work at a time. `computer` starts them on another linked computer (a name or id from thread_agents' `computers`) in its copy of this project: from your branch when you pushed it, otherwise from that computer's default branch, without your unpushed changes. With `reportBack` (default true) each thread's final reply comes back to you as a message when it finishes; with false they run on their own and nothing comes back. Returns as soon as they are recorded and does not wait for them, so don't poll: carry on, or end your turn if you have nothing else to do. At most 5 threads per call and 5 per user message.", + "Start new threads in this project to work in parallel. Each gets its own agent session and its own git worktree off your current commit (in a project without git they share the project folder). Give each a short `title` and a self-contained `prompt`: the new thread sees none of this conversation, only its prompt. `agent` picks a model from thread_agents; leave it out to use your own model and reasoning. Unless the user asked for a model or reasoning, prefer your own model or one already in this room (thread_agents' `room`), here or on another computer: a thread on a room agent's model runs at the reasoning the user set for that agent. `agent.reasoning` sets a level instead. Threads get your current access and interaction modes, never more; `access` asks for less. `runSetup: false` skips the project's setup script, for quick research. `checkout` puts a thread in a checkout that already exists instead of a new worktree, so it sees the files as they are there, uncommitted changes included (a reviewer for work another thread just finished): no worktree or branch is made and the setup script is not run. It shares that folder with the thread it belongs to, so have only one of them work at a time. `computer` starts them on another linked computer (a name or id from thread_agents' `computers`) in its copy of this project: from your branch when you pushed it, otherwise from that computer's default branch, without your unpushed changes. With `reportBack` (default true) each thread's final reply comes back to you as a message when it finishes; with false they run on their own and nothing comes back. Returns as soon as they are recorded and does not wait for them, so don't poll: carry on, or end your turn if you have nothing else to do. At most 5 threads per call and 5 per user message (10 in the project's lead chat).", parameters: Schema.Struct({ threads: Schema.Array( Schema.Struct({ @@ -279,7 +284,7 @@ export const ThreadListTool = loadedOnDemand( readsThreads( Tool.make("thread_list", { description: - 'Threads you started (`scope: "mine"`, the default), including ones the user made their own and ones on linked computers (with `computer` set, status as last heard), or this project\'s open threads (`"project"`, most recently active first, at most 30). Each has its id, title, status (working, needs the user, waiting, failed, idle, wrapped), branch, model, whether its replies come back to the thread that started it, and who started it.', + 'Threads you started (`scope: "mine"`, the default), including ones the user made their own and ones on linked computers (with `computer` set, status as last heard), or this project\'s open threads (`"project"`, most recently active first, at most 30). Each has its id, title, status (working, needs the user, waiting, failed, idle, wrapped), branch, model, whether its replies come back to the thread that started it, and who started it. The project\'s lead chat is marked `lead`; each also has when its work last moved and its pull requests as this computer knows them.', parameters: Schema.Struct({ scope: Schema.optional(Schema.Literals(["mine", "project"])), }), @@ -323,7 +328,7 @@ export const ThreadSendTool = loadedOnDemand( drivesThreads( Tool.make("thread_send", { description: - "Send one of your threads a message: more work, a correction or a question. If it is idle it starts on it now; if it is busy it takes it after its current turn. Its reply comes back to you as a message, like a start. Only threads you started whose replies still come back to you. `checkout` first moves an idle thread into another thread's checkout, keeping its conversation, so it reads your message there (a thread that planned the work looks at what another thread built). Don't poll; end your turn if you have nothing else to do.", + "Send one of your threads a message: more work, a correction or a question. If it is idle it starts on it now; if it is busy it takes it after its current turn. Its reply comes back to you as a message, like a start. Only threads you started whose replies still come back to you. `checkout` first moves an idle thread into another thread's checkout, keeping its conversation, so it reads your message there (a thread that planned the work looks at what another thread built). The project's lead chat may also pass a message to an open thread in this project that it did not start (not a room, not one another thread owns, not one the user stopped): it works on it there, and nothing comes back. Don't poll; end your turn if you have nothing else to do.", parameters: Schema.Struct({ threadId: ThreadIdParameter, message: Schema.String.annotate({ description: "What you want it to do or answer." }), diff --git a/apps/server/src/moves/ThreadMoves.test.ts b/apps/server/src/moves/ThreadMoves.test.ts index 29f3f13b0..069993917 100644 --- a/apps/server/src/moves/ThreadMoves.test.ts +++ b/apps/server/src/moves/ThreadMoves.test.ts @@ -24,7 +24,12 @@ import { previewManyThread, targetPreviewOf, } from "./ThreadMoves.ts"; -import { MOVE_MAX_BYTES, moveThreadStateOf, nativeSessionFits } from "./moveExport.ts"; +import { + exportThreadHistory, + MOVE_MAX_BYTES, + moveThreadStateOf, + nativeSessionFits, +} from "./moveExport.ts"; import { carryBringsWords, threadMoveCarry } from "../orchestration/threadMoveCarry.ts"; import { NATIVE_SESSION_MAX_BYTES, type NativeSessionExport } from "../provider/nativeSession.ts"; @@ -451,3 +456,28 @@ describe("what a thread carries, as the dialog says it (Part 3e)", () => { ]); }); }); + +describe("exportThreadHistory", () => { + it("sends an agent's message still waiting in the queue as never sent", () => { + const message = (id: string, text: string) => ({ + id: MessageId.make(id), + role: "user" as const, + text, + turnId: null, + streaming: false, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + }); + const thread = { + messages: [message("ran", "Fix it."), message("waiting", "Run the migration.")], + activities: [], + queuedFollowUps: [{ messageId: MessageId.make("waiting") }], + } as unknown as OrchestrationThread; + expect( + exportThreadHistory(thread).messages.map((entry) => [entry.text, entry.notSent ?? false]), + ).toEqual([ + ["Fix it.", false], + ["Run the migration.", true], + ]); + }); +}); diff --git a/apps/server/src/moves/moveExport.ts b/apps/server/src/moves/moveExport.ts index 976e6db58..be71dd15c 100644 --- a/apps/server/src/moves/moveExport.ts +++ b/apps/server/src/moves/moveExport.ts @@ -283,6 +283,10 @@ export function exportThreadHistory(thread: OrchestrationThread): { readonly messages: ReadonlyArray; readonly activities: ReadonlyArray; } { + // An agent's message still waiting in the queue is written into the chat + // but never ran here, and only the user's own queued messages move: it + // arrives as never sent (reachedAgent), so no history there carries it. + const queuedIds = new Set((thread.queuedFollowUps ?? []).map((queued) => queued.messageId)); const messages = thread.messages .filter( (message) => @@ -304,7 +308,7 @@ export function exportThreadHistory(thread: OrchestrationThread): { ...(message.fromOutside !== undefined ? { fromOutside: message.fromOutside } : {}), ...(message.sentFrom !== undefined ? { sentFrom: message.sentFrom } : {}), ...(message.trigger !== undefined ? { trigger: message.trigger } : {}), - ...(message.notSent === true ? { notSent: true as const } : {}), + ...(message.notSent === true || queuedIds.has(message.id) ? { notSent: true as const } : {}), createdAt: message.createdAt, })); const activities = thread.activities diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index a12e1df4f..8c9f32793 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -873,6 +873,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti case "thread.child-notes-delivered": case "thread.child-deliveries-cancelled": case "thread.child-requests-reset": + case "thread.lead-pass-recorded": case "thread.remote-child-updated": case "thread.remote-cancel-queued": case "thread.remote-cancels-delivered": { @@ -903,7 +904,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti state, event.payload.requestIds, ) - : childRequestStateOn.reset(state); + : event.type === "thread.lead-pass-recorded" + ? childRequestStateOn.leadPass(state, event.payload) + : childRequestStateOn.reset(state, event.payload); if (childRequests !== state) { yield* projectionThreadRepository.upsert({ ...existingRow.value, childRequests }); } @@ -1528,16 +1531,34 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti { ...message.value, id: message.value.messageId }, event.payload, ); - if (marked.requestOutcome !== message.value.requestOutcome) { + if ( + marked.requestOutcome !== message.value.requestOutcome || + marked.notSent !== message.value.notSent + ) { yield* projectionThreadMessageRepository.upsert({ ...message.value, requestOutcome: marked.requestOutcome, + ...(marked.notSent === true ? { notSent: true as const } : {}), }); } } return; } + // A lead chat's pass refused right before it reached the agent. + case "thread.lead-pass-recorded": { + if (event.payload.kind !== "not-run") { + return; + } + const message = yield* projectionThreadMessageRepository.getByMessageId({ + messageId: event.payload.messageId, + }); + if (Option.isSome(message) && message.value.notSent !== true) { + yield* projectionThreadMessageRepository.upsert({ ...message.value, notSent: true }); + } + return; + } + // A continue the user's own message overtook never reached the agent. case "thread.continue-at-reset-skipped": { const message = yield* projectionThreadMessageRepository.getByMessageId({ @@ -1653,6 +1674,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ...(event.payload.composer !== undefined ? { composer: event.payload.composer } : {}), ...(event.payload.sentFrom !== undefined ? { sentFrom: event.payload.sentFrom } : {}), ...(event.payload.trigger !== undefined ? { trigger: event.payload.trigger } : {}), + ...(event.payload.notSent === true ? { notSent: true as const } : {}), ...(event.payload.afterMove === true ? { afterMove: true as const } : {}), isStreaming: event.payload.streaming, createdAt: previousMessage?.createdAt ?? event.payload.createdAt, diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index fe7275c77..33a9945b6 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -156,6 +156,7 @@ const ProjectionProjectCatalogDbRowSchema = Schema.Struct({ kind: ProjectionProject.fields.kind, title: ProjectionProject.fields.title, workspaceRoot: ProjectionProject.fields.workspaceRoot, + leadThreadId: Schema.NullOr(ThreadId), createdAt: ProjectionProject.fields.createdAt, updatedAt: ProjectionProject.fields.updatedAt, deletedAt: ProjectionProject.fields.deletedAt, @@ -907,15 +908,22 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { execute: () => sql` SELECT - project_id AS "projectId", - kind, - title, - workspace_root AS "workspaceRoot", - created_at AS "createdAt", - updated_at AS "updatedAt", - deleted_at AS "deletedAt" - FROM projection_projects - ORDER BY created_at ASC, project_id ASC + p.project_id AS "projectId", + p.kind, + p.title, + p.workspace_root AS "workspaceRoot", + lead.thread_id AS "leadThreadId", + p.created_at AS "createdAt", + p.updated_at AS "updatedAt", + p.deleted_at AS "deletedAt" + FROM projection_projects p + -- A pointer at an archived, deleted or missing thread is no lead. + LEFT JOIN projection_threads lead + ON lead.thread_id = p.lead_thread_id + AND lead.project_id = p.project_id + AND lead.archived_at IS NULL + AND lead.deleted_at IS NULL + ORDER BY p.created_at ASC, p.project_id ASC `, }); @@ -2570,6 +2578,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { kind: row.kind, title: row.title, workspaceRoot: row.workspaceRoot, + ...(row.leadThreadId !== null ? { leadThreadId: row.leadThreadId } : {}), createdAt: row.createdAt, updatedAt: row.updatedAt, deletedAt: row.deletedAt, diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index e6df0bb1c..8e634eccd 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -3792,6 +3792,156 @@ describe("ProviderCommandReactor", () => { }); expect(harness.sendTurn).not.toHaveBeenCalled(); }); + + it("doesn't send a lead chat's pass the user raised above its ceiling after it was accepted", async () => { + const threadId = ThreadId.make("passed-to-thread"); + let hold: Deferred.Deferred | null = null; + const harness = await createHarness({ + beforeThreadRead: (id) => + id === threadId && hold !== null ? Deferred.await(hold) : Effect.void, + }); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-create-passed-to"), + threadId, + projectId: asProjectId("project-1"), + title: "Fix the flaky test", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt: "2026-01-01T00:00:00.000Z", + }), + ); + hold = Effect.runSync(Deferred.make()); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-pass-turn"), + threadId, + message: { + messageId: asMessageId("pass-message"), + role: "user", + text: "Run the migration", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + fromThread: { + threadId: ThreadId.make("lead-thread"), + requestId: ChildRequestId.make("pass-request"), + kind: "request", + ceiling: { + runtimeMode: "approval-required", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + }, + }, + createdAt: "2026-01-01T00:00:01.000Z", + }), + ); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("cmd-raise-passed-to"), + threadId, + runtimeMode: "full-access", + createdAt: "2026-01-01T00:00:02.000Z", + }), + ); + Effect.runSync(Deferred.succeed(hold, undefined)); + hold = null; + + const failure = async () => + (await harness.readModel()).threads + .find((entry) => entry.id === threadId) + ?.activities.find((activity) => activity.kind === "provider.turn.start.failed"); + await waitFor(async () => (await failure()) !== undefined); + expect(await failure()).toMatchObject({ + payload: { detail: expect.stringContaining("more access than the lead chat") }, + }); + expect(harness.sendTurn).not.toHaveBeenCalled(); + // It never reached the agent, so no history will carry it. + const passMessage = async () => + (await harness.readModel()).threads + .find((entry) => entry.id === threadId) + ?.messages.find((entry) => entry.id === asMessageId("pass-message")); + await waitFor(async () => (await passMessage())?.notSent === true); + }); + + it("doesn't send a lead chat's pass marked never sent while its turn was prepared", async () => { + const threadId = ThreadId.make("marked-thread"); + let hold: Deferred.Deferred | null = null; + const harness = await createHarness({ + beforeThreadRead: (id) => + id === threadId && hold !== null ? Deferred.await(hold) : Effect.void, + }); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.create", + commandId: CommandId.make("cmd-create-marked"), + threadId, + projectId: asProjectId("project-1"), + title: "Fix the flaky test", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + branch: null, + worktreePath: null, + createdAt: "2026-01-01T00:00:00.000Z", + }), + ); + hold = Effect.runSync(Deferred.make()); + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make("cmd-marked-pass-turn"), + threadId, + message: { + messageId: asMessageId("pass-message"), + role: "user", + text: "Run the migration", + attachments: [], + }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + fromThread: { + threadId: ThreadId.make("lead-thread"), + requestId: ChildRequestId.make("pass-request"), + kind: "request", + ceiling: { + runtimeMode: "approval-required", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + }, + }, + createdAt: "2026-01-01T00:00:01.000Z", + }), + ); + // A retry accepted just before the mark landed: the mark lands first here. + await Effect.runPromise( + harness.engine.dispatch({ + type: "thread.lead-pass.not-run", + commandId: CommandId.make("cmd-mark-not-run"), + threadId, + messageId: asMessageId("pass-message"), + reason: "ceiling", + createdAt: "2026-01-01T00:00:02.000Z", + }), + ); + Effect.runSync(Deferred.succeed(hold, undefined)); + hold = null; + + const failure = async () => + (await harness.readModel()).threads + .find((entry) => entry.id === threadId) + ?.activities.find((activity) => activity.kind === "provider.turn.start.failed"); + await waitFor(async () => (await failure()) !== undefined); + expect(await failure()).toMatchObject({ + payload: { detail: expect.stringContaining("was never sent") }, + }); + expect(harness.sendTurn).not.toHaveBeenCalled(); + }); }); it("picks up the room tools at the next turn, never in the middle of one", async () => { diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index a3e79fa8e..c052aeeb5 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -33,6 +33,7 @@ import { type OutsideAgentConnectionId, type OutsideAgentRef, type OutsideTurnOrigin, + type LeadPassCeiling, type RuntimeMode, ThreadAccessRaiseDeferredActivityKind, type ThreadAccessRaiseDeferredPayload, @@ -51,7 +52,7 @@ import { import { renderThreadContextSeed, withContextSeedPreamble } from "@threadlines/shared/contextSeed"; import { LEAD_WITHOUT_TOOLS_TEXT, leadRoleText } from "@threadlines/shared/projectLead"; import { agentInvitesMode, agentThreadsMode } from "@threadlines/shared/serverSettings"; -import { notesFor, remoteChildOf } from "@threadlines/shared/childThreads"; +import { notesFor, remoteChildOf, withinModeCeiling } from "@threadlines/shared/childThreads"; import { settingsChangeNotesFor } from "@threadlines/shared/settingsChangeState"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; import { exceedsRuntimeMode, saferRuntimeMode } from "@threadlines/shared/runtimeMode"; @@ -224,6 +225,14 @@ export interface ForkTurnBoundary { readonly lastTurnId?: TurnId; } +/** Why a pass marked never sent did not go when a retry asked for it. */ +const PASS_NOT_SENT_DETAIL = + "This message the lead chat passed on was never sent. Send it yourself to run it."; + +/** Why a lead chat's pass did not go to the agent: the thread's access went above its ceiling. */ +const PASS_ABOVE_CEILING_DETAIL = + "This message the lead chat passed on wasn't sent: this thread has more access than the lead chat now. Send it yourself to run it."; + /** One ensure call's launch mark: its generation and instance, once marked. */ interface SessionLaunch { generation: number | null; @@ -254,6 +263,13 @@ interface EnsureSessionOptions { * on the same read of the thread the session starts from. */ readonly outsideCeiling?: OutsideTurnOrigin; + /** + * The turn is a lead chat's pass (docs/design/lead-chat.md, "Access"): it + * runs only while the thread is within the pass's ceiling, checked on the + * same read of the thread the session starts from, since the user may have + * raised its access after the decider let the pass through. + */ + readonly passCeiling?: LeadPassCeiling; /** * A turn that isn't from outside: an agent outside text reached * (OrchestrationOutsideWork) starts fresh for it, a new runtime with a @@ -1344,6 +1360,14 @@ const make = Effect.gen(function* () { detail: `This message from ${outsideCeiling.name} wasn't sent: the thread's access was raised above what it may use.`, }); } + const passCeiling = options?.passCeiling; + if (passCeiling !== undefined && !withinModeCeiling(thread, passCeiling)) { + return yield* new ProviderAdapterRequestError({ + provider: providerErrorLabel(undefined), + method: "thread.turn.start", + detail: PASS_ABOVE_CEILING_DETAIL, + }); + } const sessionKey = participantSessionKey(threadId, participantId); const shedsOutsideWork = options?.shedOutsideWork === true && @@ -2128,7 +2152,12 @@ const make = Effect.gen(function* () { : undefined) ?? remoteChild?.title ?? "another thread"; - if (fromThread.kind === "request") { + if (fromThread.kind === "request" && fromThread.ceiling !== undefined) { + // A pass (docs/design/lead-chat.md): one-way, from the project's lead. + lines.push( + `The project's lead chat "${otherTitle}" passed this on. It is from another agent, not typed by the user. Your reply stays in this thread, where the user reads it. Do the work here; you can't start threads for it.`, + ); + } else if (fromThread.kind === "request") { lines.push( thread.attachedToParent || fromThread.environmentId !== undefined ? `Another agent started this thread from the thread "${otherTitle}", and your final reply goes back to it automatically. Work in this thread's own checkout, and end with the answer it needs.` @@ -2353,6 +2382,19 @@ const make = Effect.gen(function* () { } const sessionKey = participantSessionKey(input.threadId, input.participantId); + // Read from the stored message, which keeps it for good: a retry or a + // resend of a pass carries no origin on its turn. + const storedMessage = thread.messages.find((message) => message.id === input.messageId); + const passCeiling = storedMessage?.fromThread?.ceiling ?? input.fromThread?.ceiling; + // Marked as never sent while this turn was prepared (a retry the user + // made just before the mark landed): it stays unsent. + if (passCeiling !== undefined && storedMessage?.notSent === true) { + return yield* new ProviderAdapterRequestError({ + provider: providerErrorLabel(undefined), + method: "thread.turn.start", + detail: PASS_NOT_SENT_DETAIL, + }); + } const ensured = yield* ensureSessionForThread(input.threadId, input.createdAt, { participantId: input.participantId, ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), @@ -2360,6 +2402,7 @@ const make = Effect.gen(function* () { preservePendingTurnStartup: true, ...(forkFrom !== undefined ? { forkFrom } : {}), ...(input.fromOutside !== undefined ? { outsideCeiling: input.fromOutside } : {}), + ...(passCeiling !== undefined ? { passCeiling } : {}), ...(input.sentByPerson === true && input.fromOutside === undefined ? { shedOutsideWork: true } : {}), @@ -2385,6 +2428,25 @@ const make = Effect.gen(function* () { detail: `This message from ${input.fromOutside.name} wasn't sent: the agent here still runs with more access than it may use.`, }); } + // A pass goes only to a runtime within its ceiling, in the mode it runs. + if ( + passCeiling !== undefined && + ((activeSession !== undefined && + exceedsRuntimeMode(activeSession.runtimeMode, passCeiling.runtimeMode)) || + !withinModeCeiling( + { + runtimeMode: thread.runtimeMode, + interactionMode: input.interactionMode ?? thread.interactionMode, + }, + passCeiling, + )) + ) { + return yield* new ProviderAdapterRequestError({ + provider: providerErrorLabel(activeSession?.provider), + method: "thread.turn.start", + detail: PASS_ABOVE_CEILING_DETAIL, + }); + } // In a room, what the other agents said and changed since this agent's // conversation was last caught up. Built now, from the thread as it stands // when the turn is sent; the cursor is only kept for the conversation it @@ -3080,13 +3142,34 @@ const make = Effect.gen(function* () { }); }).pipe(Effect.ignoreCause({ log: true })); + // A lead chat's pass refused at the last check never reached the agent: + // the decider marks it so no history carries it, and the lead hears. + const markPassNotRun = (reason: "ceiling" | "stopped") => + Effect.gen(function* () { + yield* orchestrationEngine.dispatch({ + type: "thread.lead-pass.not-run", + commandId: serverCommandId("lead-pass-not-run"), + threadId: event.payload.threadId, + messageId: event.payload.messageId, + reason, + createdAt: yield* nowIso, + }); + }).pipe(Effect.ignoreCause({ log: true })); + + // What else a turn that could not start ends: its hand-off, its pass. + const afterFailedStart = (cause: Cause.Cause) => + Cause.hasInterruptsOnly(cause) + ? Effect.void + : Effect.andThen( + failHandOffForFailedStart(formatFailureDetail(cause)), + formatFailureDetail(cause).includes(PASS_ABOVE_CEILING_DETAIL) + ? markPassNotRun("ceiling") + : Effect.void, + ); + const recoverTurnStartFailure = (cause: Cause.Cause) => handleTurnStartFailure(cause).pipe( - Effect.andThen( - Cause.hasInterruptsOnly(cause) - ? Effect.void - : failHandOffForFailedStart(formatFailureDetail(cause)), - ), + Effect.andThen(afterFailedStart(cause)), Effect.catchCause((recoveryCause) => Effect.logWarning("provider command reactor failed to recover turn start failure", { eventType: event.type, @@ -3124,6 +3207,10 @@ const make = Effect.gen(function* () { messageId: event.payload.messageId, }); yield* dropStart("Stopped before the turn started."); + // A lead chat's pass never ran: marked, so no later history carries it. + if (message.fromThread?.ceiling !== undefined) { + yield* markPassNotRun("stopped"); + } return true; }); @@ -3320,11 +3407,7 @@ const make = Effect.gen(function* () { Effect.map(Option.some), Effect.catchCause((cause) => handleTurnStartFailure(cause).pipe( - Effect.andThen( - Cause.hasInterruptsOnly(cause) - ? Effect.void - : failHandOffForFailedStart(formatFailureDetail(cause)), - ), + Effect.andThen(afterFailedStart(cause)), Effect.as(Option.none()), ), ), @@ -5578,7 +5661,19 @@ const make = Effect.gen(function* () { }), ), ); - return; + // The decider can take a message back instead of starting its turn + // (a cancelled report, a lead chat's pass over its ceiling): then + // the next one goes, as nothing else will move the queue. + const after = yield* resolveThread(threadId); + const takenBack = + after !== undefined && + after.session?.status !== "starting" && + after.session?.status !== "running" && + !(after.queuedFollowUps ?? []).some((queued) => queued.messageId === current); + const next = takenBack ? nextQueuedFollowUp(after) : undefined; + if (next === undefined || next.messageId === current) return; + candidate = next.messageId; + continue; } yield* orchestrationEngine .dispatch({ diff --git a/apps/server/src/orchestration/Normalizer.ts b/apps/server/src/orchestration/Normalizer.ts index 22cebb3a8..a02716a21 100644 --- a/apps/server/src/orchestration/Normalizer.ts +++ b/apps/server/src/orchestration/Normalizer.ts @@ -21,7 +21,7 @@ import { withContextSeedPreamble, } from "@threadlines/shared/contextSeed"; import { agentInvitesMode, agentThreadsMode } from "@threadlines/shared/serverSettings"; -import { transcriptAuthor } from "@threadlines/shared/messageAuthor"; +import { reachedAgent, transcriptAuthor } from "@threadlines/shared/messageAuthor"; import { formatForkSourceExcerpt, truncate } from "@threadlines/shared/String"; import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts"; @@ -276,10 +276,10 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) => // context-seed fallback so the provider never sees both the old and the // edited instruction. Assistant/system anchors still carry the selected // message as background before the new continuation instruction. - const sourceMessages = sourceThread.messages.slice( - 0, - replacesUserPrompt ? selectedIndex : selectedIndex + 1, - ); + // Only what an agent was given: a pass that never ran stays out. + const sourceMessages = sourceThread.messages + .slice(0, replacesUserPrompt ? selectedIndex : selectedIndex + 1) + .filter((message) => reachedAgent(message, sourceThread)); const entries = [ ...sourceMessages.map((message) => ({ kind: "message" as const, diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts index 64bf65bdc..e947a20fb 100644 --- a/apps/server/src/orchestration/Schemas.ts +++ b/apps/server/src/orchestration/Schemas.ts @@ -30,6 +30,7 @@ import { ThreadChildNotesDeliveredPayload as ContractsThreadChildNotesDeliveredPayloadSchema, ThreadChildDeliveriesCancelledPayload as ContractsThreadChildDeliveriesCancelledPayloadSchema, ThreadChildRequestsResetPayload as ContractsThreadChildRequestsResetPayloadSchema, + ThreadLeadPassRecordedPayload as ContractsThreadLeadPassRecordedPayloadSchema, ThreadHandedBackPayload as ContractsThreadHandedBackPayloadSchema, ThreadRemoteCancelQueuedPayload as ContractsThreadRemoteCancelQueuedPayloadSchema, ThreadRemoteCancelsDeliveredPayload as ContractsThreadRemoteCancelsDeliveredPayloadSchema, @@ -125,6 +126,7 @@ export const ThreadChildNotesDeliveredPayload = ContractsThreadChildNotesDeliver export const ThreadChildDeliveriesCancelledPayload = ContractsThreadChildDeliveriesCancelledPayloadSchema; export const ThreadChildRequestsResetPayload = ContractsThreadChildRequestsResetPayloadSchema; +export const ThreadLeadPassRecordedPayload = ContractsThreadLeadPassRecordedPayloadSchema; export const ThreadHandedBackPayload = ContractsThreadHandedBackPayloadSchema; export const ThreadRemoteChildUpdatedPayload = ContractsThreadRemoteChildUpdatedPayloadSchema; export const ThreadRemoteCancelQueuedPayload = ContractsThreadRemoteCancelQueuedPayloadSchema; diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index 81ca8296a..68f5effc3 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -42,6 +42,8 @@ import { isSettingUpChildStart, ownChildRefusal, remoteChildOf, + leadPassRefusal, + withinModeCeiling, } from "@threadlines/shared/childThreads"; import { APPROVAL_ACTIVITY_KINDS, @@ -53,6 +55,7 @@ import { activeParticipants } from "@threadlines/shared/threadParticipants"; import { handOffReplyText } from "./agentRequestDecisions.ts"; import { isProjectLeadThread } from "./commandInvariants.ts"; + import { checkoutSelectedEvents } from "./threadCheckout.ts"; import { currentAgentModel, messageAgentModels } from "./messageAgentModels.ts"; @@ -71,17 +74,6 @@ export type ChildThreadDecision = ReadonlyArray | { readonly refus const refuse = (refusal: string) => ({ refusal }); -/** Whether `child` asks for no more than `ceiling` allows. Plan is narrower than default. */ -export function withinModeCeiling( - child: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode }, - ceiling: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode }, -): boolean { - return ( - !exceedsRuntimeMode(child.runtimeMode, ceiling.runtimeMode) && - (ceiling.interactionMode !== "plan" || child.interactionMode === "plan") - ); -} - /** * A launch narrowed to its parent's access now: a request approved after the * parent's access was lowered starts with the lower access, never the access @@ -511,16 +503,39 @@ export function decideChildRespond( `The user said not now to starting ${quotedList(titles)}. Don't ask again unless the user asks you to.`, ); } - return batch.map((request): PlannedEvent => ({ - ...baseFor(parent.id), - type: "thread.child-request-updated", - payload: { - threadId: parent.id, - requestId: request.requestId, - status: "starting", - updatedAt: command.createdAt, - }, - })); + // Some of the batch, picked on the card: the rest are declined with it. + const picked = command.requestIds === undefined ? undefined : new Set(command.requestIds); + const starting = + picked === undefined ? batch : batch.filter((request) => picked.has(request.requestId)); + if (starting.length === 0) { + return refuse("Pick at least one thread to start, or say not now."); + } + const declined = batch.filter((request) => !starting.includes(request)); + const startedTitles = starting.map((request) => titleOf(readModel, request, parent)); + return [ + ...(declined.length === 0 + ? [] + : settleOpenRequests( + readModel, + baseFor, + parent, + declined, + "declined", + command.createdAt, + (titles) => + `The user started ${quotedList(startedTitles)} but not ${quotedList(titles)}. Don't ask again for those unless the user asks you to.`, + )), + ...starting.map((request): PlannedEvent => ({ + ...baseFor(parent.id), + type: "thread.child-request-updated", + payload: { + threadId: parent.id, + requestId: request.requestId, + status: "starting", + updatedAt: command.createdAt, + }, + })), + ]; } /** A message from an agent to one of its children (`thread.child.send`). */ @@ -678,6 +693,93 @@ export function decideChildSend( ]; } +/** + * The lead chat passes a message to a thread it did not start + * (`thread.lead.pass`, docs/design/lead-chat.md, "A pass"). One-way: the + * message is queued in the target as the lead's, with the lead's access as + * its ceiling, and only the lead's send count is recorded. The tool handler + * checked the same rules first. + */ +export function decideLeadPass( + readModel: OrchestrationReadModel, + lead: OrchestrationThread, + command: CommandOf<"thread.lead.pass">, + baseFor: ChildEventBase, +): ChildThreadDecision { + const target = findThread(readModel, command.targetThreadId); + const refusal = leadPassRefusal(lead, target, { + from: command.from, + callerTurnId: command.callerTurnId, + isLead: isProjectLeadThread(readModel, lead), + }); + if (refusal !== null || target === null) { + return refuse(refusal?.detail ?? "That thread is gone."); + } + if (target.messages.some((message) => message.id === command.messageId)) { + return refuse("That message was already sent."); + } + const ceiling = { runtimeMode: lead.runtimeMode, interactionMode: lead.interactionMode }; + if (!withinModeCeiling(target, ceiling)) { + return refuse( + "That thread has more access than the lead chat, so it can't take work from it. Tell the user, who can send it there.", + ); + } + const fromThread = { + threadId: lead.id, + requestId: command.requestId, + kind: "request" as const, + ceiling, + ...(command.from.participantId !== null && command.from.participantId !== undefined + ? { passedBy: command.from.participantId } + : {}), + }; + return [ + { + ...baseFor(target.id), + type: "thread.message-sent", + payload: { + threadId: target.id, + messageId: command.messageId, + role: "user", + text: command.text, + attachments: [], + fromThread, + turnId: null, + streaming: false, + createdAt: command.createdAt, + updatedAt: command.createdAt, + }, + }, + { + ...baseFor(target.id), + type: "thread.follow-up-queued", + payload: { + threadId: target.id, + followUp: { + messageId: command.messageId, + text: command.text, + attachments: [], + fromThread, + runtimeMode: target.runtimeMode, + interactionMode: target.interactionMode, + createdAt: command.createdAt, + }, + }, + }, + { + ...baseFor(lead.id), + type: "thread.lead-pass-recorded", + payload: { + threadId: lead.id, + kind: "sent", + messageId: command.messageId, + targetThreadId: target.id, + createdAt: command.createdAt, + }, + }, + ]; +} + /** * A message to a child on a linked computer: only the parent's request is * written here. RemoteChildReactor sends it there, where it is queued in the @@ -1751,4 +1853,4 @@ export const isAgentQueued = (queued: { readonly fromThread?: unknown; }) => isAgentOrigin(queued); -export { isAttachedChild }; +export { isAttachedChild, withinModeCeiling }; diff --git a/apps/server/src/orchestration/decider.projectLead.test.ts b/apps/server/src/orchestration/decider.projectLead.test.ts index 99bf3d217..7b4f11adf 100644 --- a/apps/server/src/orchestration/decider.projectLead.test.ts +++ b/apps/server/src/orchestration/decider.projectLead.test.ts @@ -1,6 +1,11 @@ import { + ChildRequestBatchId, + ChildRequestId, CommandId, DEFAULT_PROVIDER_INTERACTION_MODE, + LEAD_PASS_NOT_RUN_ACTIVITY_KIND, + MessageId, + type OrchestrationSession, EMPTY_AGENT_REQUEST_STATE, EMPTY_CHILD_REQUEST_STATE, type OrchestrationCommand, @@ -10,7 +15,9 @@ import { ProjectId, ProviderInstanceId, ThreadId, + TurnId, } from "@threadlines/contracts"; +import { childStartRefusal } from "@threadlines/shared/childThreads"; import { LEAD_MOVE_REFUSAL } from "@threadlines/shared/projectLead"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; @@ -213,3 +220,468 @@ describe("project lead chat", () => { }); }); }); + +const LEAD_TURN = TurnId.make("lead-turn-1"); +const PRIMARY = { participantId: null }; + +function session(threadId: ThreadId, overrides: Partial = {}) { + return { + threadId, + status: "running", + providerName: "claudeAgent", + providerInstanceId: ProviderInstanceId.make("claudeAgent"), + runtimeMode: "auto-accept-edits", + activeTurnId: LEAD_TURN, + lastError: null, + updatedAt: now, + ...overrides, + } satisfies OrchestrationSession; +} + +/** A lead at work, and a thread the user started by hand. */ +async function leadAndHandMade(target: Partial = {}) { + return ( + await run( + readModel([ + thread(LEAD, { session: session(LEAD), runtimeMode: "auto-accept-edits" }), + thread(OTHER, { runtimeMode: "approval-required", ...target }), + ]), + setLead(LEAD), + ) + ).model; +} + +const PASS_MESSAGE = MessageId.make("pass-message-1"); +const pass = ( + overrides: Partial> = {}, +) => + ({ + type: "thread.lead.pass", + commandId: CommandId.make("pass-1"), + threadId: LEAD, + from: PRIMARY, + callerTurnId: LEAD_TURN, + targetThreadId: OTHER, + requestId: ChildRequestId.make("pass-request-1"), + messageId: PASS_MESSAGE, + text: "Fix the flaky checkout test.", + createdAt: now, + ...overrides, + }) satisfies OrchestrationCommand; + +const sendQueued = (messageId: MessageId): OrchestrationCommand => ({ + type: "thread.follow-up.send-queued", + commandId: CommandId.make(`send-${messageId}`), + threadId: OTHER, + messageId, + createdAt: now, +}); + +describe("lead chat passes", () => { + it("queues a pass in a thread the lead did not start, records no request, and runs it there", async () => { + const start = await leadAndHandMade(); + const passed = await run(start, pass()); + const lead = threadIn(passed.model, LEAD); + const target = threadIn(passed.model, OTHER); + expect(lead.childRequests.open).toEqual([]); + expect(lead.childRequests.sendsSinceUser).toBe(1); + const message = target.messages.find((entry) => entry.id === PASS_MESSAGE); + expect(message?.fromThread).toMatchObject({ + threadId: LEAD, + kind: "request", + ceiling: { runtimeMode: "auto-accept-edits" }, + }); + + const ran = await run(passed.model, sendQueued(PASS_MESSAGE)); + expect(ran.events.some((event) => event.type === "thread.turn-start-requested")).toBe(true); + // Nothing is owed back: no request settles anywhere. + expect(ran.events.some((event) => event.type.startsWith("thread.child-request"))).toBe(false); + expect(threadIn(ran.model, OTHER).childRequests.passCeiling).toEqual({ + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + }); + }); + + it("holds what a passed-to thread sends its own threads to the pass's ceiling", async () => { + const RAISED = ThreadId.make("raised-child"); + const ran = ( + await run( + await run( + await leadAndHandMade({ + session: session(OTHER, { status: "ready", activeTurnId: null }), + }), + pass(), + ).then((r) => r.model), + sendQueued(PASS_MESSAGE), + ) + ).model; + const OTHER_TURN = TurnId.make("other-turn-1"); + const own = { parentThreadId: OTHER, attachedToParent: true }; + const working = { + ...ran, + threads: [ + ...ran.threads.map((entry) => + entry.id === OTHER + ? { ...entry, session: session(OTHER, { activeTurnId: OTHER_TURN }) } + : entry, + ), + // The user raised this one above its parent, and above the lead. + thread(RAISED, { ...own, runtimeMode: "full-access" }), + thread(CHILD, { ...own, runtimeMode: "approval-required" }), + ], + }; + const send = (childThreadId: ThreadId): OrchestrationCommand => ({ + type: "thread.child.send", + commandId: CommandId.make(`send-to-${childThreadId}`), + threadId: OTHER, + requestId: ChildRequestId.make(`send-to-${childThreadId}`), + from: PRIMARY, + callerTurnId: OTHER_TURN, + childThreadId, + childMessageId: MessageId.make(`message-to-${childThreadId}`), + text: "Run it with full access.", + createdAt: now, + }); + expect(await refusal(working, send(RAISED))).toContain("more access than the lead chat"); + const within = await run(working, send(CHILD)); + expect(threadIn(within.model, OTHER).childRequests.open).toHaveLength(1); + }); + + it("refuses rooms, threads another thread owns, and threads the user stopped", async () => { + const room = await leadAndHandMade({ + participants: [ + { + id: "agent-1" as never, + handle: "Reviewer", + modelSelection: model, + addedAt: now, + } as never, + ], + }); + expect(await refusal(room, pass())).toContain("Rooms take work from the user"); + const owned = await leadAndHandMade({ parentThreadId: CHILD, attachedToParent: true }); + expect(await refusal(owned, pass())).toContain("Message the thread that started it"); + const stopped = await leadAndHandMade({ + latestTurn: { + turnId: TurnId.make("t"), + state: "interrupted", + requestedAt: now, + startedAt: now, + completedAt: now, + assistantMessageId: null, + }, + }); + expect(await refusal(stopped, pass())).toContain("The user stopped that thread"); + // A thread that is not the lead can't pass anything. + const notLead = (await run(await leadAndHandMade(), setLead(null))).model; + expect(await refusal(notLead, pass())).toContain("not a thread you started"); + }); + + it("takes a pass back when a user message queued ahead widened the thread's access", async () => { + const passed = (await run(await leadAndHandMade(), pass())).model; + // The user raised the thread's access while the pass waited. + const widened = ( + await run(passed, { + type: "thread.runtime-mode.set", + commandId: CommandId.make("widen"), + threadId: OTHER, + runtimeMode: "full-access", + createdAt: now, + }) + ).model; + const sent = await run(widened, sendQueued(PASS_MESSAGE)); + expect(sent.events.some((event) => event.type === "thread.turn-start-requested")).toBe(false); + const target = threadIn(sent.model, OTHER); + expect(target.queuedFollowUps ?? []).toEqual([]); + expect(target.activities.some((entry) => entry.kind === LEAD_PASS_NOT_RUN_ACTIVITY_KIND)).toBe( + true, + ); + expect(threadIn(sent.model, LEAD).childRequests.pendingNotes[0]?.text).toContain("did not run"); + expect(target.messages.find((entry) => entry.id === PASS_MESSAGE)?.notSent).toBe(true); + }); + + it("marks a pass the user took off the queue as never sent", async () => { + const passed = (await run(await leadAndHandMade(), pass())).model; + const unqueued = await run(passed, { + type: "thread.follow-up.unqueue", + commandId: CommandId.make("unqueue-pass"), + threadId: OTHER, + messageId: PASS_MESSAGE, + createdAt: now, + }); + const message = threadIn(unqueued.model, OTHER).messages.find((m) => m.id === PASS_MESSAGE); + expect(message?.notSent).toBe(true); + }); + + it("marks a pass Stop dropped before it started, and says so to the lead", async () => { + const ran = ( + await run( + await run(await leadAndHandMade(), pass()).then((r) => r.model), + sendQueued(PASS_MESSAGE), + ) + ).model; + const stopped = ( + await run(ran, { + type: "thread.lead-pass.not-run", + commandId: CommandId.make("not-run-stopped"), + threadId: OTHER, + messageId: PASS_MESSAGE, + reason: "stopped", + createdAt: now, + }) + ).model; + const target = threadIn(stopped, OTHER); + expect(target.messages.find((entry) => entry.id === PASS_MESSAGE)?.notSent).toBe(true); + expect( + target.activities.find((entry) => entry.kind === LEAD_PASS_NOT_RUN_ACTIVITY_KIND)?.summary, + ).toBe("Not run: this thread was stopped before it started."); + expect(threadIn(stopped, LEAD).childRequests.pendingNotes[0]?.text).toContain( + "the user stopped that thread", + ); + }); + + it("marks a pass refused right before it reached the agent, and never runs it again", async () => { + const ran = ( + await run( + await run(await leadAndHandMade(), pass()).then((r) => r.model), + sendQueued(PASS_MESSAGE), + ) + ).model; + // The provider layer's last check refused it: the thread's access went up. + const refused = await run(ran, { + type: "thread.lead-pass.not-run", + commandId: CommandId.make("not-run"), + threadId: OTHER, + messageId: PASS_MESSAGE, + reason: "ceiling", + createdAt: now, + }); + const target = threadIn(refused.model, OTHER); + expect(target.messages.find((entry) => entry.id === PASS_MESSAGE)?.notSent).toBe(true); + expect(target.activities.some((entry) => entry.kind === LEAD_PASS_NOT_RUN_ACTIVITY_KIND)).toBe( + true, + ); + expect(threadIn(refused.model, LEAD).childRequests.pendingNotes[0]?.text).toContain( + "did not run", + ); + // Said once: a second report changes nothing. + expect( + ( + await run(refused.model, { + type: "thread.lead-pass.not-run", + commandId: CommandId.make("not-run-again"), + threadId: OTHER, + messageId: PASS_MESSAGE, + reason: "stopped", + createdAt: now, + }) + ).events, + ).toEqual([]); + // Back within the ceiling, a retry still doesn't send it. + const failed = { + ...refused.model, + threads: refused.model.threads.map((entry) => + entry.id === OTHER + ? { + ...entry, + session: session(OTHER, { status: "error", activeTurnId: null, lastError: "boom" }), + } + : entry, + ), + }; + expect( + await refusal(failed, { + type: "thread.turn.retry", + commandId: CommandId.make("retry-not-sent"), + threadId: OTHER, + createdAt: now, + }), + ).toContain("was never sent. Send it yourself to run it"); + }); + + it("refuses to retry a pass above its ceiling: the user sends it themselves", async () => { + const ran = ( + await run( + await run(await leadAndHandMade(), pass()).then((r) => r.model), + sendQueued(PASS_MESSAGE), + ) + ).model; + const failed = { + ...ran, + threads: ran.threads.map((entry) => + entry.id === OTHER + ? { + ...entry, + runtimeMode: "full-access" as const, + session: session(OTHER, { status: "error", activeTurnId: null, lastError: "boom" }), + } + : entry, + ), + }; + expect( + await refusal(failed, { + type: "thread.turn.retry", + commandId: CommandId.make("retry"), + threadId: OTHER, + createdAt: now, + }), + ).toContain("Send it yourself to run it"); + }); + + it("retries the failed turn, never a pass still waiting in the queue", async () => { + // The pass waits behind a turn of the user's that then fails. + const userMessage = MessageId.make("user-own"); + const busy = await leadAndHandMade({ + messages: [ + { + id: userMessage, + role: "user", + text: "Mine.", + turnId: null, + streaming: false, + createdAt: now, + updatedAt: now, + }, + ], + }); + const passed = (await run(busy, pass())).model; + const failed = { + ...passed, + threads: passed.threads.map((entry) => + entry.id === OTHER + ? { + ...entry, + session: session(OTHER, { status: "error", activeTurnId: null, lastError: "boom" }), + } + : entry, + ), + }; + const retried = await run(failed, { + type: "thread.turn.retry", + commandId: CommandId.make("retry-own"), + threadId: OTHER, + createdAt: now, + }); + const requested = retried.events.find((event) => event.type === "thread.turn-start-requested"); + expect((requested?.payload as { messageId?: string }).messageId).toBe(userMessage); + expect(threadIn(retried.model, OTHER).queuedFollowUps?.map((entry) => entry.messageId)).toEqual( + [PASS_MESSAGE], + ); + }); + + it("keeps a passed-to thread from starting threads through a continue, until the user writes", async () => { + const ran = ( + await run( + await run(await leadAndHandMade(), pass()).then((r) => r.model), + sendQueued(PASS_MESSAGE), + ) + ).model; + const blocked = (current: OrchestrationReadModel) => + // Asked from inside a turn of its own, as thread_start is. + childStartRefusal( + { ...threadIn(current, OTHER), session: session(OTHER) }, + { from: PRIMARY, callerTurnId: LEAD_TURN, count: 1 }, + ); + const idle = { + ...ran, + threads: ran.threads.map((entry) => + entry.id === OTHER + ? { ...entry, session: session(OTHER, { status: "ready", activeTurnId: null }) } + : entry, + ), + }; + const turn = ( + id: string, + extra: Partial>, + ) => + ({ + type: "thread.turn.start", + commandId: CommandId.make(`turn-${id}`), + threadId: OTHER, + message: { messageId: MessageId.make(id), role: "user", text: id, attachments: [] }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + createdAt: now, + ...extra, + }) satisfies OrchestrationCommand; + const continued = (await run(idle, turn("continue", { trigger: "usageLimitReset" }))).model; + expect(blocked(continued)?.detail).toContain("the lead chat passed on"); + // Nor does a turn no person sent (an automatic fix, a scheduled run). + const automatic = ( + await run( + { + ...continued, + threads: continued.threads.map((entry) => + entry.id === OTHER + ? { ...entry, session: session(OTHER, { status: "ready", activeTurnId: null }) } + : entry, + ), + }, + turn("auto-fix", {}), + ) + ).model; + expect(blocked(automatic)?.detail).toContain("the lead chat passed on"); + const settled = { + ...continued, + threads: continued.threads.map((entry) => + entry.id === OTHER + ? { ...entry, session: session(OTHER, { status: "ready", activeTurnId: null }) } + : entry, + ), + }; + const wrote = (await run(settled, turn("user", { composer: "typed" }))).model; + expect(threadIn(wrote, OTHER).childRequests.passCeiling).toBeUndefined(); + }); + + it("starts only the threads the user left checked, and tells the agent which it didn't", async () => { + const first = ChildRequestId.make("start-1"); + const second = ChildRequestId.make("start-2"); + const asked = ( + await run(readModel([thread(LEAD, { session: session(LEAD) })]), { + type: "thread.child.start", + commandId: CommandId.make("ask"), + threadId: LEAD, + batchId: ChildRequestBatchId.make("batch"), + from: PRIMARY, + callerTurnId: LEAD_TURN, + mode: "ask", + children: [first, second].map((requestId, index) => ({ + requestId, + childThreadId: ThreadId.make(`kid-${index}`), + childMessageId: MessageId.make(`kid-message-${index}`), + launch: { + title: `Task ${index + 1}`, + prompt: "Do it.", + modelSelection: model, + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + reportBack: true, + runSetup: true, + workspace: { kind: "worktree", projectCwd: "/repo", baseRef: "main" }, + }, + })), + createdAt: now, + }) + ).model; + const answered = await run(asked, { + type: "thread.child-request.respond", + commandId: CommandId.make("respond"), + threadId: LEAD, + batchId: ChildRequestBatchId.make("batch"), + choice: "start", + requestIds: [first], + createdAt: now, + }); + const state = threadIn(answered.model, LEAD).childRequests; + expect(state.open.map((request) => [request.requestId, request.status])).toEqual([ + [first, "starting"], + ]); + expect(state.pendingNotes[0]?.text).toContain("but not 'Task 2'"); + }); +}); + +const threadIn = (current: OrchestrationReadModel, id: ThreadId) => { + const found = current.threads.find((entry) => entry.id === id); + if (found === undefined) throw new Error(`no thread ${id}`); + return found; +}; diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts index 05bcd8272..6627c3454 100644 --- a/apps/server/src/orchestration/decider.threadMoves.test.ts +++ b/apps/server/src/orchestration/decider.threadMoves.test.ts @@ -311,6 +311,15 @@ describe("moving a thread to a linked computer", () => { turnId: TurnId.make("moved-turn-1"), createdAt: now, }, + // Never reached the agent there: it stays unsent here. + { + messageId: MessageId.make("moved-message-3"), + role: "user", + text: "Run the migration.", + turnId: null, + notSent: true, + createdAt: now, + }, ], activities: [ { @@ -330,9 +339,12 @@ describe("moving a thread to a linked computer", () => { const arrived = threadOf(after, ARRIVED); expect(arrived.movedFrom).toMatchObject({ label: "Windows PC", threadId: THREAD }); expect(arrived.historySeedOwed).toBe(true); - expect(arrived.messages.map((message) => [message.text, message.imported])).toEqual([ - ["Why does it flake?", true], - ["A timer races the click.", true], + expect( + arrived.messages.map((message) => [message.text, message.imported, message.notSent ?? false]), + ).toEqual([ + ["Why does it flake?", true, false], + ["A timer races the click.", true, false], + ["Run the migration.", true, true], ]); // Tool steps carry no turn of this computer's, so every revert keeps them. expect(arrived.activities.map((activity) => [activity.kind, activity.turnId])).toEqual([ @@ -361,6 +373,7 @@ describe("moving a thread to a linked computer", () => { expect(threadOf(undone, ARRIVED).messages.map((message) => message.text)).toEqual([ "Why does it flake?", "A timer races the click.", + "Run the migration.", "Run the tests", ]); // An undo that keeps it owes nothing. diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index a942e9b99..8bc2dcf7a 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -2,6 +2,7 @@ import { DEFAULT_PROJECT_KIND, EMPTY_AGENT_REQUEST_STATE, EventId, + LEAD_PASS_NOT_RUN_ACTIVITY_KIND, MessageId, type OrchestrationCommand, type OrchestrationContinueAtReset, @@ -48,7 +49,7 @@ import { } from "@threadlines/shared/commandRuns"; import { isTurnAside } from "@threadlines/shared/transcriptRevert"; import { CONTINUE_AT_RESET_MESSAGE, continueAtResetTimeMs } from "@threadlines/shared/usageLimits"; -import { isAttachedChild } from "@threadlines/shared/childThreads"; +import { isAttachedChild, passCeilingRefusal } from "@threadlines/shared/childThreads"; import { leadSetRefusal } from "@threadlines/shared/projectLead"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; @@ -102,6 +103,7 @@ import { decideChildRequestUpdate, decideChildRespond, decideChildSend, + decideLeadPass, decideChildStart, decideChildrenStop, decideParentAttachmentSet, @@ -294,24 +296,139 @@ function childEventBase( }); } -/** The user wrote: the per-message child thread counts start over. */ +/** + * The user wrote: the per-message child thread counts start over, and a + * lead chat's pass no longer blocks starting threads. A turn Threadlines + * started for the user (`keepsPassBlock`: a continue, a restart) resets the + * counts but keeps that block (docs/design/lead-chat.md, "No fan-out"). + */ function resetChildRequestsForUser( thread: OrchestrationThread, base: () => Omit, createdAt: string, + options?: { readonly keepsPassBlock?: boolean }, ): ReadonlyArray { const state = thread.childRequests; - return state.startsSinceUser === 0 && state.sendsSinceUser === 0 + const keepsPassBlock = options?.keepsPassBlock === true; + const liftsBlock = state.passCeiling !== undefined && !keepsPassBlock; + return state.startsSinceUser === 0 && state.sendsSinceUser === 0 && !liftsBlock ? [] : [ { ...base(), type: "thread.child-requests-reset", - payload: { threadId: thread.id, createdAt }, + payload: { + threadId: thread.id, + ...(keepsPassBlock ? { keepsPassBlock: true as const } : {}), + createdAt, + }, }, ]; } +/** + * Whether a person sent this message from the app (they typed it, or their + * signed-in device sent it). Only that lifts a lead chat's pass block: a + * scheduled run, an automatic fix or a continue resets the counts but keeps it. + */ +const personWrote = (command: { + readonly composer?: unknown; + readonly sentFrom?: unknown; +}): boolean => command.composer !== undefined || command.sentFrom !== undefined; + +/** + * A pass whose ceiling is under the thread's access when its turn would + * start (docs/design/lead-chat.md, "Access"): it never runs and its message + * is `notSent`, one line in the thread, and a note for the lead's next turn + * when it is still there. `from` is where it was refused: taken off the + * queue (the unqueue marks it), or after the queue let it go, right before + * it reached the agent (`thread.lead-pass.not-run`). + */ +function passCeilingCancelEvents( + readModel: OrchestrationReadModel, + thread: OrchestrationThread, + queued: { + readonly messageId: MessageId; + readonly fromThread?: OrchestrationMessage["fromThread"]; + }, + refusal: string, + base: () => Omit, + createdAt: string, + from: "queue" | "start" = "queue", + /** Why, in the lead's note: the access went up (default), or the user stopped it. */ + stopped = false, +): PlannedOrchestrationEvent[] { + const origin = queued.fromThread; + const lead = + origin === undefined + ? undefined + : readModel.threads.find((entry) => entry.id === origin.threadId); + return [ + from === "queue" + ? { + ...base(), + type: "thread.follow-up-unqueued", + payload: { + threadId: thread.id, + messageId: queued.messageId, + reason: "cancelled", + createdAt, + }, + } + : { + ...base(), + type: "thread.lead-pass-recorded", + payload: { + threadId: thread.id, + kind: "not-run", + messageId: queued.messageId, + targetThreadId: thread.id, + createdAt, + }, + }, + { + ...base(), + type: "thread.activity-appended", + payload: { + threadId: thread.id, + activity: { + id: EventId.make(crypto.randomUUID()), + tone: "info", + kind: LEAD_PASS_NOT_RUN_ACTIVITY_KIND, + summary: refusal, + payload: { messageId: queued.messageId }, + turnId: null, + createdAt, + }, + }, + }, + ...(lead === undefined || lead.deletedAt !== null || origin === undefined + ? [] + : [ + { + ...base(), + aggregateId: lead.id, + type: "thread.lead-pass-recorded" as const, + payload: { + threadId: lead.id, + kind: "refused" as const, + messageId: queued.messageId, + targetThreadId: thread.id, + note: { + requestId: origin.requestId, + recipient: { participantId: origin.passedBy ?? null }, + text: stopped + ? `The message you passed to "${thread.title}" (thread ${thread.id}) did not run: the user stopped that thread before it started. Tell the user, who can send it there.` + : `The message you passed to "${thread.title}" (thread ${thread.id}) did not run: that thread has more access than this lead chat now. Tell the user, who can send it there.`, + createdAt, + }, + createdAt, + }, + }, + ]), + ]; +} + type DecideOrchestrationCommandResult = | PlannedOrchestrationEvent | ReadonlyArray; @@ -743,7 +860,9 @@ function decideFollowUpSubmit( return withLeadingEvents( [ ...resetAgentRequestsForUser(targetThread, userBase, command.createdAt), - ...resetChildRequestsForUser(targetThread, userBase, command.createdAt), + ...resetChildRequestsForUser(targetThread, userBase, command.createdAt, { + keepsPassBlock: !personWrote(command), + }), ...closedQuestions, ], { @@ -784,7 +903,9 @@ function decideFollowUpSubmit( return withLeadingEvents( [ ...resetAgentRequestsForUser(targetThread, steerBase, command.createdAt), - ...resetChildRequestsForUser(targetThread, steerBase, command.createdAt), + ...resetChildRequestsForUser(targetThread, steerBase, command.createdAt, { + keepsPassBlock: !personWrote(command), + }), ...closedQuestions, ], { @@ -2268,9 +2389,38 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ); } + // Refused right before it reached the agent (the provider reactor's last + // check): marked, said once, and the lead hears on its next turn. + case "thread.lead-pass.not-run": { + const target = yield* requireThread({ readModel, command, threadId: command.threadId }); + const message = target.messages.find((entry) => entry.id === command.messageId); + if (message === undefined || message.fromThread?.ceiling === undefined || message.notSent) { + return []; + } + return passCeilingCancelEvents( + readModel, + target, + { messageId: message.id, fromThread: message.fromThread }, + command.reason === "stopped" + ? "Not run: this thread was stopped before it started." + : "Not run: this thread has more access than the lead chat.", + () => + withEventBase({ + aggregateKind: "thread", + aggregateId: target.id, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + command.createdAt, + "start", + command.reason === "stopped", + ); + } + case "thread.child.start": case "thread.child-request.respond": case "thread.child.send": + case "thread.lead.pass": case "thread.child-request.update": case "thread.child-request.settle": case "thread.child-notes.delivered": @@ -2292,19 +2442,21 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ? decideChildRespond(readModel, thread, command, baseFor) : command.type === "thread.child.send" ? decideChildSend(readModel, thread, command, baseFor) - : command.type === "thread.child-request.update" - ? decideChildRequestUpdate(thread, command, baseFor) - : command.type === "thread.child-request.settle" - ? decideChildRequestSettle(readModel, thread, command, baseFor) - : command.type === "thread.remote-child.update" - ? decideRemoteChildUpdate(thread, command, baseFor) - : command.type === "thread.remote-cancels.delivered" - ? decideRemoteCancelsDelivered(thread, command, baseFor) - : command.type === "thread.remote-request.queue" - ? decideRemoteRequestQueue(thread, command, baseFor) - : command.type === "thread.remote-handed-back.record" - ? decideRemoteHandedBackRecord(thread, command, baseFor) - : decideChildNotesDelivered(thread, command, baseFor), + : command.type === "thread.lead.pass" + ? decideLeadPass(readModel, thread, command, baseFor) + : command.type === "thread.child-request.update" + ? decideChildRequestUpdate(thread, command, baseFor) + : command.type === "thread.child-request.settle" + ? decideChildRequestSettle(readModel, thread, command, baseFor) + : command.type === "thread.remote-child.update" + ? decideRemoteChildUpdate(thread, command, baseFor) + : command.type === "thread.remote-cancels.delivered" + ? decideRemoteCancelsDelivered(thread, command, baseFor) + : command.type === "thread.remote-request.queue" + ? decideRemoteRequestQueue(thread, command, baseFor) + : command.type === "thread.remote-handed-back.record" + ? decideRemoteHandedBackRecord(thread, command, baseFor) + : decideChildNotesDelivered(thread, command, baseFor), ); } @@ -3003,6 +3155,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" detail: "The request this turn answers was cancelled.", }); } + // A lead chat's pass never starts above the access it was passed with. + const passStartRefusal = passCeilingRefusal(command, targetThread); + if (passStartRefusal !== null) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: passStartRefusal, + }); + } // An outside agent's turn (docs/design/outside-agents.md): only in a // thread it started (any thread at Work), never above its ceiling, // never into a busy thread (an answer's own turn passes over its @@ -3329,12 +3489,34 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }, ] : []; + // A lead chat's pass starting its turn: until the user writes, no + // threads may be started from here, and its ceiling holds what this + // thread sends on (docs/design/lead-chat.md, "No fan-out"). + const passCeiling = command.fromThread?.ceiling; + const passStartedEvents: ReadonlyArray = + passCeiling !== undefined + ? [ + { + ...turnBase(), + type: "thread.lead-pass-recorded", + payload: { + threadId: command.threadId, + kind: "started", + messageId: command.message.messageId, + targetThreadId: command.threadId, + ceiling: passCeiling, + createdAt: command.createdAt, + }, + }, + ] + : []; return [ userMessageEvent, ...(titleSeedEvent ? [titleSeedEvent] : []), ...(startingSessionEvent ? [startingSessionEvent] : []), turnStartRequestedEvent, ...requestRunningEvents, + ...passStartedEvents, // The user wrote: agents may make requests again. (A queued message // sent later drops these; it counted when the user queued it.) An // agent's message, another thread's or an outside agent's, is not @@ -3342,7 +3524,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ...(command.fromThread === undefined && command.fromOutside === undefined ? [ ...resetAgentRequestsForUser(targetThread, turnBase, command.createdAt), - ...resetChildRequestsForUser(targetThread, turnBase, command.createdAt), + ...resetChildRequestsForUser(targetThread, turnBase, command.createdAt, { + keepsPassBlock: command.trigger !== undefined || !personWrote(command), + }), ...settleCandidateBeforeUserTurn(readModel, targetThread, command), ] : []), @@ -3379,7 +3563,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" // What sits beside a turn (an invite, an invited review, a message // steered into it while it ran) is never the turn's own message, so it // is never what a retry sends again. - const turnMessages = targetThread.messages.filter((message) => !isTurnAside(message)); + // Nor is a message still waiting in the queue: it hasn't run yet, and + // runs from there in its turn. + const queuedIds = new Set( + (targetThread.queuedFollowUps ?? []).map((queued) => queued.messageId), + ); + const turnMessages = targetThread.messages.filter( + (message) => !isTurnAside(message) && !queuedIds.has(message.id), + ); if (!session || (command.type === "thread.turn.retry" && session.lastError === null)) { return yield* new OrchestrationCommandInvariantError({ commandType: command.type, @@ -3416,6 +3607,26 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" detail: `This message came from ${lastUserMessage.fromOutside.name}, outside Threadlines. Ask it to send it again, or write it yourself.`, }); } + // A message that never reached the agent stays out of its history for + // good (OrchestrationMessage.notSent), so it never runs from here. + if (lastUserMessage.notSent === true) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: + lastUserMessage.fromThread?.ceiling !== undefined + ? "This message the lead chat passed on was never sent. Send it yourself to run it." + : "This message was never sent. Write it again to send it.", + }); + } + // A lead chat's pass runs again only within the access it was passed + // with; above it, the user sends it themselves. + const retryPassRefusal = passCeilingRefusal(lastUserMessage, targetThread); + if (retryPassRefusal !== null) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: `${retryPassRefusal} Send it yourself to run it.`, + }); + } // A failed turn is retried with the agent that failed it: the slot // still holds that agent's session. const retryParticipantId = sessionSlotParticipantId(session); @@ -3494,6 +3705,28 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" return [ retrySessionEvent, retryTurnStartRequestedEvent, + // A lead chat's pass, run again: still held to its ceiling. + ...(lastUserMessage.fromThread?.ceiling !== undefined + ? [ + { + ...withEventBase({ + aggregateKind: "thread", + aggregateId: command.threadId, + occurredAt: command.createdAt, + commandId: command.commandId, + }), + type: "thread.lead-pass-recorded" as const, + payload: { + threadId: command.threadId, + kind: "started" as const, + messageId: lastUserMessage.id, + targetThreadId: command.threadId, + ceiling: lastUserMessage.fromThread.ceiling, + createdAt: command.createdAt, + }, + }, + ] + : []), ...resetAgentRequestsForUser( targetThread, () => @@ -3741,6 +3974,20 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ) { return [{ ...unqueuedEvent, payload: { ...unqueuedEvent.payload, reason: "cancelled" } }]; } + // A lead chat's pass runs only within the lead's access as it was when + // passed. A user message queued ahead may have widened the thread's + // access since; then the pass is taken back instead. + const passRefusal = passCeilingRefusal(queued, targetThread); + if (passRefusal !== null) { + return passCeilingCancelEvents( + readModel, + targetThread, + queued, + passRefusal, + sendBase, + command.createdAt, + ); + } // A message an agent queued carries no model: its agent's current one // applies (the thread's own model for the thread's own agent), so a // model change since it was queued is honored. diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index b9cb1ccfd..202163b6e 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -108,6 +108,7 @@ import { ThreadChildRequestSubmittedPayload, ThreadChildRequestUpdatedPayload, ThreadChildRequestsResetPayload, + ThreadLeadPassRecordedPayload, ThreadHandedBackPayload, ThreadRemoteCancelQueuedPayload, ThreadRemoteCancelsDeliveredPayload, @@ -992,10 +993,41 @@ export function projectEvent( "payload", ).pipe( Effect.map((payload) => - updateChildRequests(nextBase, payload.threadId, childRequestStateOn.reset), + updateChildRequests(nextBase, payload.threadId, (state) => + childRequestStateOn.reset(state, payload), + ), ), ); + case "thread.lead-pass-recorded": + return decodeForEvent( + ThreadLeadPassRecordedPayload, + event.payload, + event.type, + "payload", + ).pipe( + Effect.map((payload) => { + const next = updateChildRequests(nextBase, payload.threadId, (state) => + childRequestStateOn.leadPass(state, payload), + ); + // Refused right before it reached the agent: the message never ran. + if (payload.kind !== "not-run") return next; + const thread = next.threads.find((entry) => entry.id === payload.threadId); + return thread === undefined + ? next + : { + ...next, + threads: updateThread(next.threads, payload.threadId, { + messages: thread.messages.map((message) => + message.id === payload.messageId + ? { ...message, notSent: true as const } + : message, + ), + }), + }; + }), + ); + case "thread.remote-child-updated": return decodeForEvent( ThreadRemoteChildUpdatedPayload, @@ -1362,6 +1394,7 @@ export function projectEvent( ...(payload.composer !== undefined ? { composer: payload.composer } : {}), ...(payload.sentFrom !== undefined ? { sentFrom: payload.sentFrom } : {}), ...(payload.trigger !== undefined ? { trigger: payload.trigger } : {}), + ...(payload.notSent === true ? { notSent: true as const } : {}), ...(payload.afterMove === true ? { afterMove: true as const } : {}), turnId: payload.turnId, streaming: payload.streaming, @@ -1401,7 +1434,9 @@ export function projectEvent( ...(entry.trigger === undefined && message.trigger !== undefined ? { trigger: message.trigger } : {}), - ...(entry.notSent === true ? { notSent: true as const } : {}), + ...(entry.notSent === true || message.notSent === true + ? { notSent: true as const } + : {}), ...(entry.afterMove === true || message.afterMove === true ? { afterMove: true as const } : {}), diff --git a/apps/server/src/orchestration/roomCatchUp.test.ts b/apps/server/src/orchestration/roomCatchUp.test.ts index c30dc97c5..4ac0d498e 100644 --- a/apps/server/src/orchestration/roomCatchUp.test.ts +++ b/apps/server/src/orchestration/roomCatchUp.test.ts @@ -1,9 +1,11 @@ import { CheckpointRef, + ChildRequestId, MessageId, ProviderInstanceId, RoomAgentRequestId, SideTurnId, + ThreadId, ThreadParticipantId, TurnId, type OrchestrationMessage, @@ -209,6 +211,38 @@ describe("buildRoomCatchUp", () => { expect(note).toContain(`message ${ROOM_JOIN_MESSAGE_COUNT + 2}`); }); + it("leaves a lead chat's pass that never ran out of a joining agent's note", () => { + const ceiling = { runtimeMode: "approval-required", interactionMode: "default" } as const; + const pass = (id: string, text: string, extra: Partial = {}) => + message(id, "user", text, null, { + fromThread: { + threadId: ThreadId.make("lead"), + requestId: ChildRequestId.make(`request-${id}`), + kind: "request", + ceiling, + }, + ...extra, + }); + const note = buildRoomCatchUp({ + thread: thread( + [ + pass("ran", "passed on and done"), + pass("refused", "passed on, refused at its ceiling", { notSent: true }), + pass("waiting", "passed on, still waiting"), + message("now", "user", "astra, take a look", astraId), + ], + { queuedFollowUps: [{ messageId: "waiting" }] }, + ), + participantId: astraId, + messageId: MessageId.make("now"), + ...main, + })?.note; + + expect(note).toContain("passed on and done"); + expect(note).not.toContain("refused at its ceiling"); + expect(note).not.toContain("still waiting"); + }); + it("delivers a side exchange that landed before the agent's own reply", () => { const sideTurnId = SideTurnId.make("0d9e8f7a-6b5c-4d3e-8f1a-2b3c4d5e6f70"); const messages = [ diff --git a/apps/server/src/orchestration/roomCatchUp.ts b/apps/server/src/orchestration/roomCatchUp.ts index f23768b13..855429a2b 100644 --- a/apps/server/src/orchestration/roomCatchUp.ts +++ b/apps/server/src/orchestration/roomCatchUp.ts @@ -29,7 +29,7 @@ import type { import { isRoomThread } from "@threadlines/shared/threadParticipants"; -import { messageAuthor } from "@threadlines/shared/messageAuthor"; +import { messageAuthor, reachedAgent } from "@threadlines/shared/messageAuthor"; import { handOffReplyText } from "./agentRequestDecisions.ts"; /** Messages an agent joining late gets verbatim. */ @@ -45,6 +45,8 @@ export interface RoomCatchUpInput { readonly agentRole?: string | undefined; readonly participants: ReadonlyArray; readonly messages: ReadonlyArray; + /** What still waits to be sent: kept out of the note (`reachedAgent`). */ + readonly queuedFollowUps?: ReadonlyArray<{ readonly messageId: string }> | undefined; readonly checkpoints: ReadonlyArray; }; /** The agent the turn is for. Null: the thread's own agent. */ @@ -209,7 +211,9 @@ export function buildRoomCatchUp(input: RoomCatchUpInput): RoomCatchUp | undefin (message) => message.id !== input.messageId && (message.role === "user" || message.role === "assistant") && - message.text.trim().length > 0, + message.text.trim().length > 0 && + // Only what an agent was given: a pass that never ran stays out. + reachedAgent(message, thread), ); const ownerOf = (message: OrchestrationMessage) => message.participantId ?? null; // A reply arrives as the message below the note. The words it was taken diff --git a/apps/server/src/outsideAgents/connectToolHandlers.ts b/apps/server/src/outsideAgents/connectToolHandlers.ts index 93113ef72..9f9986d37 100644 --- a/apps/server/src/outsideAgents/connectToolHandlers.ts +++ b/apps/server/src/outsideAgents/connectToolHandlers.ts @@ -307,7 +307,7 @@ export interface ConnectToolDeps { export type ConnectProject = Pick< OrchestrationProjectCatalogEntry, "id" | "kind" | "title" | "workspaceRoot" ->; +> & { readonly leadThreadId?: ThreadId | null | undefined }; type Refusal = { readonly outcome: "limit" | "not_allowed"; @@ -748,6 +748,7 @@ export const makeConnectToolHandlers = ( projectId: project.id, name: project.title, folder: assistant ? lastPathSegment(project.workspaceRoot) : project.workspaceRoot, + ...(project.leadThreadId != null ? { leadThreadId: project.leadThreadId } : {}), })), } satisfies ProjectsResult; }); diff --git a/apps/server/src/outsideAgents/connectTools.ts b/apps/server/src/outsideAgents/connectTools.ts index 8bfb9599e..d8971b457 100644 --- a/apps/server/src/outsideAgents/connectTools.ts +++ b/apps/server/src/outsideAgents/connectTools.ts @@ -129,7 +129,13 @@ export const ProjectsResult = Schema.Struct({ detail: Detail, retryAfterSeconds: RetryAfter, projects: Schema.Array( - Schema.Struct({ projectId: Schema.String, name: Schema.String, folder: Schema.String }), + Schema.Struct({ + projectId: Schema.String, + name: Schema.String, + folder: Schema.String, + /** The project's lead chat: send work for the project there. Absent: none. */ + leadThreadId: Schema.optional(Schema.String), + }), ), }); export type ProjectsResult = typeof ProjectsResult.Type; diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index e815b4b96..35d4964cf 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -16,5 +16,5 @@ "show_page" ], "upFrontToolDefinitionBytes": 16834, - "onDemandToolDefinitionBytes": 48382 + "onDemandToolDefinitionBytes": 48765 } diff --git a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts index efcb2081c..2b3e2adb1 100644 --- a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts +++ b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts @@ -196,6 +196,40 @@ describe("ThreadContextSeedBuilder", () => { expect(value.entries.map((entry) => entry.text)).toEqual(["previous context"]); }); + it("holds only messages an agent was given: never a queued or not-sent pass", async () => { + const thread = { + ...fakeThread( + [ + { id: "ran", role: "user", text: "passed on, ran", createdAt: "2026-01-01T00:00:00Z" }, + // A room hand-off that ran, later cancelled with its agent: it was given. + { + id: "hand-off", + role: "user", + text: "hand-off that ran", + requestOutcome: "cancelled", + createdAt: "2026-01-01T00:00:01Z", + } as FakeMessage, + { id: "queued", role: "user", text: "still waiting", createdAt: "2026-01-01T00:00:02Z" }, + { + id: "refused", + role: "user", + text: "refused at its ceiling", + notSent: true, + createdAt: "2026-01-01T00:00:03Z", + } as FakeMessage, + { id: "current", role: "user", text: "switch now", createdAt: "2026-01-01T00:00:04Z" }, + ], + [], + ), + queuedFollowUps: [{ messageId: "queued" }], + } as unknown as OrchestrationThread; + const seed = await build({ thread, excludeMessageId: "current" }); + expect(Option.getOrThrow(seed).entries.map((entry) => entry.text)).toEqual([ + "passed on, ran", + "hand-off that ran", + ]); + }); + it("returns a workspace-only seed when the thread detail read fails", async () => { const seed = await build({ thread: null, diff --git a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts index 00e01db5f..d3b56df05 100644 --- a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts +++ b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts @@ -28,7 +28,7 @@ import { type SeedBudget, splitSeedEntriesByBudget, } from "@threadlines/shared/contextSeed"; -import { transcriptAuthor } from "@threadlines/shared/messageAuthor"; +import { reachedAgent, transcriptAuthor } from "@threadlines/shared/messageAuthor"; import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -107,6 +107,9 @@ function buildEntries(input: { readonly text: string; readonly attachments?: ReadonlyArray<{ readonly name: string }> | undefined; readonly fromOutside?: OrchestrationMessage["fromOutside"]; + readonly fromThread?: OrchestrationMessage["fromThread"]; + readonly fromAgent?: OrchestrationMessage["fromAgent"]; + readonly notSent?: true | undefined; readonly createdAt: string; }>; readonly activities: ReadonlyArray<{ @@ -115,6 +118,11 @@ function buildEntries(input: { readonly createdAt: string; }>; readonly excludeMessageId?: string | undefined; + /** Whether an agent was given the message (`reachedAgent`): history holds only those. */ + readonly reachedAgent: (message: { + readonly id: string; + readonly notSent?: true | undefined; + }) => boolean; }): ReadonlyArray { const items: Array<{ readonly createdAt: string; readonly entry: ThreadContextSeedEntry }> = []; @@ -122,6 +130,9 @@ function buildEntries(input: { if (message.id !== undefined && message.id === input.excludeMessageId) { continue; } + if (message.id !== undefined && !input.reachedAgent({ ...message, id: message.id })) { + continue; + } const attached = (message.attachments ?? []).map((attachment) => attachment.name); const text = [ message.text.trim(), @@ -191,6 +202,7 @@ export const makeThreadContextSeedBuilder = (deps: { messages: thread.messages, activities: thread.activities, excludeMessageId: input.excludeMessageId, + reachedAgent: (message) => reachedAgent(message, thread), }); if (entries.length === 0 && pointer === undefined) { diff --git a/apps/server/src/pullRequest/PullRequestObservations.test.ts b/apps/server/src/pullRequest/PullRequestObservations.test.ts index 22a30b2b9..4d824541f 100644 --- a/apps/server/src/pullRequest/PullRequestObservations.test.ts +++ b/apps/server/src/pullRequest/PullRequestObservations.test.ts @@ -130,4 +130,29 @@ describe("PullRequestObservations", () => { assert.strictEqual(first[0]?.number, 7); }), ); + + it.effect("finds a branch's pull request only in the same repository on the same host", () => + Effect.gen(function* () { + const observations = yield* make; + const gitlab = (path: string, number: number): PullRequestRead => + read({ + provider: "gitlab", + repository: path, + number, + url: `https://gitlab.com/${path}/-/merge_requests/${number}`, + }); + yield* observations.observe(Effect.succeed(1), () => [ + gitlab("org/app", 1), + gitlab("org/public/app", 2), + read({ number: 3, url: "https://ghe.example.com/org/app/pull/3", repository: "org/app" }), + ]); + const numbersAt = (repositoryKey: string) => + observations + .known({ repositoryKey, branch: "fix-it", urls: [] }) + .pipe(Effect.map((known) => known.map((entry) => entry.number))); + assert.deepStrictEqual(yield* numbersAt("gitlab.com/org/public/app"), [2]); + assert.deepStrictEqual(yield* numbersAt("gitlab.com/org/app"), [1]); + assert.deepStrictEqual(yield* numbersAt("github.com/org/app"), []); + }), + ); }); diff --git a/apps/server/src/pullRequest/PullRequestObservations.ts b/apps/server/src/pullRequest/PullRequestObservations.ts index c0d180c8f..e260a3049 100644 --- a/apps/server/src/pullRequest/PullRequestObservations.ts +++ b/apps/server/src/pullRequest/PullRequestObservations.ts @@ -19,6 +19,7 @@ import type { PullRequestState, SourceControlProviderKind, } from "@threadlines/contracts"; +import { normalizeGitRemoteUrl } from "@threadlines/shared/git"; import { pullRequestIdentityKey } from "@threadlines/shared/sourceControl"; import * as Clock from "effect/Clock"; import * as Context from "effect/Context"; @@ -167,6 +168,17 @@ export interface PullRequestObservationsShape { ) => Effect.Effect, E, R>; /** Every record kept, oldest change first, then each change as it lands. */ readonly stream: Stream.Stream; + /** + * What is already known about a thread's pull requests, with no call to the + * host: the one from its branch in the repository at `repositoryKey` (its + * remote's host and whole path, RepositoryIdentity.canonicalKey), and the + * ones at `urls`. Pull requests nobody has read yet are left out. + */ + readonly known: (input: { + readonly repositoryKey: string | null; + readonly branch: string | null; + readonly urls: ReadonlyArray; + }) => Effect.Effect>; } export class PullRequestObservations extends Context.Service< @@ -239,7 +251,26 @@ export const make = Effect.gen(function* () { }), ); - return { observe, stream } satisfies PullRequestObservationsShape; + const known: PullRequestObservationsShape["known"] = (input) => + Ref.get(state).pipe( + Effect.map((current) => { + // Matched on the address, host and whole path, so another host's or + // another group's `owner/name` with the same branch never answers. + const repositoryPrefix = + input.repositoryKey === null ? null : `${input.repositoryKey.toLowerCase()}/`; + const urls = new Set(input.urls); + return Array.from(current.records.values(), (entry) => entry.observation).filter( + (observation) => + urls.has(observation.url) || + (repositoryPrefix !== null && + input.branch !== null && + observation.headBranch === input.branch && + normalizeGitRemoteUrl(observation.url).startsWith(repositoryPrefix)), + ); + }), + ); + + return { observe, stream, known } satisfies PullRequestObservationsShape; }); export const layer = Layer.effect(PullRequestObservations, make); diff --git a/apps/server/src/threads/threadOperations.ts b/apps/server/src/threads/threadOperations.ts index ed07e175a..5babd5883 100644 --- a/apps/server/src/threads/threadOperations.ts +++ b/apps/server/src/threads/threadOperations.ts @@ -277,6 +277,10 @@ export const summarizeThread = ( readonly titleOf: (threadId: ThreadId) => string | undefined; /** Threads a scheduled-task card waits in (ScheduledTasks.waitingThreadIds). */ readonly scheduleAnswerWaiting?: ReadonlySet; + /** The project's lead chat, when it has one (docs/design/lead-chat.md). */ + readonly leadThreadId?: ThreadId | null; + /** Its pull requests as already known; see AgentThreadSummary.pullRequests. */ + readonly pullRequests?: ThreadSummary["pullRequests"]; }, ): ThreadSummary => { const remoteOrigin = thread.remoteOrigin ?? null; @@ -301,6 +305,12 @@ export const summarizeThread = ( ? "you" : (input.titleOf(thread.parentThreadId) ?? thread.parentThreadId), ...(input.caller !== undefined && thread.id === input.caller.id ? { you: true } : {}), + ...((input.leadThreadId ?? null) === thread.id ? { lead: true } : {}), + lastActivityAt: + thread.latestTurn?.completedAt ?? thread.latestTurn?.startedAt ?? thread.updatedAt, + ...(input.pullRequests !== undefined && input.pullRequests.length > 0 + ? { pullRequests: input.pullRequests } + : {}), }; }; @@ -464,6 +474,7 @@ export function readThreadPage( origin, ...text, ...(message.streaming ? { streaming: true } : {}), + ...(message.notSent === true ? { notSent: true } : {}), }; }; const wanted = input.messageId?.trim(); diff --git a/apps/web/src/components/ChatView.agents.browser.tsx b/apps/web/src/components/ChatView.agents.browser.tsx index 768125632..064561ff0 100644 --- a/apps/web/src/components/ChatView.agents.browser.tsx +++ b/apps/web/src/components/ChatView.agents.browser.tsx @@ -1120,6 +1120,9 @@ describe("ChatView (full app): agent browser tabs and rooms", () => { ); expect(neverMadeReport?.querySelector("button[data-thread-message-author]")).toBeNull(); + // This server can't take a partial answer: no checkboxes, and Start + // answers for the whole batch. + expect(panel.querySelector('[data-slot="checkbox"]')).toBeNull(); [...panel.querySelectorAll("button")] .find((button) => button.textContent === "Start") ?.click(); @@ -1134,6 +1137,106 @@ describe("ChatView (full app): agent browser tabs and rooms", () => { ).toMatchObject({ batchId, choice: "start" }), { timeout: 8_000, interval: 16 }, ); + const respond = wsRequests.find( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + (request as { type?: string }).type === "thread.child-request.respond", + ) as { requestIds?: unknown } | undefined; + expect(respond?.requestIds).toBeUndefined(); + } finally { + await mounted.cleanup(); + } + }); + + it("starts only the threads left checked, where the server takes a partial answer", async () => { + const base = createSnapshotForTargetUser({ + targetMessageId: "msg-user-child-select" as MessageId, + targetText: "child select target", + }); + const batchId = ChildRequestBatchId.make("batch-select"); + const capabilities = { repositoryIdentity: true, childStartSelection: true }; + const ask = (index: number, title: string) => ({ + requestId: ChildRequestId.make(`request-select-${index}`), + batchId, + kind: "start" as const, + from: { participantId: null }, + callerTurnId: "turn-select" as TurnId, + deliveryEpoch: 0, + status: "awaiting_user" as const, + childThreadId: `thread-child-select-${index}` as ThreadId, + childMessageId: `msg-child-select-${index}` as MessageId, + launch: { + title, + prompt: `${title}.`, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, + runtimeMode: "full-access" as const, + interactionMode: "default" as const, + reportBack: true, + runSetup: true, + workspace: { kind: "project_folder" as const }, + }, + createdAt: isoAt(301), + }); + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + environment: { ...nextFixture.serverConfig.environment, capabilities }, + }; + nextFixture.welcome = { + ...nextFixture.welcome, + environment: { ...nextFixture.welcome.environment, capabilities }, + }; + }, + snapshot: { + ...base, + threads: base.threads.map((thread) => + thread.id === THREAD_ID + ? { + ...thread, + childRequests: { + ...EMPTY_CHILD_REQUEST_STATE, + startsSinceUser: 3, + open: [ + ask(1, "Fix the flaky test"), + ask(2, "Update the docs"), + ask(3, "Bump the version"), + ], + }, + } + : thread, + ), + }, + }); + try { + const panel = await waitForElement( + () => document.querySelector('[data-testid="child-threads-panel"]'), + "Unable to find the approval card.", + ); + const startButton = () => + [...panel.querySelectorAll("button")].find((button) => + button.textContent?.startsWith("Start"), + ); + expect(startButton()?.textContent).toBe("Start all"); + await page.getByRole("checkbox", { name: "Start Update the docs" }).click(); + await vi.waitFor(() => expect(startButton()?.textContent).toBe("Start 2")); + startButton()?.click(); + await vi.waitFor( + () => + expect( + wsRequests.find( + (request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + (request as { type?: string }).type === "thread.child-request.respond", + ), + ).toMatchObject({ + batchId, + choice: "start", + requestIds: ["request-select-1", "request-select-3"], + }), + { timeout: 8_000, interval: 16 }, + ); } finally { await mounted.cleanup(); } diff --git a/apps/web/src/components/chat/ComposerChildThreadsPanel.tsx b/apps/web/src/components/chat/ComposerChildThreadsPanel.tsx index 9a35406f1..d33ce207c 100644 --- a/apps/web/src/components/chat/ComposerChildThreadsPanel.tsx +++ b/apps/web/src/components/chat/ComposerChildThreadsPanel.tsx @@ -6,7 +6,9 @@ import type { PendingChildThreads } from "~/childThreads"; import { readEnvironmentApi } from "~/environmentApi"; import { cn, newCommandId } from "~/lib/utils"; import { formatChildThreadCount } from "../Sidebar.logic"; +import { readEnvironmentDescriptor } from "~/environments/runtime"; import { Button } from "../ui/button"; +import { Checkbox } from "../ui/checkbox"; import { failureNotice, toastManager } from "../ui/toast"; import { addComputerNotConnectedNotice } from "../computerConnectionNotices"; import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; @@ -44,6 +46,17 @@ export const ComposerChildThreadsPanel = memo(function ComposerChildThreadsPanel const { request } = props; const [responding, setResponding] = useState(false); const [showPrompts, setShowPrompts] = useState(false); + // Several threads: each can be left out, where the thread's server can + // take a partial answer (an older one would start the whole batch). + const selectable = + request.threads.length > 1 && + readEnvironmentDescriptor(props.threadRef.environmentId)?.capabilities.childStartSelection === + true; + const [unchecked, setUnchecked] = useState>(() => new Set()); + const checkedIds = request.threads + .map((thread) => thread.requestId) + .filter((requestId) => !unchecked.has(requestId)); + const allChecked = checkedIds.length === request.threads.length; const respond = async (choice: "start" | "decline") => { const api = readEnvironmentApi(props.threadRef.environmentId); @@ -62,6 +75,7 @@ export const ComposerChildThreadsPanel = memo(function ComposerChildThreadsPanel threadId: props.threadRef.threadId, batchId: request.batchId, choice, + ...(choice === "start" && selectable && !allChecked ? { requestIds: checkedIds } : {}), createdAt: new Date().toISOString(), }); } catch (error) { @@ -98,7 +112,31 @@ export const ComposerChildThreadsPanel = memo(function ComposerChildThreadsPanel )} data-testid="child-threads-panel-thread" > - {thread.title} + {selectable ? ( + { + setUnchecked((current) => { + const updated = new Set(current); + if (next) updated.delete(thread.requestId); + else updated.add(thread.requestId); + return updated; + }); + }} + /> + ) : null} + + {thread.title} + void respond("start")} > - Start + {!selectable ? "Start" : allChecked ? "Start all" : `Start ${checkedIds.length}`} diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 5722403d5..153306a04 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -3250,7 +3250,16 @@ function ThreadMessageTimelineRow({ } /> - {message.requestOutcome === "cancelled" ? ( + {message.notSent === true ? ( + // A lead chat's pass that never reached the agent; the line in the + // thread below says why. +

+ Not sent +

+ ) : message.requestOutcome === "cancelled" ? (

+ childRequestStateOn.reset(current, event.payload), + ); + + case "thread.lead-pass-recorded": { + const next = updateChildRequestState(state, event.payload.threadId, (current) => + childRequestStateOn.leadPass(current, event.payload), + ); + // Refused right before it reached the agent: the message never ran. + return event.payload.kind !== "not-run" + ? next + : updateThreadState(next, event.payload.threadId, (thread) => ({ + ...thread, + messages: thread.messages.map((message) => + message.id === event.payload.messageId + ? { ...message, notSent: true as const } + : message, + ), + })); + } // Agents' settings changes (docs/design/agent-settings-changes.md), // folded through the reducer the server's projector uses. diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index adb5e1d2d..05ceae88e 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -140,7 +140,7 @@ export interface ChatMessage { sentFrom?: MessageSentFrom | undefined; /** See OrchestrationMessage.trigger: why Threadlines sent it for the user. */ trigger?: MessageTrigger | undefined; - /** See OrchestrationMessage.notSent: the user wrote first, so it never went. */ + /** See OrchestrationMessage.notSent: it never reached the agent (a continue the user overtook, a pass refused). */ notSent?: true | undefined; /** * See OrchestrationMessage.imported: brought over when the thread moved diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md index eceb837ba..254489aac 100644 --- a/docs/design/lead-chat.md +++ b/docs/design/lead-chat.md @@ -217,7 +217,22 @@ coordinate it. without passing through either, decider.ts ~3350). If the target then has more access than the ceiling (`withinModeCeiling`), the message does not run: one line in the target ("Not run: this thread has more access than the lead chat"), and a - note to the lead on its next turn. A retry by the user is refused the same way, + note to the lead on its next turn. The provider layer checks the ceiling once more + right before the turn goes to the agent (the user may raise access after the + decision), against the thread and the live runtime, as it does for outside agents; + a pass refused there fails its turn with a line saying so. A pass that never + reached the agent is `notSent` (OrchestrationMessage.notSent): taken back at the + queue, taken off it by the user, or dropped after the queue let it go + (`thread.lead-pass.not-run`: refused at that last check, or stopped while its turn + was prepared; it also writes the line and the lead's note). The mark moves with + the thread to another computer. No history an agent is given includes a + `notSent` or still-queued message (`reachedAgent`: the hand-off seed, a fork's + context, a room's catch-up note); `thread_read` and `room_history` keep it, + labelled. A pass that did run is never called the user's in that history: the + hand-off seed and a fork's context name a message another agent wrote as that + agent's (`transcriptAuthor`), as `thread_read` and `room_history` already did. + It is never retried or resent ("Send it yourself to run it."), and it + says "Not sent" on screen. A retry by the user is refused the same way, with "Send it yourself to run it." The user's thread's access is never changed. - **No fan-out.** Once a pass starts its turn in a thread, that thread cannot call `thread_start` until the user writes there ("This thread is working on something @@ -225,7 +240,10 @@ coordinate it. Without this, one message in a lead on Automatic could start threads through every thread it passes to. It is a fact on the thread, not on the turn, so a retry or a continue of that work cannot shed it. `thread_send` to that thread's own children - still works. + still works, held to the pass's ceiling: a child with more access than the lead, + or one on another computer, is refused ("Do the work here, or tell the user, who + can send it there."). The check is at send time; after that, only the user can + raise a child's access. - A pass counts against the lead's sends per user message. - What the target does with it is the target's business: the user's own queued messages go first; Stop, taking the message off the queue, revert and archive work @@ -234,7 +252,9 @@ coordinate it. a thread it did not start. - **`thread_list`** summaries gain optional fields: `lead` (true on the lead), `lastActivityAt`, `pullRequests` (`number`, `url`, and `state` when the server already - holds an observation; no network call). Every agent sees which thread is the lead. + holds an observation; no network call; a branch's pull request is matched on the + project remote's host and whole path, never on `owner/name` alone). Every agent sees + which thread is the lead. - **Limits in a lead:** 10 starts and 20 sends per user message (5 and 10 elsewhere); 5 per call stays. A scheduled or event run into the lead already counts as the user writing (`thread.follow-up.submit` resets the counters), so a lead fed by an event @@ -299,11 +319,23 @@ the user. Your reply stays in this thread, where the user reads it." emits `turn-start-requested` for a stored message (`thread.turn.start`, `thread.follow-up.send-queued`, `thread.turn.retry`, `thread.turn.resend`), reading the ceiling from the message itself. -- No fan-out is state: optional `startsBlockedByPass?: true` on the target's - `OrchestrationChildRequestState`, set by the decision that starts a pass's turn and - cleared by `thread.child-requests-reset` (the user wrote). `childStartRefusal` reads - it; `childSendRefusal` does not (both call `callerRefusal`, so the rule cannot live - there). +- No fan-out is state: optional `passCeiling` on the target's + `OrchestrationChildRequestState`, the narrowest ceiling of the passes that started + turns there since the user wrote. The decision that starts a pass's turn sets it + (its `started` record carries the ceiling); `thread.child-requests-reset` clears it + (the user wrote). `childStartRefusal` refuses while it is set; `childSendRefusal` + refuses a child above it or on another computer (both call `callerRefusal`, so the + rule cannot live there). +- Built (piece 2): the lead's send count, the refusal note and the "started" mark ride + one event, `thread.lead-pass-recorded` (`kind`: `sent` on the lead, `refused` with + the note on the lead, `started` on the target), so nothing settles a request that + does not exist. The note goes to the lead's agent that passed it + (`fromThread.passedBy` in a room). The block lifts only when a person writes + (`composer` or `sentFrom` on the turn or the queued message); a continue, a restart, + a scheduled run or an automatic fix reset the counts with `keepsPassBlock`. A target + whose last turn failed is refused like a stopped one, since its queue is held the + same way. Retry never picks a message still waiting in the queue, and the queue + moves on when the decider takes a message back instead of starting its turn. - A pass does not stamp `handed-back` and emits no `child-request-settled`, so the target's wrap rules and "done" alert are untouched (the alert rule cancels on every `child-request-settled`, pushAlertRules.ts). diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 86185951e..81da68b50 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -200,6 +200,12 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ * would refuse the command, so clients hide the lead actions for them. */ projectLead: Schema.optionalKey(Schema.Boolean), + /** + * The approval card for starting several threads can start some of them + * (`thread.child-request.respond` `requestIds`). An older server would start + * the whole batch, so clients only show the checkboxes for this one. + */ + childStartSelection: Schema.optionalKey(Schema.Boolean), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index d1467dca4..19dc9247e 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -465,6 +465,8 @@ export const OrchestrationProjectCatalogEntry = Schema.Struct({ kind: ProjectKind.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROJECT_KIND))), title: TrimmedNonEmptyString, workspaceRoot: TrimmedNonEmptyString, + /** The project's lead chat, when it has an open one (docs/design/lead-chat.md). */ + leadThreadId: Schema.optional(ThreadId), createdAt: IsoDateTime, updatedAt: IsoDateTime, deletedAt: Schema.NullOr(IsoDateTime), @@ -610,6 +612,16 @@ export type AgentInvitesMode = typeof AgentInvitesMode.Type; export const AgentThreadsMode = Schema.Literals(["off", "ask", "auto"]); export type AgentThreadsMode = typeof AgentThreadsMode.Type; +/** + * The most a lead chat's pass may run with (docs/design/lead-chat.md, + * "Access"): the lead's access and interaction mode when it passed it. + */ +export const LeadPassCeiling = Schema.Struct({ + runtimeMode: RuntimeMode, + interactionMode: ProviderInteractionMode, +}); +export type LeadPassCeiling = typeof LeadPassCeiling.Type; + /** * A message that crossed between a thread and one it started: a `request` its * parent's agent wrote into the child, or a `report`, the child's answer @@ -635,6 +647,17 @@ export const ThreadMessageOrigin = Schema.Struct({ * With no child to check, only Stop or a wrap (the delivery epoch) cancels it. */ neverMade: Schema.optional(Schema.Boolean), + /** + * A pass (docs/design/lead-chat.md): the project's lead chat passed this + * message into a thread it did not start. The lead's access and interaction + * mode when it passed it, kept on the message for good: every decision that + * starts a turn from it refuses when the thread has more access by then. + * Nothing is owed back for a pass: no request is recorded on the lead. + * Only a pass carries it. + */ + ceiling: Schema.optional(LeadPassCeiling), + /** A pass: the lead's agent that passed it (a room's agent), for its notes. Absent: its own. */ + passedBy: Schema.optional(ThreadParticipantId), }); export type ThreadMessageOrigin = typeof ThreadMessageOrigin.Type; @@ -1252,8 +1275,11 @@ export const OrchestrationMessage = Schema.Struct({ /** See MessageTrigger. Written with the message and kept. */ trigger: Schema.optional(MessageTrigger), /** - * A message Threadlines wrote for the user (`trigger`) that never reached - * the agent: the user wrote before it went, and theirs went instead. + * A message that never reached the agent, kept in the chat: a continue + * Threadlines wrote for the user (`trigger`) that the user's own message + * overtook, or a lead chat's pass that was taken back or refused at its + * ceiling. Once set, kept. No history an agent is given includes it + * (`reachedAgent`), and it is never retried. */ notSent: Schema.optional(Schema.Literal(true)), /** @@ -1356,6 +1382,13 @@ export type ThreadCheckoutSwitchDeferredPayload = typeof ThreadCheckoutSwitchDef * turn is refused (CheckpointRevert). */ export const ThreadCheckoutMovedActivityKind = "thread.checkout.moved"; + +/** + * A lead chat's pass that never ran here: its turn would have started with + * more access than the lead had when it passed it (docs/design/lead-chat.md, + * "Access"). Payload `{ messageId }`; the summary is the line the chat shows. + */ +export const LEAD_PASS_NOT_RUN_ACTIVITY_KIND = "lead-chat.pass-not-run"; export const ThreadCheckoutMovedPayload = Schema.Struct({ /** The thread whose checkout it moved into, with its title then. */ ownerThreadId: ThreadId, @@ -2720,6 +2753,14 @@ export const OrchestrationChildRequestState = Schema.Struct({ remoteChildren: Schema.optional(Schema.Array(RemoteChildThread)), /** Cancels still owed to linked computers, oldest first. Absent: none. */ remoteCancels: Schema.optional(Schema.Array(RemoteChildCancel)), + /** + * A message the lead chat passed on started a turn here since the user + * last wrote (docs/design/lead-chat.md, "No fan-out"): the narrowest + * ceiling of those passes. Until the user writes here, this thread's agents + * can't start threads, and message only their own threads that are within + * it on this computer. Absent: no pass holds them. + */ + passCeiling: Schema.optional(LeadPassCeiling), }); export type OrchestrationChildRequestState = typeof OrchestrationChildRequestState.Type; @@ -4061,6 +4102,12 @@ const ThreadChildRequestRespondCommand = Schema.Struct({ threadId: ThreadId, batchId: ChildRequestBatchId, choice: Schema.Literals(["start", "decline"]), + /** + * With `start`: only these of the batch start, and the rest are declined in + * the same answer (capability `childStartSelection`). Absent: the whole + * batch. + */ + requestIds: Schema.optional(Schema.Array(ChildRequestId)), createdAt: IsoDateTime, }); @@ -4954,6 +5001,42 @@ const ThreadChildSendCommand = Schema.Struct({ createdAt: IsoDateTime, }); +/** + * The project's lead chat passes a message into a thread it did not start + * (docs/design/lead-chat.md, "A pass"). Server only, from `thread_send`. + * One-way: the message lands in `targetThreadId` as the lead's, and nothing + * is recorded on the lead but its send count. `requestId` names the pass + * (`fromThread.requestId` on the message); `ceiling` is the lead's access. + */ +const ThreadLeadPassCommand = Schema.Struct({ + type: Schema.Literal("thread.lead.pass"), + commandId: CommandId, + threadId: ThreadId, + from: RoomAgentRef, + callerTurnId: TurnId, + targetThreadId: ThreadId, + requestId: ChildRequestId, + messageId: MessageId, + text: TrimmedNonEmptyString, + createdAt: IsoDateTime, +}); + +/** + * A lead chat's pass never went to the agent after the queue let it go: the + * thread's access was raised above its ceiling, or Stop landed, while its + * turn was prepared (docs/design/lead-chat.md, "Access"). Server only, from + * the provider reactor. `threadId` is the thread it was passed to. + */ +const ThreadLeadPassNotRunCommand = Schema.Struct({ + type: Schema.Literal("thread.lead-pass.not-run"), + commandId: CommandId, + threadId: ThreadId, + messageId: MessageId, + /** `ceiling`: its access went above the pass's. `stopped`: Stop landed while it was prepared. */ + reason: Schema.Literals(["ceiling", "stopped"]), + createdAt: IsoDateTime, +}); + /** Child threads: a request moved on (set up, its turn started, background wait). */ const ThreadChildRequestUpdateCommand = Schema.Struct({ type: Schema.Literal("thread.child-request.update"), @@ -5428,6 +5511,8 @@ const InternalOrchestrationCommand = Schema.Union([ ThreadNativeSessionFallBackCommand, ThreadChildStartCommand, ThreadChildSendCommand, + ThreadLeadPassCommand, + ThreadLeadPassNotRunCommand, ThreadChildRequestUpdateCommand, ThreadChildRequestSettleCommand, ThreadChildNotesDeliveredCommand, @@ -5523,6 +5608,7 @@ export const OrchestrationEventType = Schema.Literals([ "thread.child-notes-delivered", "thread.child-deliveries-cancelled", "thread.child-requests-reset", + "thread.lead-pass-recorded", "thread.remote-child-updated", "thread.remote-cancel-queued", "thread.remote-cancels-delivered", @@ -6002,6 +6088,38 @@ export const ThreadChildDeliveriesCancelledPayload = Schema.Struct({ /** The user wrote: the per-message child thread counts start over. */ export const ThreadChildRequestsResetPayload = Schema.Struct({ threadId: ThreadId, + /** + * A turn Threadlines started for the user (a continue at the reset, after a + * restart or an account switch), not the user writing: the counts start + * over, but a pass's block on starting threads stays. + */ + keepsPassBlock: Schema.optional(Schema.Literal(true)), + createdAt: IsoDateTime, +}); + +/** + * The lead chat's passes (docs/design/lead-chat.md, "A pass"). On the lead: + * `sent` counts one toward its sends since the user wrote; `refused` (the + * passed message could not run, its ceiling was over) leaves `note` for the + * lead's next turn. On the thread passed to: `started` (the pass started its + * turn there) blocks its agents from starting threads until the user writes. + */ +export const ThreadLeadPassRecordedPayload = Schema.Struct({ + threadId: ThreadId, + /** + * `sent`, `refused` (with the lead's `note`): on the lead. `started`: the + * pass started its turn in the target. `not-run`: on the target, the pass + * was refused right before it went to the agent, so its message is + * `notSent`. (One taken off the queue is marked by that, see + * withUnqueuedAgentMessage.) + */ + kind: Schema.Literals(["sent", "refused", "started", "not-run"]), + /** The pass's message, in the thread it was passed to. */ + messageId: MessageId, + targetThreadId: ThreadId, + note: Schema.optional(ChildRequestNote), + /** `started`: the pass's ceiling, which now holds the target (`passCeiling`). */ + ceiling: Schema.optional(LeadPassCeiling), createdAt: IsoDateTime, }); @@ -6100,6 +6218,8 @@ export const ThreadMessageSentPayload = Schema.Struct({ streaming: Schema.Boolean, /** See OrchestrationMessage.imported. */ imported: Schema.optional(Schema.Literal(true)), + /** See OrchestrationMessage.notSent: an imported message that never reached the agent there. */ + notSent: Schema.optional(Schema.Literal(true)), /** See OrchestrationMessage.afterMove. */ afterMove: Schema.optional(Schema.Literal(true)), /** Missing means legacy behavior for events written before assistant @@ -6674,6 +6794,11 @@ export const OrchestrationEvent = Schema.Union([ type: Schema.Literal("thread.child-requests-reset"), payload: ThreadChildRequestsResetPayload, }), + Schema.Struct({ + ...EventBaseFields, + type: Schema.Literal("thread.lead-pass-recorded"), + payload: ThreadLeadPassRecordedPayload, + }), Schema.Struct({ ...EventBaseFields, type: Schema.Literal("thread.remote-child-updated"), diff --git a/packages/contracts/src/peerRpc.ts b/packages/contracts/src/peerRpc.ts index a2cb23850..ee28ca8f9 100644 --- a/packages/contracts/src/peerRpc.ts +++ b/packages/contracts/src/peerRpc.ts @@ -71,6 +71,23 @@ export const AgentThreadSummary = Schema.Struct({ you: Schema.optional(Schema.Boolean), /** The linked computer it runs on; absent: this one. */ computer: Schema.optional(Schema.String), + /** Its project's lead chat (docs/design/lead-chat.md). */ + lead: Schema.optional(Schema.Boolean), + /** When its work last moved: its latest turn, else its last change. */ + lastActivityAt: Schema.optional(Schema.String), + /** + * Its pull requests, as this computer already knows them (no call to the + * host): `state` where a read has said. + */ + pullRequests: Schema.optional( + Schema.Array( + Schema.Struct({ + number: Schema.Number, + url: Schema.String, + state: Schema.optional(Schema.Literals(["open", "merged", "closed"])), + }), + ), + ), }); export type AgentThreadSummary = typeof AgentThreadSummary.Type; @@ -100,6 +117,8 @@ export const AgentThreadReadResult = Schema.Struct({ /** Read by `messageId`: pass as `offset` to read on. Absent: `text` reaches the end. */ nextOffset: Schema.optional(Schema.Number), streaming: Schema.optional(Schema.Boolean), + /** It never reached that thread's agent (OrchestrationMessage.notSent): shown, never acted on. */ + notSent: Schema.optional(Schema.Boolean), }), ), /** Pass as `after` later for only newer messages; null when there are none. */ diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts index f8d508f03..c657845c8 100644 --- a/packages/shared/src/childThreads.ts +++ b/packages/shared/src/childThreads.ts @@ -18,16 +18,22 @@ import { type RemoteChildCancel, type RemoteChildRequest, type FamilyRemoteChild, + type LeadPassCeiling, type RemoteChildStart, type RemoteChildThread, type RemoteThreadFiling, type RoomAgentRef, type LocalChildStart, + type ProviderInteractionMode, + type RuntimeMode, type ThreadId, type ThreadParticipantId, type TurnId, } from "@threadlines/contracts"; +import { exceedsRuntimeMode, saferRuntimeMode } from "./runtimeMode.ts"; +import { isRoomThread } from "./threadParticipants.ts"; + /** What the rules read from a thread an agent works in. */ export interface ChildRequestCaller { readonly id: ThreadId; @@ -127,6 +133,17 @@ export function childStartRefusal( if (caller !== null) { return caller; } + // No fan-out (docs/design/lead-chat.md): one message in a lead chat must + // not start threads through every thread it is passed to. Messaging this + // thread's own children still works, within the pass's ceiling + // (childSendRefusal). + if (thread.childRequests.passCeiling !== undefined) { + return { + outcome: "not_allowed", + detail: + "This thread is working on something the lead chat passed on. Do the work here, or say what should be started.", + }; + } if (input.count < 1 || input.count > CHILD_THREADS_PER_CALL) { return { outcome: "refused", @@ -144,7 +161,11 @@ export function childStartRefusal( return null; } -/** Why sending a message to `childThreadId` is refused, or null. */ +/** + * Why sending a message to `childThreadId` is refused, or null. `child`'s + * modes are absent for a thread on another computer, whose access this + * computer can't hold to a pass's ceiling. + */ export function childSendRefusal( thread: ChildRequestCaller, child: { @@ -152,6 +173,8 @@ export function childSendRefusal( readonly parentThreadId: ThreadId | null; readonly attachedToParent: boolean; readonly archivedAt: string | null; + readonly runtimeMode?: RuntimeMode | undefined; + readonly interactionMode?: ProviderInteractionMode | undefined; } | null, input: { readonly from: RoomAgentRef; @@ -168,6 +191,30 @@ export function childSendRefusal( if (ownRefusal !== null) { return ownRefusal; } + // Work the lead chat passed on keeps its ceiling when it is handed down: + // a pass never reaches a thread with more access than the lead's. + const passCeiling = thread.childRequests.passCeiling; + if (passCeiling !== undefined && child !== null) { + if (child.runtimeMode === undefined || child.interactionMode === undefined) { + return { + outcome: "not_allowed", + detail: + "This thread is working on something the lead chat passed on, and that thread is on another computer. Do the work here, or tell the user, who can send it there.", + }; + } + if ( + !withinModeCeiling( + { runtimeMode: child.runtimeMode, interactionMode: child.interactionMode }, + passCeiling, + ) + ) { + return { + outcome: "not_allowed", + detail: + "This thread is working on something the lead chat passed on, and that thread has more access than the lead chat. Do the work here, or tell the user, who can send it there.", + }; + } + } const limit = childRequestLimits({ isLead: input.isLead === true }).sends; if (thread.childRequests.sendsSinceUser >= limit) { return { @@ -244,6 +291,161 @@ export function childAttachRefusal( return null; } +/** Whether `child` asks for no more than `ceiling` allows. Plan is narrower than default. */ +export function withinModeCeiling( + child: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode }, + ceiling: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode }, +): boolean { + return ( + !exceedsRuntimeMode(child.runtimeMode, ceiling.runtimeMode) && + (ceiling.interactionMode !== "plan" || child.interactionMode === "plan") + ); +} + +/** The narrower of two ceilings: no more access than either allows. */ +export function narrowerModeCeiling( + left: LeadPassCeiling | undefined, + right: LeadPassCeiling, +): LeadPassCeiling { + if (left === undefined) return right; + const narrower = { + runtimeMode: saferRuntimeMode(left.runtimeMode, right.runtimeMode), + interactionMode: + left.interactionMode === "plan" || right.interactionMode === "plan" + ? ("plan" as const) + : ("default" as const), + }; + return narrower.runtimeMode === left.runtimeMode && + narrower.interactionMode === left.interactionMode + ? left + : narrower; +} + +/** + * What a `started` record without a ceiling holds the thread to: the least + * access there is. Every decision that records one sends the pass's ceiling. + */ +const SAFEST_PASS_CEILING: LeadPassCeiling = { + runtimeMode: "approval-required", + interactionMode: "plan", +}; + +/** What the pass rules read from the thread a lead chat passes a message to. */ +export interface LeadPassTarget { + readonly id: ThreadId; + readonly projectId: string; + readonly parentThreadId: ThreadId | null; + readonly attachedToParent: boolean; + readonly archivedAt: string | null; + readonly deletedAt?: string | null | undefined; + readonly participants: Parameters[0]["participants"]; + readonly remoteOrigin?: unknown; + readonly outsideOrigin?: unknown; + readonly move?: unknown; + readonly pendingMove?: unknown; + readonly agentRequests: { readonly hold: boolean }; + readonly latestTurn: { readonly state: string } | null; +} + +/** + * Why the project's lead chat may not pass a message to `target`, a thread it + * did not start (docs/design/lead-chat.md, "Tools"), or null. The caller has + * already sent a thread it started down the child path. `isLead` is whether + * the caller is its project's lead chat now. + */ +export function leadPassRefusal( + lead: ChildRequestCaller & { readonly projectId: string }, + target: LeadPassTarget | null, + input: { + readonly from: RoomAgentRef; + readonly callerTurnId: TurnId; + readonly isLead: boolean; + }, +): ChildRequestRefusal | null { + const caller = callerRefusal(lead, input); + if (caller !== null) { + return caller; + } + if (!input.isLead) { + return { + outcome: "not_allowed", + detail: "That is not a thread you started. You can only message or stop your own threads.", + }; + } + if (target === null || (target.deletedAt ?? null) !== null) { + return { outcome: "refused", detail: "That thread is gone." }; + } + if (target.id === lead.id) { + return { outcome: "refused", detail: "That is this thread." }; + } + if (target.projectId !== lead.projectId) { + return { outcome: "refused", detail: "That thread is in another project." }; + } + if (target.archivedAt !== null) { + return { outcome: "refused", detail: "That thread is archived." }; + } + if (isAttachedChild(target)) { + return { + outcome: "not_allowed", + detail: + "Another thread started that one and still owns it. Message the thread that started it.", + }; + } + if (isRoomThread(target)) { + return { outcome: "not_allowed", detail: "Rooms take work from the user." }; + } + if ((target.remoteOrigin ?? null) !== null || (target.outsideOrigin ?? null) !== null) { + return { + outcome: "not_allowed", + detail: "That thread was started from another computer or by an outside agent.", + }; + } + if ((target.move ?? null) !== null || (target.pendingMove ?? null) !== null) { + return { outcome: "refused", detail: "That thread is moving to another computer." }; + } + // What it was last told to stop doing, or failed at, holds its queue until + // the user writes there: a pass would sit there unseen. + if (target.agentRequests.hold || target.latestTurn?.state === "interrupted") { + return { + outcome: "refused", + detail: "The user stopped that thread. It takes work again once they write there.", + }; + } + if (target.latestTurn?.state === "error") { + return { + outcome: "refused", + detail: "That thread's last turn failed. It takes work again once the user writes there.", + }; + } + const limit = childRequestLimits({ isLead: true }).sends; + if (lead.childRequests.sendsSinceUser >= limit) { + return { + outcome: "limit", + detail: `The lead chat can send ${limit} messages to threads per user message, and that many were sent since the user last wrote, so this one was not. Say so in your reply, and wait for the user before sending more.`, + }; + } + return null; +} + +/** + * Why a stored message can't start a turn in `thread` now: it is a pass whose + * ceiling is under the thread's access at this moment. Every decision that + * starts a turn from a stored message asks (send-queued, retry, resend). + */ +export function passCeilingRefusal( + message: { + readonly fromThread?: + | { readonly ceiling?: Parameters[1] | undefined } + | undefined; + }, + thread: Parameters[0], +): string | null { + const ceiling = message.fromThread?.ceiling; + return ceiling === undefined || withinModeCeiling(thread, ceiling) + ? null + : "Not run: this thread has more access than the lead chat."; +} + /** Requests whose answers are still owed, as the parent's sidebar row counts them. */ export const awaitedChildRequestCount = (state: OrchestrationChildRequestState): number => state.open.filter((request) => request.status !== "awaiting_user").length; @@ -536,10 +738,60 @@ export const childRequestStateOn = { deliveryEpoch: number, ): OrchestrationChildRequestState => state.deliveryEpoch === deliveryEpoch ? state : { ...state, deliveryEpoch }, - reset: (state: OrchestrationChildRequestState): OrchestrationChildRequestState => - state.startsSinceUser === 0 && state.sendsSinceUser === 0 - ? state - : { ...state, startsSinceUser: 0, sendsSinceUser: 0 }, + /** + * The user wrote (or, with `keepsPassBlock`, Threadlines started a turn for + * them): the per-message counts start over, and unless kept, a pass's + * block on starting threads lifts. + */ + reset: ( + state: OrchestrationChildRequestState, + options?: { readonly keepsPassBlock?: boolean | undefined }, + ): OrchestrationChildRequestState => { + const liftsBlock = state.passCeiling !== undefined && options?.keepsPassBlock !== true; + if (state.startsSinceUser === 0 && state.sendsSinceUser === 0 && !liftsBlock) { + return state; + } + const { passCeiling: _block, ...rest } = state; + return { + ...(liftsBlock ? rest : state), + startsSinceUser: 0, + sendsSinceUser: 0, + }; + }, + /** The lead chat's passes (`thread.lead-pass-recorded`); see its payload. */ + leadPass: ( + state: OrchestrationChildRequestState, + pass: { + readonly kind: "sent" | "refused" | "started" | "not-run"; + readonly note?: ChildRequestNote | undefined; + readonly ceiling?: LeadPassCeiling | undefined; + }, + ): OrchestrationChildRequestState => { + switch (pass.kind) { + case "sent": + return { ...state, sendsSinceUser: state.sendsSinceUser + 1 }; + // Its mark is on the message, not on the thread's requests. + case "not-run": + return state; + case "started": { + const passCeiling = narrowerModeCeiling( + state.passCeiling, + pass.ceiling ?? SAFEST_PASS_CEILING, + ); + return passCeiling === state.passCeiling ? state : { ...state, passCeiling }; + } + case "refused": { + const note = pass.note; + return note === undefined || + state.pendingNotes.some((entry) => entry.requestId === note.requestId) + ? state + : { + ...state, + pendingNotes: [...state.pendingNotes, note].slice(-CHILD_REQUEST_NOTE_LIMIT), + }; + } + } + }, }; /** diff --git a/packages/shared/src/contextSeed.test.ts b/packages/shared/src/contextSeed.test.ts index 7b5a82c04..590e6441d 100644 --- a/packages/shared/src/contextSeed.test.ts +++ b/packages/shared/src/contextSeed.test.ts @@ -1,6 +1,8 @@ import { + ChildRequestId, OutsideAgentConnectionId, ProviderDriverKind, + ThreadId, type ThreadContextSeedEntry, } from "@threadlines/contracts"; import { describe, expect, it } from "vite-plus/test"; @@ -88,6 +90,27 @@ describe("renderSeedEntries with authors", () => { expect(rendered).toContain("**Claude Code (outside agent):** Fix it"); expect(rendered).toContain("**User:** Thanks"); }); + + it("never calls another agent's message the user's", () => { + const fromThread = { + threadId: ThreadId.make("thread-lead"), + requestId: ChildRequestId.make("request-1"), + }; + expect(transcriptAuthor({ role: "user", fromThread: { ...fromThread, kind: "request" } })).toBe( + "Agent in another thread (request)", + ); + expect(transcriptAuthor({ role: "user", fromThread: { ...fromThread, kind: "report" } })).toBe( + "Agent in another thread (report)", + ); + expect(transcriptAuthor({ role: "user", fromAgent: { participantId: null } })).toBe( + "Another agent in this thread", + ); + // The user's own words, and an agent's reply, keep their role's name. + expect(transcriptAuthor({ role: "user" })).toBeUndefined(); + expect( + transcriptAuthor({ role: "assistant", fromThread: { ...fromThread, kind: "report" } }), + ).toBeUndefined(); + }); }); describe("renderThreadContextSeed", () => { diff --git a/packages/shared/src/messageAuthor.ts b/packages/shared/src/messageAuthor.ts index c2ff72333..0049d2e28 100644 --- a/packages/shared/src/messageAuthor.ts +++ b/packages/shared/src/messageAuthor.ts @@ -41,15 +41,47 @@ export const outsideAgentAuthor = (agent: { readonly name: string }): string => /** * The name a transcript handed to an agent gives a message instead of its - * role's ("User"), or undefined to keep the role's: an outside agent's - * message carries the agent's name. + * role's ("User"), or undefined to keep the role's. A user-role message some + * agent wrote is never called the user's: an outside agent's carries its + * name, another thread's agent's says so (a parent's request, a lead chat's + * pass, a child's report), and so does one from another agent in the thread. + * A transcript has no names to look up, so the last two are general. */ export function transcriptAuthor( - message: Pick, + message: Pick, ): string | undefined { - return message.role === "user" && message.fromOutside !== undefined - ? outsideAgentAuthor(message.fromOutside) - : undefined; + if (message.role !== "user") { + return undefined; + } + if (message.fromOutside !== undefined) { + return outsideAgentAuthor(message.fromOutside); + } + if (message.fromThread !== undefined) { + return message.fromThread.kind === "request" + ? "Agent in another thread (request)" + : "Agent in another thread (report)"; + } + return message.fromAgent !== undefined ? "Another agent in this thread" : undefined; +} + +/** + * Whether an agent was given this message, so history may include it: not + * `notSent` (never reached the agent), and not still waiting in the thread's + * queue (an agent's message is written into the chat when it is queued). + * Every history handed to an agent filters through this (context seeds, a + * fork's context, a room's catch-up note); explicit reads (`thread_read`, + * `room_history`) keep the message and label it instead. + */ +export function reachedAgent( + message: { readonly id: string; readonly notSent?: true | undefined }, + thread: { + readonly queuedFollowUps?: ReadonlyArray<{ readonly messageId: string }> | undefined; + }, +): boolean { + return ( + message.notSent !== true && + !(thread.queuedFollowUps ?? []).some((queued) => queued.messageId === message.id) + ); } /** The message's author line and origin. */ @@ -63,9 +95,8 @@ export function messageAuthor( if (message.role !== "user") { return { author: names.agentName(message.participantId), origin: "agent" }; } - const outside = transcriptAuthor(message); - if (outside !== undefined) { - return { author: outside, origin: "user" }; + if (message.fromOutside !== undefined) { + return { author: outsideAgentAuthor(message.fromOutside), origin: "user" }; } if (message.fromThread !== undefined) { return message.fromThread.kind === "request" diff --git a/packages/shared/src/projectLead.ts b/packages/shared/src/projectLead.ts index bcd2ab5bf..3e902bc39 100644 --- a/packages/shared/src/projectLead.ts +++ b/packages/shared/src/projectLead.ts @@ -87,9 +87,9 @@ export function leadRoleText(projectTitle: string): string { return [ `This thread is the lead chat for the project "${projectTitle}". The user drops work here and you coordinate it.`, "- Answer quick questions yourself. Do not change files in this thread.", - '- For work, call thread_list with scope "project" first. If a thread you started already works in that area, send it the message with thread_send. Otherwise start one thread per independent task with thread_start, each with a brief that stands on its own.', + '- For work, call thread_list with scope "project" first. If an open thread already works in that area, pass the message on with thread_send. Otherwise start one thread per independent task with thread_start, each with a brief that stands on its own.', "- Say in a line or two what went where. When a report comes back, tell the user what finished and what needs them. Do not repeat the report.", - "- Threads you started report back by themselves. Do not poll them.", + "- Threads you started report back by themselves. Do not poll them. A thread you did not start does not report back: the user sees its answer there.", ].join("\n"); } diff --git a/packages/shared/src/roomAgentRequests.ts b/packages/shared/src/roomAgentRequests.ts index e68cdddf8..faf2b3c8e 100644 --- a/packages/shared/src/roomAgentRequests.ts +++ b/packages/shared/src/roomAgentRequests.ts @@ -317,26 +317,41 @@ export const isAgentOrigin = (entry: { /** * A message an agent queued (a reply, or a child thread's report or request) * that was taken back before it was sent: it stays in the chat, marked - * cancelled, and never started a turn. The projections and the web store all - * apply it through this. + * cancelled, and never started a turn. A lead chat's pass (`fromThread.ceiling`) + * taken back is also `notSent`, which keeps it out of every history an agent + * is given (`reachedAgent`). The projections and the web store all apply it + * through this. */ export const withUnqueuedAgentMessage = < Message extends { readonly id: string; readonly fromAgent?: unknown; - readonly fromThread?: unknown; + readonly fromThread?: { readonly ceiling?: unknown } | undefined; + readonly fromOutside?: unknown; readonly requestOutcome?: RoomAgentRequestOutcome | undefined; + readonly notSent?: true | undefined; }, >( message: Message, unqueued: { readonly messageId: string; readonly reason: "sent" | "cancelled" }, -): Message => - unqueued.reason === "cancelled" && - message.id === unqueued.messageId && - isAgentOrigin(message) && - message.requestOutcome === undefined - ? { ...message, requestOutcome: "cancelled" } +): Message => { + if ( + unqueued.reason !== "cancelled" || + message.id !== unqueued.messageId || + !isAgentOrigin(message) + ) { + return message; + } + const outcome = message.requestOutcome === undefined; + const notSent = message.fromThread?.ceiling !== undefined && message.notSent !== true; + return outcome || notSent + ? { + ...message, + ...(outcome ? { requestOutcome: "cancelled" as const } : {}), + ...(notSent ? { notSent: true as const } : {}), + } : message; +}; /** * Whether the user wrote a message. In a room, an agent can write a user-role