From 94001dda7423cc2d4dcd695cdbfb6bf9eb99f10b Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:01:22 -0500 Subject: [PATCH 1/2] fix: lead chat review leftovers from #970 - A goal set or resumed in the lead now carries the lead's role. Claude reads it as a no-reply message just before /goal; Codex gets it as a developer message in the thread's history (thread/inject_items) before thread/goal/set, best effort. A goal given back after a move carries it too. - The palette's New lead chat targets the open draft's project, and no longer falls back to the first project while that project is loading. - The thread menu's make and stop lead items have their own action ids, so a menu left open does what its label said. - The role text and the thread_send description state the lead's limits; both tool descriptions build their numbers from the enforced constants. - Auto-archive and its settings preview keep a project's lead chat, as they keep a pinned thread. - lead-chat.md matches what ships: no keybinding command, and an agent without thread tools is told per turn instead of a disabled item. --- apps/server/src/guide/topics.ts | 4 +- apps/server/src/mcp/threadTools.ts | 11 +++- .../Layers/ProviderCommandReactor.test.ts | 34 +++++++++++++ .../Layers/ProviderCommandReactor.ts | 27 ++++++++++ .../Layers/ThreadAutoArchiveSweeper.test.ts | 29 ++++++++++- .../Layers/ThreadAutoArchiveSweeper.ts | 9 +++- .../src/provider/Layers/ClaudeAdapter.test.ts | 26 ++++++++++ .../src/provider/Layers/ClaudeAdapter.ts | 27 ++++++---- .../src/provider/Layers/CodexAdapter.ts | 1 + .../provider/Layers/CodexSessionRuntime.ts | 26 ++++++++++ .../src/provider/Layers/ProviderService.ts | 2 + .../src/provider/Services/ProviderAdapter.ts | 5 ++ .../src/provider/Services/ProviderService.ts | 3 ++ .../components/ChatView.palette.browser.tsx | 50 +++++++++++++++++++ .../components/ChatView.sidebar.browser.tsx | 25 ++++++++++ .../src/components/CommandPaletteDialog.tsx | 31 ++++++------ .../components/settings/SettingsPanels.tsx | 4 +- apps/web/src/components/threadMenu.logic.ts | 7 ++- apps/web/src/hooks/useThreadMenu.ts | 9 +++- apps/web/src/threadAutoArchive.test.ts | 15 ++++++ apps/web/src/threadAutoArchive.ts | 16 +++++- docs/design/lead-chat.md | 31 +++++++++--- packages/shared/src/projectLead.ts | 5 +- packages/shared/src/threadAutoArchive.ts | 5 +- 24 files changed, 355 insertions(+), 47 deletions(-) diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index cdbe2de3f..e0384b5c7 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -128,11 +128,11 @@ When an agent asks to start several threads, the card has a checkbox per thread, 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 crown, says Lead where the project name goes, and never wraps up on its own. The chat shows a Lead chat label beside the title, or, once it has started threads, the family tabs with the lead first. +The lead's row sits at the top of the sidebar with a crown, says Lead where the project name goes, and never wraps up on its own. {place:archived.autoArchive} leaves it alone, as it does a pinned thread. The chat shows a Lead chat label beside the title, or, once it has started threads, the family tabs with the lead first. The Threads tab in the right sidebar shows the project's threads on every computer you can see, grouped as Needs you, Ready for review, Working, Landing, Idle and Done. Open it from the sidebar's list of panels or its + menu, on any thread of the project. A thread you wrapped up goes under Done (for 7 days, closed until you open it) unless its pull request is still open, which keeps it under Ready for review or Landing. Ready for review says what the pull request waits on, as the Pull requests page does. Click a row to open the thread, or right-click it for the thread's menu. The top line counts what needs you and what's working, with a Lead chat link when you're on another thread. -The lead's agent is told its role at the start of every turn. It may start 10 threads and send 20 messages to them per message you send, instead of 5 and 10. It needs {place:threads.agentThreads} to be on, and an agent that can't use the thread tools says so. General chats, a thread another thread still owns, and threads from another computer or an outside agent can't be the lead.`, +The lead's agent is told its role at the start of every turn, and when you give it a goal. It may start 10 threads and send 20 messages to them per message you send, instead of 5 and 10. It needs {place:threads.agentThreads} to be on, and an agent that can't use the thread tools says so. General chats, a thread another thread still owns, and threads from another computer or an outside agent can't be the lead.`, }, { id: "linking-computers", diff --git a/apps/server/src/mcp/threadTools.ts b/apps/server/src/mcp/threadTools.ts index 47527101b..a68e59285 100644 --- a/apps/server/src/mcp/threadTools.ts +++ b/apps/server/src/mcp/threadTools.ts @@ -14,8 +14,12 @@ import { AgentThreadReadResult, AgentThreadStatusWord, AgentThreadSummary, + CHILD_THREAD_SEND_LIMIT, + CHILD_THREAD_START_LIMIT, + CHILD_THREADS_PER_CALL, RuntimeMode, } from "@threadlines/contracts"; +import { LEAD_THREAD_SEND_LIMIT, LEAD_THREAD_START_LIMIT } from "@threadlines/shared/childThreads"; import * as Schema from "effect/Schema"; import { Tool, Toolkit } from "effect/ai"; import { loadedOnDemand } from "./toolLoading.ts"; @@ -246,7 +250,8 @@ 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 (10 in the project's lead chat).", + "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 ${CHILD_THREADS_PER_CALL} threads per call and ${CHILD_THREAD_START_LIMIT} per user message (${LEAD_THREAD_START_LIMIT} in the project's lead chat).`, parameters: Schema.Struct({ threads: Schema.Array( Schema.Struct({ @@ -328,7 +333,9 @@ 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). 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.", + "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. " + + `At most ${CHILD_THREAD_SEND_LIMIT} messages per user message (${LEAD_THREAD_SEND_LIMIT} in the project's lead chat). ` + + "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/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index 558614487..40006e25f 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -1178,6 +1178,40 @@ describe("ProviderCommandReactor", () => { expect(steered.input).not.toContain(role); }); + it("gives a goal set in the lead chat the lead's role, apart from the objective", async () => { + const harness = await createHarness(); + const setGoal = (id: string) => + Effect.runPromise( + harness.engine.dispatch({ + type: "thread.goal.set", + commandId: CommandId.make(`cmd-goal-set-${id}`), + threadId: ThreadId.make("thread-1"), + objective: `Goal ${id}`, + createdAt: "2026-01-01T00:00:00.000Z", + }), + ); + // Not the lead yet: the goal goes as it is. + await setGoal("before"); + await waitFor(() => harness.setThreadGoal.mock.calls.length === 1); + expect(harness.setThreadGoal.mock.calls[0]?.[0].context).toBeUndefined(); + + await Effect.runPromise( + harness.engine.dispatch({ + type: "project.lead.set", + commandId: CommandId.make("cmd-lead-set"), + projectId: asProjectId("project-1"), + threadId: ThreadId.make("thread-1"), + }), + ); + await setGoal("after"); + await waitFor(() => harness.setThreadGoal.mock.calls.length === 2); + const asLead = harness.setThreadGoal.mock.calls[1]?.[0]; + expect(asLead?.objective).toBe("Goal after"); + expect(asLead?.context).toContain( + 'This thread is the lead chat for the project "Provider Project"', + ); + }); + it("steers the user's message into a continue that already reached the agent", async () => { const harness = await createHarness(); const send = ( diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts index 0a4147041..755146296 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -4188,10 +4188,30 @@ const make = Effect.gen(function* () { ) : Effect.succeed(null), ), + // A goal that starts work in the lead carries the lead's role, as a + // turn there would: the provider runs that work without a turn start + // of ours (docs/design/lead-chat.md, "Role text"). Effect.flatMap((resumed) => + (event.payload.objective !== undefined || event.payload.status === "active" + ? providerService + .listSessions() + .pipe( + Effect.flatMap((sessions) => + leadChatContext( + thread, + sessions.find((session) => session.threadId === goalHolderSessionKey) + ?.roomTools, + ), + ), + ) + : Effect.succeed(undefined) + ).pipe(Effect.map((context) => ({ resumed, context }))), + ), + Effect.flatMap(({ resumed, context }) => providerService.setThreadGoal({ threadId: goalHolderSessionKey, modelSelection: goalModelSelection, + ...(context !== undefined ? { context } : {}), ...(event.payload.objective !== undefined ? { objective: event.payload.objective } : resumed !== null @@ -5950,11 +5970,18 @@ const make = Effect.gen(function* () { // Unreadable: tried again at the next turn end. if (Option.isNone(held)) return; if (held.value === null || held.value.status !== "active") { + // Made the lead here since it arrived: the goal's work hears it. + const leadContext = yield* leadChatContext( + thread, + (yield* providerService.listSessions()).find((session) => session.threadId === holderKey) + ?.roomTools, + ); const given = yield* providerService .setThreadGoal({ threadId: holderKey, modelSelection: holderModel, status: "active", + ...(leadContext !== undefined ? { context: leadContext } : {}), // The provider counts from zero again: what is left of the budget. ...(held.value === null ? { diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts index 8348c7cae..4d8f06dd5 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.test.ts @@ -108,10 +108,26 @@ function runningSession(threadId: ThreadId): OrchestrationSession { function makeSnapshotQuery( threads: readonly OrchestrationThreadShell[], + leadThreadId?: ThreadId, ): ProjectionSnapshotQueryShape { const shellSnapshot = { snapshotSequence: 1, - projects: [], + projects: + leadThreadId === undefined + ? [] + : [ + { + id: PROJECT_ID, + kind: "workspace" as const, + title: "Project", + workspaceRoot: "/repo/project", + defaultModelSelection: null, + scripts: [], + leadThreadId, + createdAt: daysAgo(60), + updatedAt: daysAgo(60), + }, + ], threads: [...threads], updatedAt: new Date(NOW_MS).toISOString(), }; @@ -157,6 +173,7 @@ describe("ThreadAutoArchiveSweeper", () => { async function createHarness(input: { readonly inactiveDays: AutoArchiveInactiveThreadsDays; readonly threads: readonly OrchestrationThreadShell[]; + readonly leadThreadId?: ThreadId; readonly failingThreadIds?: ReadonlySet; readonly settingsShape?: ServerSettingsShape; /** The children each parent's archive takes along, as the decider would decide. */ @@ -243,7 +260,12 @@ describe("ThreadAutoArchiveSweeper", () => { }) : Layer.succeed(ServerSettingsService, input.settingsShape), ), - Layer.provideMerge(Layer.succeed(ProjectionSnapshotQuery, makeSnapshotQuery(input.threads))), + Layer.provideMerge( + Layer.succeed( + ProjectionSnapshotQuery, + makeSnapshotQuery(input.threads, input.leadThreadId), + ), + ), Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)), ); runtime = ManagedRuntime.make(layer); @@ -318,10 +340,13 @@ describe("ThreadAutoArchiveSweeper", () => { inactiveDays: 30, threads: [ thread("pinned", { pinnedAt: daysAgo(40) }), + // The project's lead chat: archiving it would end its role. + thread("lead"), { ...running, session: runningSession(running.id) }, thread("approval", { hasPendingApprovals: true }), thread("recent", { updatedAt: daysAgo(2) }), ], + leadThreadId: ThreadId.make("lead"), }); expect(await runtime!.runPromise(sweeper.sweepNow())).toBe(0); diff --git a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts index 90be6d41c..4a914e3f0 100644 --- a/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts +++ b/apps/server/src/orchestration/Layers/ThreadAutoArchiveSweeper.ts @@ -86,8 +86,15 @@ const makeThreadAutoArchiveSweeper = (options?: ThreadAutoArchiveSweeperLiveOpti ) .map((thread) => thread.parentThreadId), ); + const leadThreadIds = new Set( + snapshot.projects.flatMap((project) => + project.leadThreadId != null ? [project.leadThreadId] : [], + ), + ); const candidates = selectAutoArchiveCandidates({ - threads: snapshot.threads, + threads: snapshot.threads.map((thread) => + leadThreadIds.has(thread.id) ? { ...thread, lead: true } : thread, + ), inactiveDays, nowMs, isExcluded: (thread) => liveChildParents.has(thread.id), diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index e292d5cc9..e33beaff0 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -12485,6 +12485,32 @@ describe("ClaudeAdapterLive goals", () => { }, ); + it.effect("puts a goal's context ahead of /goal without a turn of its own", () => { + const harness = makeHarness(); + return Effect.gen(function* () { + const { adapter } = yield* startGoalSession(harness); + const setting = yield* adapter.setThreadGoal!({ + threadId: THREAD_ID, + objective: "Tests pass", + origin: "user", + context: "This thread is the lead chat.", + }).pipe(Effect.forkChild); + const sent = yield* Effect.promise(() => + readPromptMessages(harness.getLastCreateQueryInput(), 2), + ); + assert.deepEqual(sent.map(promptMessageShape), [ + { origin: undefined, shouldQuery: false, text: "This thread is the lead chat." }, + { origin: { kind: "human" }, shouldQuery: undefined, text: "/goal Tests pass" }, + ]); + harness.query.emit(goalReply("Tests pass", "Goal set: Tests pass")); + const goal = yield* Fiber.join(setting); + assert.equal(goal.objective, "Tests pass"); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + ); + }); + // As Claude Code 2.1.301 answers it: the running turn's result comes first, // then the clear's own answer and its zero-turn result. it.effect( diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 5cd30abee..6f6d13933 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -6744,6 +6744,7 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const queueGoalCommand = Effect.fn("queueGoalCommand")(function* ( context: ClaudeSessionContext, command: { readonly kind: "set" | "clear"; readonly args: string }, + goalContext?: string, ) { const reply = yield* Deferred.make(); const request: ClaudeGoalCommandRequest = { ...command, sentAtMs: Date.now() }; @@ -6751,16 +6752,19 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const messages: Array = []; // A goal can be the first thing a thread handed over from another agent // asks for; the handoff's context goes in ahead of it, as it would ahead - // of a message. + // of a message. So does what the goal's work should read first (a lead + // chat's role), unless a turn is running: that turn already heard it. const seed = context.pendingContextSeedText; - if ( - command.kind === "set" && - seed !== undefined && - supportsClaudeAppendOnly(context.cliVersion) - ) { + const leading = + command.kind === "set" && supportsClaudeAppendOnly(context.cliVersion) + ? [seed, context.turnState ? undefined : goalContext] + .filter((part): part is string => part !== undefined && part.trim().length > 0) + .join("\n\n") + : ""; + if (leading.length > 0) { messages.push( deliverAsWritten( - buildUserMessage({ sdkContent: [{ type: "text", text: seed }], appendOnly: true }), + buildUserMessage({ sdkContent: [{ type: "text", text: leading }], appendOnly: true }), context.cliVersion, ), ); @@ -6788,8 +6792,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( const sendGoalCommand = Effect.fn("sendGoalCommand")(function* ( context: ClaudeSessionContext, command: { readonly kind: "set" | "clear"; readonly args: string }, + goalContext?: string, ) { - const { reply, request } = yield* queueGoalCommand(context, command); + const { reply, request } = yield* queueGoalCommand(context, command, goalContext); yield* ensureGoalWatch(context); const outcome = yield* Deferred.await(reply).pipe( Effect.timeoutOption(CLAUDE_GOAL_REPLY_TIMEOUT), @@ -6920,7 +6925,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( threadId: input.threadId, modelSelection: input.modelSelection, }); - const outcome = yield* sendGoalCommand(context, { kind: "set", args: objective }); + const outcome = yield* sendGoalCommand( + context, + { kind: "set", args: objective }, + input.context, + ); if (!outcome.accepted) { return yield* refuse(outcome.text.length > 0 ? outcome.text : "Claude did not set the goal."); } diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 2e32ed45f..9f5aa8f81 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -4006,6 +4006,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( ...(input.objective !== undefined ? { objective: input.objective } : {}), ...(input.status !== undefined ? { status: input.status } : {}), ...(input.tokenBudget !== undefined ? { tokenBudget: input.tokenBudget } : {}), + ...(input.context !== undefined ? { context: input.context } : {}), }), ), Effect.map(normalizeCodexThreadGoal), diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index 89896dcd7..584c70612 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -455,6 +455,10 @@ export interface CodexSessionRuntimeSetGoalInput { /** Codex 0.163+ records only "user" edits in the model's history; older * app-servers ignore the field. */ readonly origin: "user" | "automatic"; + /** Put in the model's history as a developer message just before the goal + * is set, so the turns Codex runs for the goal read it (a lead chat's + * role). Best effort: an app-server that refuses it still gets the goal. */ + readonly context?: string; } export type CodexSessionRuntimeError = @@ -3261,6 +3265,28 @@ const makeCodexSessionRuntimeIn = ( setGoal: (input) => Effect.gen(function* () { const providerThreadId = yield* readProviderThreadId; + if (input.context !== undefined && input.context.trim().length > 0) { + yield* withCodexRequestTimeout( + "add a Codex goal's context", + client.raw.request("thread/inject_items", { + threadId: providerThreadId, + items: [ + { + type: "message", + role: "developer", + content: [{ type: "input_text", text: input.context }], + }, + ], + }), + ).pipe( + Effect.catch((cause) => + Effect.logWarning("codex goal context was not added", { + threadId: providerThreadId, + cause, + }), + ), + ); + } const rawResponse = yield* withCodexRequestTimeout( "set a Codex thread goal", client.raw.request("thread/goal/set", { diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index 900d079fd..b2a7405f0 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -124,6 +124,7 @@ const ProviderSetThreadGoalServiceInput = Schema.Struct({ status: Schema.optional(ThreadGoalStatus), tokenBudget: Schema.optional(Schema.NullOr(NonNegativeInt)), modelSelection: Schema.optional(ModelSelection), + context: Schema.optional(Schema.String), }); const ProviderClearThreadGoalServiceInput = Schema.Struct({ threadId: ThreadId, @@ -2351,6 +2352,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( ...(input.status !== undefined ? { status: input.status } : {}), ...(input.tokenBudget !== undefined ? { tokenBudget: input.tokenBudget } : {}), ...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}), + ...(input.context !== undefined ? { context: input.context } : {}), }); // Project the authoritative response directly: goal notifications keep // later autonomous updates flowing, but the requester's own change must diff --git a/apps/server/src/provider/Services/ProviderAdapter.ts b/apps/server/src/provider/Services/ProviderAdapter.ts index 0fce5bded..6187a01a1 100644 --- a/apps/server/src/provider/Services/ProviderAdapter.ts +++ b/apps/server/src/provider/Services/ProviderAdapter.ts @@ -79,6 +79,11 @@ export interface ProviderSetThreadGoalInput { /** The model the goal's work should run on, for providers that start that * work as a turn of their own (Claude). */ readonly modelSelection?: ModelSelection; + /** What the agent reads ahead of the goal's work (a lead chat's role), as + * a turn start would carry it. Never part of the objective. A driver puts + * it in the agent's history without a turn of its own, or drops it when it + * has no way to. */ + readonly context?: string; } export interface ProviderAdapterCapabilities { diff --git a/apps/server/src/provider/Services/ProviderService.ts b/apps/server/src/provider/Services/ProviderService.ts index 7f56ab4c0..7253d7eaf 100644 --- a/apps/server/src/provider/Services/ProviderService.ts +++ b/apps/server/src/provider/Services/ProviderService.ts @@ -270,6 +270,9 @@ export interface ProviderServiceShape { /** The model the goal's work runs on, where the provider starts that * work itself (Claude). */ readonly modelSelection?: ModelSelection; + /** What the agent reads ahead of the goal's work (a lead chat's role). + * See `ProviderSetThreadGoalInput.context`. */ + readonly context?: string; }) => Effect.Effect; /** diff --git a/apps/web/src/components/ChatView.palette.browser.tsx b/apps/web/src/components/ChatView.palette.browser.tsx index aa0eab1cd..77cceeb2e 100644 --- a/apps/web/src/components/ChatView.palette.browser.tsx +++ b/apps/web/src/components/ChatView.palette.browser.tsx @@ -1092,6 +1092,56 @@ describe("ChatView (full app): command palette and search", () => { } }); + it("offers New lead chat for the draft's project, not the first project", async () => { + const capabilities = { repositoryIdentity: true, projectLead: true }; + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: createSnapshotWithSecondaryProject({ includeSecondaryThread: false }), + configureFixture: (nextFixture) => { + // The first project already has its lead. + nextFixture.snapshot = { + ...nextFixture.snapshot, + projects: nextFixture.snapshot.projects.map((project) => + project.id === PROJECT_ID ? { ...project, leadThreadId: THREAD_ID } : project, + ), + }; + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + environment: { ...nextFixture.serverConfig.environment, capabilities }, + }; + nextFixture.welcome = { + ...nextFixture.welcome, + environment: { ...nextFixture.welcome.environment, capabilities }, + }; + }, + }); + + try { + await waitForServerConfigToApply(); + const palette = page.getByTestId("command-palette"); + await openCommandPaletteFromTrigger(); + await page.getByPlaceholder("Search commands, projects, and threads...").fill("clients/docs"); + await palette.getByText("Docs Portal", { exact: true }).click(); + const draftPath = await waitForURL( + mounted.router, + (path) => UUID_ROUTE_RE.test(path), + "Route should have changed to a draft in the second project.", + ); + expect( + useComposerDraftStore.getState().getDraftSession(draftIdFromPath(draftPath))?.projectId, + ).toBe(SECOND_PROJECT_ID); + await expect.element(palette).not.toBeInTheDocument(); + + await openCommandPaletteFromTrigger(); + await page.getByPlaceholder("Search commands, projects, and threads...").fill("new lead"); + // Named for the draft's project; the first project's lead hides nothing. + await expect.element(palette.getByText("New lead chat", { exact: true })).toBeInTheDocument(); + await expect.element(palette.getByText("Docs Portal", { exact: true })).toBeInTheDocument(); + } finally { + await mounted.cleanup(); + } + }); + it("filters archived threads out of command palette search results", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index d379ecc27..5befa3279 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -38,6 +38,7 @@ import { import { getClientSettings, updateSettings } from "../hooks/useSettings"; import { nextFrames, readAfterEachPaint } from "../lib/frameProbe.browser-harness"; import { isMacPlatform } from "../lib/utils"; +import { useStore } from "../store"; import { useThreadSelectionStore } from "../threadSelectionStore"; import { useUiStateStore } from "../uiStateStore"; @@ -45,6 +46,7 @@ import { DEFAULT_CLIENT_SETTINGS } from "@threadlines/contracts/settings"; import { THREAD_ID, THREAD_TITLE, + PROJECT_ID, SECOND_PROJECT_ID, LOCAL_ENVIRONMENT_ID, BrowserHostHarness, @@ -81,6 +83,8 @@ import { sendShellThreadUpsert, mountChatView, fixture, + rpcHarness, + toShellSnapshot, clickProjectMenuItem, registerChatViewSuiteHooks, openCommandPaletteFromTrigger, @@ -434,6 +438,27 @@ describe("ChatView (full app): sidebar", () => { await openRowMenu(THREAD_ID); await page.getByRole("button", { name: "Stop using as lead chat", exact: true }).click(); await vi.waitFor(() => expect(leadSets()).toEqual([otherThreadId, null])); + + // Another client makes the other thread the lead while this menu is + // open: its "Stop using" must not turn into making this one the lead. + await openRowMenu(THREAD_ID); + const stop = page.getByRole("button", { name: "Stop using as lead chat", exact: true }); + await expect.element(stop).toBeVisible(); + const [project] = toShellSnapshot(fixture.snapshot).projects; + rpcHarness.emitStreamValue(ORCHESTRATION_WS_METHODS.subscribeShell, { + kind: "project-upserted", + sequence: fixture.snapshot.snapshotSequence + 1, + project: { ...project!, leadThreadId: otherThreadId }, + }); + await vi.waitFor(() => + expect( + useStore.getState().environmentStateById[LOCAL_ENVIRONMENT_ID]?.projectById[PROJECT_ID] + ?.leadThreadId, + ).toBe(otherThreadId), + ); + await stop.click(); + await new Promise((resolve) => setTimeout(resolve, 200)); + expect(leadSets()).toEqual([otherThreadId, null]); } finally { await mounted.cleanup(); } diff --git a/apps/web/src/components/CommandPaletteDialog.tsx b/apps/web/src/components/CommandPaletteDialog.tsx index 775541fc6..6d584397b 100644 --- a/apps/web/src/components/CommandPaletteDialog.tsx +++ b/apps/web/src/components/CommandPaletteDialog.tsx @@ -485,7 +485,11 @@ const PALETTE_THREAD_ACTIONS: Partial< } > > = { - lead: { + "make-lead": { + searchTerms: ["lead chat", "lead", "coordinate", "project lead"], + icon: , + }, + "stop-lead": { searchTerms: ["lead chat", "lead", "coordinate", "project lead"], icon: , }, @@ -2247,21 +2251,18 @@ export function OpenCommandPaletteDialog() { }, }); } + // The open thread's or draft's project (none until its computer's projects + // load); the first project only when neither is open. const leadScopeProject = - (activeThread - ? projects.find( - (project) => - project.environmentId === activeThread.environmentId && - project.id === activeThread.projectId, - ) - : undefined) ?? - (defaultProjectRef - ? projects.find( - (project) => - project.environmentId === defaultProjectRef.environmentId && - project.id === defaultProjectRef.projectId, - ) - : undefined); + currentProjectId !== null + ? (currentProject ?? undefined) + : defaultProjectRef + ? projects.find( + (project) => + project.environmentId === defaultProjectRef.environmentId && + project.id === defaultProjectRef.projectId, + ) + : undefined; if ( leadScopeProject !== undefined && leadScopeProject.kind === "workspace" && diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index ba0307c5c..4d5051430 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -2282,9 +2282,10 @@ export function ArchivedThreadsPanel({ hostedStatic }: { readonly hostedStatic: () => selectAutoArchiveCandidates({ threads: sidebarThreads, + projects, inactiveDays: autoArchivePreviewDays, }), - [autoArchivePreviewDays, sidebarThreads], + [autoArchivePreviewDays, projects, sidebarThreads], ); const inactiveThreadGroups = useMemo( () => @@ -2351,6 +2352,7 @@ export function ArchivedThreadsPanel({ hostedStatic }: { readonly hostedStatic: if (nextDays !== 0) { const nextCandidates = selectAutoArchiveCandidates({ threads: sidebarThreads, + projects, inactiveDays: nextDays, }); if (nextCandidates.length > 0) { diff --git a/apps/web/src/components/threadMenu.logic.ts b/apps/web/src/components/threadMenu.logic.ts index 9679b6cd5..83cb800b4 100644 --- a/apps/web/src/components/threadMenu.logic.ts +++ b/apps/web/src/components/threadMenu.logic.ts @@ -12,7 +12,8 @@ export type ThreadMenuAction = | "reopen" | "move-up" | "move-down" - | "lead" + | "make-lead" + | "stop-lead" | "separate" | "attach" | "stop-children" @@ -91,7 +92,9 @@ export function describeThreadMenu(facts: ThreadMenuFacts): ContextMenuItem([ { - id: "lead", + // Make and stop are separate actions, as pin and unpin are: a menu + // left open while another client changes the lead does what it says. + id: facts.lead.kind === "stop" ? "stop-lead" : "make-lead", label: leadMenuLabel(facts.lead), disabled: facts.lead.kind === "make" && facts.lead.refusal !== null, }, diff --git a/apps/web/src/hooks/useThreadMenu.ts b/apps/web/src/hooks/useThreadMenu.ts index 6d1710ecb..969b8a0ee 100644 --- a/apps/web/src/hooks/useThreadMenu.ts +++ b/apps/web/src/hooks/useThreadMenu.ts @@ -223,9 +223,14 @@ export function useThreadMenu() { case "move": openThreadMoveDialog(threadRef); return; - case "lead": { + case "make-lead": + case "stop-lead": { + // The click does what the item said. Since the menu opened, another + // client may have done it already (nothing to do) or made it + // refused (the item would read disabled now). const lead = readLeadMenuState(useStore.getState(), thread); - if (lead === null || (lead.kind === "make" && lead.refusal !== null)) return; + if (lead === null || lead.kind !== (action === "make-lead" ? "make" : "stop")) return; + if (lead.kind === "make" && lead.refusal !== null) return; const made = await setProjectLead({ environmentId: thread.environmentId, projectId: thread.projectId, diff --git a/apps/web/src/threadAutoArchive.test.ts b/apps/web/src/threadAutoArchive.test.ts index 2d6e3c59a..edd4ddd7c 100644 --- a/apps/web/src/threadAutoArchive.test.ts +++ b/apps/web/src/threadAutoArchive.test.ts @@ -56,6 +56,7 @@ describe("thread auto-archive candidates", () => { inactiveDays: 30, nowMs: NOW_MS, threads: [excluded, thread("included")], + projects: [], excludeThreadKeys: new Set([ scopedThreadKey(scopeThreadRef(excluded.environmentId, excluded.id)), ]), @@ -64,6 +65,19 @@ describe("thread auto-archive candidates", () => { expect(candidates.map((candidate) => candidate.id)).toEqual([ThreadId.make("included")]); }); + it("keeps each project's lead chat, as it keeps a pinned thread", () => { + const candidates = selectAutoArchiveCandidates({ + inactiveDays: 30, + nowMs: NOW_MS, + threads: [thread("lead"), thread("other")], + projects: [ + { id: PROJECT_ID, environmentId: ENVIRONMENT_ID, leadThreadId: ThreadId.make("lead") }, + ], + }); + + expect(candidates.map((candidate) => candidate.id)).toEqual([ThreadId.make("other")]); + }); + it("groups candidates by project", () => { const project: Project = { id: PROJECT_ID, @@ -78,6 +92,7 @@ describe("thread auto-archive candidates", () => { inactiveDays: 30, nowMs: NOW_MS, threads: [thread("one"), thread("two")], + projects: [project], }); expect(groupAutoArchiveCandidatesByProject({ candidates, projects: [project] })).toMatchObject([ diff --git a/apps/web/src/threadAutoArchive.ts b/apps/web/src/threadAutoArchive.ts index 7c2c64359..5956c483b 100644 --- a/apps/web/src/threadAutoArchive.ts +++ b/apps/web/src/threadAutoArchive.ts @@ -26,6 +26,8 @@ export interface AutoArchiveProjectGroup { interface SelectAutoArchiveCandidatesInput { readonly threads: ReadonlyArray; + /** The threads' projects, which say which thread is each one's lead chat. */ + readonly projects: ReadonlyArray>; readonly inactiveDays: AutoArchiveInactiveThreadsDays; readonly nowMs?: number | undefined; readonly excludeThreadKeys?: ReadonlySet | undefined; @@ -46,12 +48,24 @@ export function resolveAutoArchivePreviewDays( export function selectAutoArchiveCandidates({ threads, + projects, inactiveDays, nowMs = Date.now(), excludeThreadKeys, }: SelectAutoArchiveCandidatesInput): ReadonlyArray { + const leadThreadKeys = new Set( + projects.flatMap((project) => + project.leadThreadId != null + ? [scopedThreadKey(scopeThreadRef(project.environmentId, project.leadThreadId))] + : [], + ), + ); return selectSharedAutoArchiveCandidates({ - threads, + threads: threads.map((thread) => + leadThreadKeys.has(scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))) + ? { ...thread, lead: true } + : thread, + ), inactiveDays, nowMs, isExcluded: diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md index 1e914bdc8..9cbcaec66 100644 --- a/docs/design/lead-chat.md +++ b/docs/design/lead-chat.md @@ -97,10 +97,15 @@ Words below are the on-screen words. Copy follows the repo's copy rules (no em d rules they don't know (a follow-up). - **Not allowed, with the reason shown on the disabled item:** General Chats; a thread another thread started and still owns; a thread from another computer or an outside - agent; an archived thread; a thread with a move pending; an agent that cannot use the - thread tools; "Agents can start threads" off (the reason links to that setting). + agent; an archived thread; a thread with a move pending; "Agents can start threads" + off (the reason names that setting). +- **An agent that cannot use the thread tools (built):** not refused at the menu. + Whether a runtime takes the thread tools is known only once it is up, and a room's + agents differ. Each turn whose runtime came up without them adds a line to the role + text telling the agent to say it can't coordinate the lead (`LEAD_WITHOUT_TOOLS_TEXT`). - **Takes effect at the thread's next turn.** A turn already running is not told. -- **Ends by itself** when the lead thread is archived or deleted. Moving the lead to +- **Ends by itself** when the lead thread is archived or deleted. Auto-archive keeps + the lead as it keeps a pinned thread, so an idle lead is never archived for the user. Moving the lead to another computer is refused: "This is the project's lead chat. Pick another lead first." - Nothing is lost when a lead stops being one: it becomes an ordinary thread, and the @@ -233,6 +238,8 @@ coordinate it. finished and what needs them. Do not repeat the report. - 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. +- Here you may start 10 threads (at most 5 per call) and send 20 messages per user + message. ``` - It is a preference, not a fence: we cannot remove file tools on every provider. @@ -240,6 +247,14 @@ coordinate it. (the turn got the text when it started), and a room agent's side answer (read-only, not lead work). Both are named in the builder's tests so a change is deliberate. - In a room that is the lead, each agent's turns get it. +- **Goals (built):** a goal's work starts on the provider, not through a turn start, so + setting or resuming a goal in the lead carries the role too, apart from the objective. + Claude reads it as a no-reply message just before `/goal`. Codex gets it as a + developer message in the thread's history (`thread/inject_items`) before + `thread/goal/set`, so the turns it runs for the goal read it; an app-server that + refuses that still gets the goal. +- **The role text states the lead's limits** (starts and sends per user message), and + so do the `thread_start` and `thread_send` descriptions. ### Tools @@ -520,15 +535,15 @@ Built (piece 4), where it differs from or adds to the rulings: ## Every surface - **Entry points:** thread menus (sidebar, header), project menu, command palette, - keybinding command, new-thread screen (a "Lead chat" link beside the project's thread + new-thread screen (a "Lead chat" link beside the project's thread map when one exists). - **Clients:** web, desktop and the phone view share the components. Board logic that is not view code goes in `packages/client-runtime`. - **Providers:** a lead needs the thread tools. Codex, Claude, OpenCode, Muse and Pi get them; ACP agents (fx, Cursor, Antigravity, Grok, community agents) only when they - take an HTTP tool server, decided in the generic core. Where they do not, "Make this - the lead chat" is disabled with the reason. Role text reaches all of them through - the per-turn context. A room can be the lead: requests already carry the asking + take an HTTP tool server, decided in the generic core. Where they do not, the role + text tells the agent to say it can't coordinate (see "An agent that cannot use the + thread tools"). Role text reaches all of them through the per-turn context. A room can be the lead: requests already carry the asking agent. - **Contracts:** project field and command, two capability flags, the origin's `ceiling`, respond's `requestIds`, the update event's `childMessageId`, summary @@ -549,7 +564,7 @@ files and go in that order from one builder. 3 is web only and can run beside 2 piece 1's contracts are committed. 5 is web only and can run beside 4. 1. **Lead role.** Project field, command, cascades, migration, capability; role text - on every turn start; limits; menus, palette, keybinding command, sidebar row and + on every turn start; limits; menus, palette, sidebar row and sort, header chip, placeholder; guide topic. Tests: decider (set, replace, refusals, cascades, ghost pointer), a restart round-trip of the pointer, role text present on person, task, report, retry and continue turns and absent on steers and side diff --git a/packages/shared/src/projectLead.ts b/packages/shared/src/projectLead.ts index 3e902bc39..a3417bef0 100644 --- a/packages/shared/src/projectLead.ts +++ b/packages/shared/src/projectLead.ts @@ -3,7 +3,9 @@ * project points at with `leadThreadId`. The decider enforces these rules and * the client reads the same ones to explain a disabled menu item. */ -import type { ProjectId, ThreadId } from "@threadlines/contracts"; +import { CHILD_THREADS_PER_CALL, type ProjectId, type ThreadId } from "@threadlines/contracts"; + +import { LEAD_THREAD_SEND_LIMIT, LEAD_THREAD_START_LIMIT } from "./childThreads.ts"; /** What the lead rules read from a project. */ export interface LeadProject { @@ -90,6 +92,7 @@ export function leadRoleText(projectTitle: string): string { '- 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. A thread you did not start does not report back: the user sees its answer there.", + `- Here you may start ${LEAD_THREAD_START_LIMIT} threads (at most ${CHILD_THREADS_PER_CALL} per call) and send ${LEAD_THREAD_SEND_LIMIT} messages per user message.`, ].join("\n"); } diff --git a/packages/shared/src/threadAutoArchive.ts b/packages/shared/src/threadAutoArchive.ts index 2da6709aa..18cfb318a 100644 --- a/packages/shared/src/threadAutoArchive.ts +++ b/packages/shared/src/threadAutoArchive.ts @@ -6,6 +6,9 @@ export interface AutoArchiveThreadFields { readonly latestUserMessageAt: string | null; readonly archivedAt: string | null; readonly pinnedAt: string | null; + /** It is its project's lead chat (docs/design/lead-chat.md): kept like a + * pinned thread, since archiving it would end its role. */ + readonly lead?: boolean | undefined; readonly hasPendingApprovals: boolean; readonly hasPendingUserInput: boolean; readonly hasActionableProposedPlan: boolean; @@ -29,7 +32,7 @@ export function getAutoArchiveThreadInactiveSince(thread: AutoArchiveThreadField } export function isAutoArchiveProtectedThread(thread: AutoArchiveThreadFields): boolean { - if (thread.archivedAt !== null || thread.pinnedAt !== null) { + if (thread.archivedAt !== null || thread.pinnedAt !== null || thread.lead === true) { return true; } From e8cb246cedd9a55a0646e37524bd4074ec50e1c9 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 04:23:58 -0500 Subject: [PATCH 2/2] test(server): the agent context budget counts the lead's send limit thread_send's description now states the lead chat's message limit (20 per user message, 10 for other threads). ACP agents learn rules only from tool descriptions, so the 70 bytes are what tells them. --- apps/server/src/provider/agentContextBudget.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index 35d4964cf..ae593628e 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -16,5 +16,5 @@ "show_page" ], "upFrontToolDefinitionBytes": 16834, - "onDemandToolDefinitionBytes": 48765 + "onDemandToolDefinitionBytes": 48835 }