From eea048e4859e38ff268f1baa0b67626228447f8f Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:09:39 -0500 Subject: [PATCH 1/2] feat: a project can have a lead chat Each project can now name one thread its lead chat: the place to drop work for the project, whose agent coordinates threads for it (docs/design/lead-chat.md, piece 1 of 4). The project keeps a pointer to its lead (`leadThreadId`, migration 116), set with `project.lead.set` and carried on the existing project update event. Archiving or deleting the lead ends it in the same decision; the lead can't be put back under a parent or moved to another computer, and a pointer at an archived or missing thread reads as no lead. The lead's agent hears its role at the start of every turn, and may start 10 threads and send 20 messages per user message instead of 5 and 10. In the app the lead is set and unset from the thread menu, the project menu (Open or New lead chat), the command palette and a keybinding command. Its row sorts first in the sidebar with a flag and never wraps up on its own; the chat shows a Lead chat label and invites work in the composer. The app guide has a lead chat topic. --- .../environment/Layers/ServerEnvironment.ts | 1 + apps/server/src/guide/topics.ts | 20 +- apps/server/src/mcp/threadToolHandlers.ts | 17 +- .../Layers/OrchestrationEngine.ts | 1 + .../Layers/ProjectionPipeline.ts | 3 + .../Layers/ProjectionSnapshotQuery.ts | 11 + .../Layers/ProviderCommandReactor.test.ts | 48 ++ .../Layers/ProviderCommandReactor.ts | 24 + .../src/orchestration/childThreadDecisions.ts | 14 +- .../src/orchestration/commandInvariants.ts | 13 + .../orchestration/decider.projectLead.test.ts | 215 ++++++++ apps/server/src/orchestration/decider.ts | 94 +++- apps/server/src/orchestration/projector.ts | 3 + .../src/orchestration/threadMoveDecisions.ts | 13 +- .../persistence/Layers/ProjectionProjects.ts | 5 + .../Layers/ProjectionRepositories.test.ts | 27 + apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/116_ProjectLeadThread.ts | 15 + .../Services/ProjectionProjects.ts | 3 + apps/web/src/components/AppSidebarLayout.tsx | 11 +- .../components/ChatView.browser-harness.tsx | 1 + .../components/ChatView.sidebar.browser.tsx | 76 +++ apps/web/src/components/ChatView.tsx | 5 + .../src/components/CommandPaletteDialog.tsx | 82 ++- apps/web/src/components/Sidebar.logic.test.ts | 30 ++ apps/web/src/components/Sidebar.logic.ts | 58 ++- apps/web/src/components/Sidebar.tsx | 31 +- apps/web/src/components/chat/ChatComposer.tsx | 6 + apps/web/src/components/chat/ChatHeader.tsx | 12 + .../src/components/chat/ProjectThreadMap.tsx | 32 ++ .../components/chat/composerPlaceholder.ts | 8 +- apps/web/src/components/sidebar/InboxRows.tsx | 13 + .../components/sidebar/ProjectScopeMenu.tsx | 72 ++- apps/web/src/components/threadMenu.logic.ts | 17 + apps/web/src/hooks/useInboxThreads.ts | 17 +- apps/web/src/hooks/useThreadMenu.ts | 21 + apps/web/src/leadChat.ts | 302 +++++++++++ apps/web/src/newThreadDefaults.ts | 2 +- apps/web/src/store.ts | 4 + apps/web/src/types.ts | 5 + docs/design/lead-chat.md | 493 ++++++++++++++++++ packages/contracts/src/environment.ts | 6 + packages/contracts/src/keybindings.ts | 1 + packages/contracts/src/orchestration.ts | 28 + packages/shared/package.json | 4 + packages/shared/src/childThreads.test.ts | 9 + packages/shared/src/childThreads.ts | 42 +- packages/shared/src/projectLead.ts | 98 ++++ 48 files changed, 1978 insertions(+), 37 deletions(-) create mode 100644 apps/server/src/orchestration/decider.projectLead.test.ts create mode 100644 apps/server/src/persistence/Migrations/116_ProjectLeadThread.ts create mode 100644 apps/web/src/leadChat.ts create mode 100644 docs/design/lead-chat.md create mode 100644 packages/shared/src/projectLead.ts diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.ts index e41ebd0ef..bd49d2553 100644 --- a/apps/server/src/environment/Layers/ServerEnvironment.ts +++ b/apps/server/src/environment/Layers/ServerEnvironment.ts @@ -116,6 +116,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function outsideAgents: true, pushAlerts: true, phoneAlertControls: true, + projectLead: true, deviceNames: true, draftGoalSetup: true, pullRequestSwitchesByNumber: true, diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index ca5be7861..7bb9b1e8c 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -45,7 +45,7 @@ export const GUIDE_TOPICS: ReadonlyArray = [ ], body: `A thread is one conversation with an agent in a project. Threads are listed in the sidebar; one that needs you, finished or failed says so there. In a narrow window the sidebar floats over the thread instead of sitting beside it: the sidebar button at the top left, or Cmd+B (Ctrl+B on Windows and Linux), opens it, and picking a thread or clicking the thread puts it away. -The sliders button beside the project picker at the top of the sidebar groups the list by project or computer and sorts it: recent activity, newest, oldest, title, or a custom order. In the custom order you drag rows to arrange them, or use Move up and Move down in a thread's menu, and only you move a row; new threads go to the bottom, and the same button can reset the order. Pinned threads stay above a thin line in every sort. When the list is grouped, drag a group's header to move the whole group, in any sort; its menu has Move up, Move down and Use automatic order. These orders are kept per device, so a phone has its own. +The sliders button beside the project picker at the top of the sidebar groups the list by project or computer and sorts it: recent activity, newest, oldest, title, or a custom order. In the custom order you drag rows to arrange them, or use Move up and Move down in a thread's menu, and only you move a row; new threads go to the bottom, and the same button can reset the order. Pinned threads stay above a thin line in every sort, under a project's lead chat, which comes first. When the list is grouped, drag a group's header to move the whole group, in any sort; its menu has Move up, Move down and Use automatic order. These orders are kept per device, so a phone has its own. A new thread starts either in the project folder as it is, or in a worktree of its own: a separate git checkout on a new branch, so its changes stay apart until you merge them. You pick per thread in the composer; the default is {place:threads.startIn}, and new worktrees branch from {place:threads.worktreesFrom}. A project's setup script runs once in each new worktree. @@ -100,7 +100,23 @@ A started thread works in a worktree of its own; in a project without git it sha A started thread gets at most its parent's access level, or a lower one the agent asks for, and the parent's model unless the agent picks another. On a model already in the room it runs at the reasoning you set for that agent there, unless the agent or you name another level; the approval card shows the level. With computers linked in Fleet, an agent can also start a thread on another computer, if that computer allows it ({place:fleet.worksWith}). -A thread on another computer stays under its parent on both computers and shows how it is doing there, even after its answer came back. Once its answer reached the parent it wraps up and moves to Wrapped like any other, unless someone picked it up again there. Its row has Wrap up (and Reopen in Wrapped), which applies on both computers. To open it, connect this app to that computer.`, +A thread on another computer stays under its parent on both computers and shows how it is doing there, even after its answer came back. Once its answer reached the parent it wraps up and moves to Wrapped like any other, unless someone picked it up again there. Its row has Wrap up (and Reopen in Wrapped), which applies on both computers. To open it, connect this app to that computer. + +A project's lead chat is a thread set up to coordinate the project; see the lead chat topic.`, + }, + { + id: "lead-chat", + title: "Lead chat", + keywords: ["lead chat", "lead", "coordinator", "project lead", "orchestrator", "drop work"], + body: `Each project can have one lead chat: a thread you drop work into (a bug, a stack trace, a list of tasks). Its agent answers small questions itself and starts threads for new work. Those threads show under the lead in the sidebar and report back to it, and it tells you what finished and what needs you. + +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. + +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. + +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.`, }, { id: "linking-computers", diff --git a/apps/server/src/mcp/threadToolHandlers.ts b/apps/server/src/mcp/threadToolHandlers.ts index adcfe28c4..afbd4e988 100644 --- a/apps/server/src/mcp/threadToolHandlers.ts +++ b/apps/server/src/mcp/threadToolHandlers.ts @@ -129,7 +129,9 @@ export interface ThreadToolDeps { ) => Effect.Effect>; readonly readProject: ( projectId: ProjectId, - ) => Effect.Effect | undefined>; + ) => Effect.Effect< + Pick | undefined + >; /** The provider snapshots: who a child could run on. */ readonly providers: Effect.Effect>; /** The user's default for new threads (Settings): the last reasoning a child follows. */ @@ -469,6 +471,16 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { participantId: scope.participantId, }); + /** + * Whether the calling thread is its project's lead chat, which gets a larger + * budget (docs/design/lead-chat.md). The caller is open and working, so the + * pointer alone answers it; the decider checks again. + */ + const isLeadThread = (thread: OrchestrationThread) => + deps + .readProject(thread.projectId) + .pipe(Effect.map((project) => (project?.leadThreadId ?? null) === thread.id)); + /** An attached child may not start, message or stop threads: families are one level deep. */ const depthRefusal = (thread: OrchestrationThread, scope: McpInvocationScope) => ({ outcome: "not_allowed" as const, @@ -980,6 +992,7 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { from: from(scope), callerTurnId, count: specs.length, + isLead: yield* isLeadThread(current), }); if (refusal !== null) { return ruleOutcome(refusal) satisfies ThreadStartResult; @@ -1290,6 +1303,7 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { from: from(scope), callerTurnId, count: specs.length, + isLead: yield* isLeadThread(current), }); if (refusal !== null) { return ruleOutcome(refusal) satisfies ThreadStartResult; @@ -1761,6 +1775,7 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) { const refusal = childSendRefusal(caller, child ?? null, { from: from(scope), callerTurnId, + isLead: yield* isLeadThread(caller), }); if (refusal !== null) { return { diff --git a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts index f475b8660..9fa654611 100644 --- a/apps/server/src/orchestration/Layers/OrchestrationEngine.ts +++ b/apps/server/src/orchestration/Layers/OrchestrationEngine.ts @@ -62,6 +62,7 @@ function commandToAggregateRef(command: OrchestrationCommand): { switch (command.type) { case "project.create": case "project.meta.update": + case "project.lead.set": case "project.general-chats.relocate": case "project.delete": return { diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts index e72827221..8765afafd 100644 --- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts +++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts @@ -469,6 +469,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti ...(event.payload.phoneAlertsMuted !== undefined ? { phoneAlertsMuted: event.payload.phoneAlertsMuted } : {}), + ...(event.payload.leadThreadId !== undefined + ? { leadThreadId: event.payload.leadThreadId } + : {}), updatedAt: event.payload.updatedAt, }); return; diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts index bfd671dcb..188f93492 100644 --- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts +++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts @@ -759,6 +759,7 @@ function mapProjectShellRow( defaultModelSelection: row.defaultModelSelection, scripts: row.scripts, ...(row.phoneAlertsMuted ? { phoneAlertsMuted: true } : {}), + ...((row.leadThreadId ?? null) !== null ? { leadThreadId: row.leadThreadId } : {}), createdAt: row.createdAt, updatedAt: row.updatedAt, }; @@ -884,6 +885,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { default_model_selection_json AS "defaultModelSelection", scripts_json AS "scripts", phone_alerts_muted AS "phoneAlertsMuted", + lead_thread_id AS "leadThreadId", created_at AS "createdAt", updated_at AS "updatedAt", deleted_at AS "deletedAt" @@ -1821,6 +1823,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { default_model_selection_json AS "defaultModelSelection", scripts_json AS "scripts", phone_alerts_muted AS "phoneAlertsMuted", + lead_thread_id AS "leadThreadId", created_at AS "createdAt", updated_at AS "updatedAt", deleted_at AS "deletedAt" @@ -1845,6 +1848,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { default_model_selection_json AS "defaultModelSelection", scripts_json AS "scripts", phone_alerts_muted AS "phoneAlertsMuted", + lead_thread_id AS "leadThreadId", created_at AS "createdAt", updated_at AS "updatedAt", deleted_at AS "deletedAt" @@ -2840,6 +2844,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { defaultModelSelection: row.defaultModelSelection, scripts: row.scripts, ...(row.phoneAlertsMuted ? { phoneAlertsMuted: true } : {}), + ...((row.leadThreadId ?? null) !== null ? { leadThreadId: row.leadThreadId } : {}), createdAt: row.createdAt, updatedAt: row.updatedAt, deletedAt: row.deletedAt, @@ -3068,6 +3073,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { defaultModelSelection: row.defaultModelSelection, scripts: row.scripts, ...(row.phoneAlertsMuted ? { phoneAlertsMuted: true } : {}), + ...((row.leadThreadId ?? null) !== null + ? { leadThreadId: row.leadThreadId } + : {}), createdAt: row.createdAt, updatedAt: row.updatedAt, deletedAt: row.deletedAt, @@ -3546,6 +3554,9 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () { defaultModelSelection: option.value.defaultModelSelection, scripts: option.value.scripts, ...(option.value.phoneAlertsMuted ? { phoneAlertsMuted: true } : {}), + ...((option.value.leadThreadId ?? null) !== null + ? { leadThreadId: option.value.leadThreadId } + : {}), createdAt: option.value.createdAt, updatedAt: option.value.updatedAt, deletedAt: option.value.deletedAt, diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts index d9d94c8fc..af64a4f41 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts @@ -1119,6 +1119,54 @@ describe("ProviderCommandReactor", () => { expect(harness.sendTurn.mock.calls.length).toBe(1); }); + it("tells the lead chat's agent its role at each turn start, not in a steered message", async () => { + const harness = await createHarness(); + 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"), + }), + ); + const send = (id: string, extra: { readonly trigger?: "usageLimitReset" }) => + Effect.runPromise( + harness.engine.dispatch({ + type: "thread.turn.start", + commandId: CommandId.make(`cmd-turn-start-${id}`), + threadId: ThreadId.make("thread-1"), + message: { messageId: asMessageId(id), role: "user", text: id, attachments: [] }, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + runtimeMode: "approval-required", + ...extra, + createdAt: "2026-01-01T00:00:00.000Z", + }), + ); + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const defaultSendTurn = harness.sendTurn.getMockImplementation(); + if (!defaultSendTurn) throw new Error("sendTurn mock has no implementation"); + harness.sendTurn.mockImplementationOnce((input: unknown) => + Effect.promise(() => gate).pipe(Effect.flatMap(() => defaultSendTurn(input))), + ); + // A continue at the reset starts a turn like any other; the user's message + // during it is steered into that turn. + await send("continue-at-reset", { trigger: "usageLimitReset" }); + await waitFor(() => harness.sendTurn.mock.calls.length === 1); + await send("user-wrote-during-start", {}); + release(); + await waitFor(() => harness.steerTurn.mock.calls.length === 1); + + const role = 'This thread is the lead chat for the project "Provider Project"'; + const started = harness.sendTurn.mock.calls[0]?.[0] as { readonly input?: string }; + const steered = harness.steerTurn.mock.calls[0]?.[0] as { readonly input?: string }; + expect(started.input).toContain(role); + expect(steered.input).toContain("user-wrote-during-start"); + expect(steered.input).not.toContain(role); + }); + 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 898a24114..4954cd6bc 100644 --- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts +++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts @@ -49,6 +49,7 @@ import { type TurnId, } from "@threadlines/contracts"; 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 { settingsChangeNotesFor } from "@threadlines/shared/settingsChangeState"; @@ -2159,6 +2160,27 @@ const make = Effect.gen(function* () { }; }); + /** + * The lead chat's role (docs/design/lead-chat.md, "Role text"): added to + * every turn that starts in a project's lead, whatever started it, and to + * each room agent's turns there. A message steered into a running turn and + * a side answer don't carry it, by decision: the turn heard it when it + * started, and a side answer is read-only. An agent whose runtime came up + * without the thread tools (an ACP agent that takes no HTTP tool server) + * is told it can't coordinate, so it says so instead of pretending. + */ + const leadChatContext = Effect.fnUntraced(function* ( + thread: OrchestrationThread, + roomTools: boolean | undefined, + ) { + if (thread.archivedAt !== null) return undefined; + const project = yield* resolveProject(thread.projectId); + if (project === undefined || (project.leadThreadId ?? null) !== thread.id) return undefined; + return roomTools === false + ? `${leadRoleText(project.title)}\n\n${LEAD_WITHOUT_TOOLS_TEXT}` + : leadRoleText(project.title); + }); + /** * Outside agents (docs/design/outside-agents.md): a message one wrote is * named as its, so the agent here never takes it for the user's own words. @@ -2470,6 +2492,7 @@ const make = Effect.gen(function* () { // Child threads: who this message is from, and what this agent's threads // did since its last turn without waking it (notes are its alone). const childContext = yield* childThreadContext(thread, input.participantId, input.fromThread); + const leadContext = yield* leadChatContext(thread, activeSession?.roomTools); const scheduleContext = yield* scheduledTaskContext(thread, input.participantId); const settingsContext = settingsChangeContext(thread, input.participantId); const sentMessage = thread.messages.find((message) => message.id === input.messageId); @@ -2510,6 +2533,7 @@ const make = Effect.gen(function* () { resumeContextText, forkContextText, roomCatchUp?.note, + leadContext, childContext.text, outsideAgentContext(thread, input.messageId), scheduleContext.text, diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts index a2a6977c9..81ca8296a 100644 --- a/apps/server/src/orchestration/childThreadDecisions.ts +++ b/apps/server/src/orchestration/childThreadDecisions.ts @@ -52,6 +52,7 @@ import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; 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"; @@ -416,6 +417,7 @@ export function decideChildStart( from: command.from, callerTurnId: command.callerTurnId, count: command.children.length, + isLead: isProjectLeadThread(readModel, parent), }); if (refusal !== null) { return refuse(refusal.detail); @@ -530,7 +532,13 @@ export function decideChildSend( ): ChildThreadDecision { const remoteChild = remoteChildOf(parent.childRequests, command.childThreadId); if (remoteChild !== undefined) { - return decideRemoteChildSend(parent, command, baseFor, remoteChild); + return decideRemoteChildSend( + parent, + command, + baseFor, + remoteChild, + isProjectLeadThread(readModel, parent), + ); } if (pendingChildRequest(parent, command.childThreadId) !== undefined) { return refuse("That thread is still being set up. Send it a message once it has started."); @@ -539,6 +547,7 @@ export function decideChildSend( const refusal = childSendRefusal(parent, child, { from: command.from, callerTurnId: command.callerTurnId, + isLead: isProjectLeadThread(readModel, parent), }); if (refusal !== null || child === null) { return refuse(refusal?.detail ?? "That thread is gone."); @@ -679,6 +688,7 @@ function decideRemoteChildSend( command: CommandOf<"thread.child.send">, baseFor: ChildEventBase, remoteChild: NonNullable>, + isLead: boolean, ): ChildThreadDecision { const refusal = childSendRefusal( parent, @@ -688,7 +698,7 @@ function decideRemoteChildSend( attachedToParent: true, archivedAt: null, }, - { from: command.from, callerTurnId: command.callerTurnId }, + { from: command.from, callerTurnId: command.callerTurnId, isLead }, ); if (refusal !== null) { return refuse(refusal.detail); diff --git a/apps/server/src/orchestration/commandInvariants.ts b/apps/server/src/orchestration/commandInvariants.ts index 53899dec4..90ed771b9 100644 --- a/apps/server/src/orchestration/commandInvariants.ts +++ b/apps/server/src/orchestration/commandInvariants.ts @@ -6,6 +6,7 @@ import type { ProjectId, ThreadId, } from "@threadlines/contracts"; +import { projectLeadThreadId } from "@threadlines/shared/projectLead"; import * as Effect from "effect/Effect"; import { OrchestrationCommandInvariantError } from "./Errors.ts"; @@ -31,6 +32,18 @@ export function findProjectById( return readModel.projects.find((project) => project.id === projectId); } +/** Whether `thread` is its project's lead chat now (docs/design/lead-chat.md). */ +export function isProjectLeadThread( + readModel: OrchestrationReadModel, + thread: Pick, +): boolean { + return ( + projectLeadThreadId(findProjectById(readModel, thread.projectId), (threadId) => + findThreadById(readModel, threadId), + ) === thread.id + ); +} + export function listThreadsByProjectId( readModel: OrchestrationReadModel, projectId: ProjectId, diff --git a/apps/server/src/orchestration/decider.projectLead.test.ts b/apps/server/src/orchestration/decider.projectLead.test.ts new file mode 100644 index 000000000..99bf3d217 --- /dev/null +++ b/apps/server/src/orchestration/decider.projectLead.test.ts @@ -0,0 +1,215 @@ +import { + CommandId, + DEFAULT_PROVIDER_INTERACTION_MODE, + EMPTY_AGENT_REQUEST_STATE, + EMPTY_CHILD_REQUEST_STATE, + type OrchestrationCommand, + type OrchestrationEvent, + type OrchestrationReadModel, + type OrchestrationThread, + ProjectId, + ProviderInstanceId, + ThreadId, +} from "@threadlines/contracts"; +import { LEAD_MOVE_REFUSAL } from "@threadlines/shared/projectLead"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import { describe, expect, it } from "vite-plus/test"; + +import { isProjectLeadThread } from "./commandInvariants.ts"; +import { decideOrchestrationCommand } from "./decider.ts"; +import { projectEvent } from "./projector.ts"; +import { threadMoveRefusals } from "./threadMoveDecisions.ts"; + +const now = "2026-11-16T10:00:00.000Z"; +const projectId = ProjectId.make("project-1"); +const LEAD = ThreadId.make("lead"); +const OTHER = ThreadId.make("other"); +const CHILD = ThreadId.make("child"); +const model = { instanceId: ProviderInstanceId.make("claudeAgent"), model: "opus-5-5" }; + +function thread(id: ThreadId, overrides: Partial = {}): OrchestrationThread { + return { + id, + projectId, + title: id, + modelSelection: model, + runtimeMode: "auto-accept-edits", + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: null, + worktreePath: null, + effectiveCwd: null, + goal: null, + latestTurn: null, + createdAt: now, + updatedAt: now, + archivedAt: null, + pinnedAt: null, + pullRequestAutoFix: false, + pullRequestAutoMerge: null, + linkedPullRequests: [], + agentRequests: EMPTY_AGENT_REQUEST_STATE, + parentThreadId: null, + parentTurnId: null, + attachedToParent: false, + parentAttachmentEpoch: 0, + handedBackAt: null, + handedBackTurnId: null, + archivedWithParentAt: null, + childRequests: EMPTY_CHILD_REQUEST_STATE, + participants: [], + doneOverride: null, + lastSeenAt: null, + deletedAt: null, + messages: [], + proposedPlans: [], + activities: [], + checkpoints: [], + diffStatBaselineTurnCount: 0, + session: null, + ...overrides, + }; +} + +function readModel(threads: ReadonlyArray): OrchestrationReadModel { + return { + snapshotSequence: 1, + updatedAt: now, + projects: [ + { + id: projectId, + kind: "workspace", + title: "threadlines", + workspaceRoot: "/repo", + defaultModelSelection: null, + scripts: [], + createdAt: now, + updatedAt: now, + deletedAt: null, + }, + ], + threads, + }; +} + +type Planned = Omit; + +async function run(current: OrchestrationReadModel, command: OrchestrationCommand) { + const decided = await Effect.runPromise( + decideOrchestrationCommand({ command, readModel: current }), + ); + const events = (Array.isArray(decided) ? decided : [decided]) as ReadonlyArray; + let next = current; + let sequence = current.snapshotSequence; + for (const event of events) { + sequence += 1; + next = await Effect.runPromise( + projectEvent(next, { ...event, sequence } as OrchestrationEvent), + ); + } + return { events, model: next }; +} + +const refusal = async (current: OrchestrationReadModel, command: OrchestrationCommand) => { + const exit = await Effect.runPromiseExit( + decideOrchestrationCommand({ command, readModel: current }), + ); + return Exit.isFailure(exit) ? JSON.stringify(exit.cause) : null; +}; + +const setLead = (threadId: ThreadId | null): OrchestrationCommand => ({ + type: "project.lead.set", + commandId: CommandId.make(`lead-${threadId ?? "none"}`), + projectId, + threadId, +}); + +const leadOf = (current: OrchestrationReadModel) => + current.projects.find((project) => project.id === projectId)?.leadThreadId ?? null; + +describe("project lead chat", () => { + it("names a lead, replaces it in one event, and stops having one", async () => { + const start = readModel([thread(LEAD), thread(OTHER)]); + const first = await run(start, setLead(LEAD)); + expect(leadOf(first.model)).toBe(LEAD); + expect(isProjectLeadThread(first.model, thread(LEAD))).toBe(true); + + const replaced = await run(first.model, setLead(OTHER)); + expect(replaced.events).toHaveLength(1); + expect(leadOf(replaced.model)).toBe(OTHER); + expect(isProjectLeadThread(replaced.model, thread(LEAD))).toBe(false); + + const cleared = await run(replaced.model, setLead(null)); + expect(leadOf(cleared.model)).toBeNull(); + }); + + it("refuses a thread another thread owns, an archived one, and General Chats", async () => { + const owned = thread(CHILD, { parentThreadId: LEAD, attachedToParent: true }); + const archived = thread(OTHER, { archivedAt: now }); + const start = readModel([thread(LEAD), owned, archived]); + expect(await refusal(start, setLead(CHILD))).toContain("belongs to the thread that started"); + expect(await refusal(start, setLead(OTHER))).toContain("Archived threads"); + + const generalChats = { + ...start, + projects: start.projects.map((project) => ({ ...project, kind: "general-chat" as const })), + }; + expect(await refusal(generalChats, setLead(LEAD))).not.toBeNull(); + }); + + it("ends the lead when its thread is archived or deleted", async () => { + const start = (await run(readModel([thread(LEAD)]), setLead(LEAD))).model; + const archived = await run(start, { + type: "thread.archive", + commandId: CommandId.make("archive"), + threadId: LEAD, + }); + expect(leadOf(archived.model)).toBeNull(); + // Coming back from the archive does not make it the lead again. + const unarchived = await run(archived.model, { + type: "thread.unarchive", + commandId: CommandId.make("unarchive"), + threadId: LEAD, + }); + expect(leadOf(unarchived.model)).toBeNull(); + + const deleted = await run(start, { + type: "thread.delete", + commandId: CommandId.make("delete"), + threadId: LEAD, + }); + expect(leadOf(deleted.model)).toBeNull(); + }); + + it("reads a pointer at an archived or missing thread as no lead", () => { + const ghost = readModel([thread(LEAD, { archivedAt: now })]); + const pointing = { + ...ghost, + projects: ghost.projects.map((project) => ({ ...project, leadThreadId: LEAD })), + }; + expect(isProjectLeadThread(pointing, thread(LEAD))).toBe(false); + const missing = { ...pointing, threads: [] }; + expect(isProjectLeadThread(missing, thread(LEAD))).toBe(false); + }); + + it("keeps the lead top-level and on this computer", async () => { + const separated = thread(LEAD, { parentThreadId: OTHER, attachedToParent: false }); + const start = (await run(readModel([thread(OTHER), separated]), setLead(LEAD))).model; + expect( + await refusal(start, { + type: "thread.parent-attachment.set", + commandId: CommandId.make("attach"), + threadId: LEAD, + attached: true, + createdAt: now, + }), + ).toContain("lead chat"); + + const lead = start.threads.find((entry) => entry.id === LEAD)!; + expect(threadMoveRefusals(start, lead)).toContainEqual({ + kind: "blocked", + code: "lead", + words: LEAD_MOVE_REFUSAL, + }); + }); +}); diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts index 44551aefa..4aaee8332 100644 --- a/apps/server/src/orchestration/decider.ts +++ b/apps/server/src/orchestration/decider.ts @@ -15,6 +15,7 @@ import { SIDE_ANSWER_OUTCOME_ACTIVITY_KIND, type SideTurnId, TurnId, + type ThreadId, type ThreadParticipantId, } from "@threadlines/contracts"; import { saferRuntimeMode } from "@threadlines/shared/runtimeMode"; @@ -48,6 +49,7 @@ import { import { isTurnAside } from "@threadlines/shared/transcriptRevert"; import { CONTINUE_AT_RESET_MESSAGE, continueAtResetTimeMs } from "@threadlines/shared/usageLimits"; import { isAttachedChild } from "@threadlines/shared/childThreads"; +import { leadSetRefusal } from "@threadlines/shared/projectLead"; import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests"; import { OrchestrationCommandInvariantError } from "./Errors.ts"; @@ -67,6 +69,7 @@ import { } from "./agentRequestDecisions.ts"; import { findProjectById, + isProjectLeadThread, listThreadsByProjectId, requireNonNegativeInteger, requireProject, @@ -880,6 +883,37 @@ function holdCommandOutputOnStop( })); } +/** + * Clears the lead pointer of every project that names one of `threadIds` + * (docs/design/lead-chat.md: archive and delete end a lead in the same + * decision). Reads the raw pointer, so a stale one is cleaned up too. + */ +function leadClearEvents( + readModel: OrchestrationReadModel, + threadIds: ReadonlyArray, + commandId: OrchestrationCommand["commandId"], + occurredAt: string, +): PlannedOrchestrationEvent[] { + return readModel.projects + .filter( + (project) => + project.deletedAt === null && + project.leadThreadId !== undefined && + project.leadThreadId !== null && + threadIds.includes(project.leadThreadId), + ) + .map((project) => ({ + ...withEventBase({ + aggregateKind: "project", + aggregateId: project.id, + occurredAt, + commandId, + }), + type: "project.meta-updated" as const, + payload: { projectId: project.id, leadThreadId: null, updatedAt: occurredAt }, + })); +} + export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand")(function* ({ command, readModel, @@ -984,6 +1018,44 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" }; } + case "project.lead.set": { + const project = yield* requireWorkspaceProject({ + readModel, + command, + projectId: command.projectId, + }); + if (command.threadId !== null) { + const thread = yield* requireThread({ + readModel, + command, + threadId: command.threadId, + }); + const refusal = leadSetRefusal(project, thread); + if (refusal !== null) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: refusal, + }); + } + } + // One pointer: naming a new lead replaces the old one in this event. + const occurredAt = yield* nowIso; + return { + ...withEventBase({ + aggregateKind: "project", + aggregateId: command.projectId, + occurredAt, + commandId: command.commandId, + }), + type: "project.meta-updated", + payload: { + projectId: command.projectId, + leadThreadId: command.threadId, + updatedAt: occurredAt, + }, + }; + } + case "project.delete": { yield* requireWorkspaceProject({ readModel, @@ -1445,9 +1517,10 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" })), }) : []; - return familyEvents.length === 0 && childDeletes.length === 0 + const leadEvents = leadClearEvents(readModel, [thread.id], command.commandId, occurredAt); + return familyEvents.length === 0 && childDeletes.length === 0 && leadEvents.length === 0 ? deletedEvent - : [...familyEvents, ...childDeletes, deletedEvent]; + : [...familyEvents, ...childDeletes, ...leadEvents, deletedEvent]; } case "thread.archive": { @@ -1523,7 +1596,15 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" ]; }), ]; - return familyEvents.length === 0 ? archivedEvent : [...familyEvents, archivedEvent]; + const leadEvents = leadClearEvents( + readModel, + [thread.id, ...plan.archive.map((child) => child.id)], + command.commandId, + occurredAt, + ); + return familyEvents.length === 0 && leadEvents.length === 0 + ? archivedEvent + : [...familyEvents, ...leadEvents, archivedEvent]; } case "thread.unarchive": { @@ -2419,6 +2500,13 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand" command, threadId: command.threadId, }); + // A lead chat is top-level by definition. + if (command.attached && isProjectLeadThread(readModel, thread)) { + return yield* new OrchestrationCommandInvariantError({ + commandType: command.type, + detail: "This is the project's lead chat. Pick another lead first.", + }); + } return yield* planChildThreadDecision( command.type, decideParentAttachmentSet( diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts index 68f653d0c..e17319969 100644 --- a/apps/server/src/orchestration/projector.ts +++ b/apps/server/src/orchestration/projector.ts @@ -392,6 +392,9 @@ export function projectEvent( ...(payload.phoneAlertsMuted !== undefined ? { phoneAlertsMuted: payload.phoneAlertsMuted } : {}), + ...(payload.leadThreadId !== undefined + ? { leadThreadId: payload.leadThreadId } + : {}), updatedAt: payload.updatedAt, } : project, diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts index 01538ec1b..07ead7aae 100644 --- a/apps/server/src/orchestration/threadMoveDecisions.ts +++ b/apps/server/src/orchestration/threadMoveDecisions.ts @@ -11,6 +11,7 @@ * `thread.move.start` ends the pending move as it freezes the thread. Each * function returns the events to plan, or a refusal to report. */ +import { LEAD_MOVE_REFUSAL } from "@threadlines/shared/projectLead"; import { EventId, type OrchestrationCommand, @@ -69,7 +70,8 @@ export type ThreadMoveBlockCode = | "goal" | "check_back" | "command_request" - | "pull_request_automation"; + | "pull_request_automation" + | "lead"; /** * One reason a thread can't move right now. A `wait` goes away on its own @@ -112,7 +114,10 @@ const blocked = (code: ThreadMoveBlockCode, words: string): ThreadMoveRefusalEnt /** What the move checks read: the projects, and the threads they can see. */ export interface ThreadMoveView { readonly projects: ReadonlyArray< - Pick + Pick< + OrchestrationReadModel["projects"][number], + "id" | "kind" | "workspaceRoot" | "leadThreadId" + > >; readonly threads: ReadonlyArray; } @@ -155,6 +160,10 @@ export function threadMoveRefusals( if (project?.kind === "general-chat") { found.push(blocked("general_chat", "General chats can't move yet.")); } + // Words only: the move's refusal code is a closed set older peers decode. + if ((project?.leadThreadId ?? null) === thread.id && thread.archivedAt === null) { + found.push(blocked("lead", LEAD_MOVE_REFUSAL)); + } if (isRoomThread(thread) || thread.agentRequests.open.length > 0) { found.push(blocked("room", "Threads with more than one agent can't move yet.")); } diff --git a/apps/server/src/persistence/Layers/ProjectionProjects.ts b/apps/server/src/persistence/Layers/ProjectionProjects.ts index 9c65d5c9e..ad2936949 100644 --- a/apps/server/src/persistence/Layers/ProjectionProjects.ts +++ b/apps/server/src/persistence/Layers/ProjectionProjects.ts @@ -39,6 +39,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () { default_model_selection_json, scripts_json, phone_alerts_muted, + lead_thread_id, created_at, updated_at, deleted_at @@ -51,6 +52,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () { ${row.defaultModelSelection !== null ? JSON.stringify(row.defaultModelSelection) : null}, ${JSON.stringify(row.scripts)}, ${row.phoneAlertsMuted === true ? 1 : 0}, + ${row.leadThreadId ?? null}, ${row.createdAt}, ${row.updatedAt}, ${row.deletedAt} @@ -63,6 +65,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () { default_model_selection_json = excluded.default_model_selection_json, scripts_json = excluded.scripts_json, phone_alerts_muted = excluded.phone_alerts_muted, + lead_thread_id = excluded.lead_thread_id, created_at = excluded.created_at, updated_at = excluded.updated_at, deleted_at = excluded.deleted_at @@ -82,6 +85,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () { default_model_selection_json AS "defaultModelSelection", scripts_json AS "scripts", phone_alerts_muted AS "phoneAlertsMuted", + lead_thread_id AS "leadThreadId", created_at AS "createdAt", updated_at AS "updatedAt", deleted_at AS "deletedAt" @@ -103,6 +107,7 @@ const makeProjectionProjectRepository = Effect.gen(function* () { default_model_selection_json AS "defaultModelSelection", scripts_json AS "scripts", phone_alerts_muted AS "phoneAlertsMuted", + lead_thread_id AS "leadThreadId", created_at AS "createdAt", updated_at AS "updatedAt", deleted_at AS "deletedAt" diff --git a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts index d11c7696f..4480ed7b6 100644 --- a/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts +++ b/apps/server/src/persistence/Layers/ProjectionRepositories.test.ts @@ -47,6 +47,33 @@ projectionRepositoriesLayer("Projection repositories", (it) => { }), ); + it.effect("keeps a project's lead chat across a restart, and clears it", () => + Effect.gen(function* () { + const projects = yield* ProjectionProjectRepository; + const project = { + projectId: ProjectId.make("project-lead"), + kind: "workspace" as const, + title: "Lead", + workspaceRoot: "/tmp/project-lead", + defaultModelSelection: null, + scripts: [], + createdAt: "2026-11-16T00:00:00.000Z", + updatedAt: "2026-11-16T00:00:00.000Z", + deletedAt: null, + }; + const read = projects + .getById({ projectId: project.projectId }) + .pipe(Effect.map((row) => Option.getOrThrow(row).leadThreadId ?? null)); + + yield* projects.upsert(project); + assert.strictEqual(yield* read, null); + yield* projects.upsert({ ...project, leadThreadId: ThreadId.make("thread-lead") }); + assert.strictEqual(yield* read, "thread-lead"); + yield* projects.upsert({ ...project, leadThreadId: null }); + assert.strictEqual(yield* read, null); + }), + ); + it.effect("stores SQL NULL for missing project model options", () => Effect.gen(function* () { const projects = yield* ProjectionProjectRepository; diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 97027b489..d4613280e 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -135,6 +135,7 @@ import Migration0112 from "./Migrations/112_ThreadMoveBatches.ts"; import Migration0113 from "./Migrations/113_LinkMoveStagedApproval.ts"; import Migration0114 from "./Migrations/114_LinkMoveAbortCode.ts"; import Migration0115 from "./Migrations/115_ThreadNativeSession.ts"; +import Migration0116 from "./Migrations/116_ProjectLeadThread.ts"; /** * Migration loader with all migrations defined inline. @@ -262,6 +263,7 @@ export const migrationEntries = [ [113, "LinkMoveStagedApproval", Migration0113], [114, "LinkMoveAbortCode", Migration0114], [115, "ThreadNativeSession", Migration0115], + [116, "ProjectLeadThread", Migration0116], ] as const; /** Highest id in the full registry, so the "n of total" count is the real total. */ diff --git a/apps/server/src/persistence/Migrations/116_ProjectLeadThread.ts b/apps/server/src/persistence/Migrations/116_ProjectLeadThread.ts new file mode 100644 index 000000000..0b9c562fa --- /dev/null +++ b/apps/server/src/persistence/Migrations/116_ProjectLeadThread.ts @@ -0,0 +1,15 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * A project's lead chat (`OrchestrationProject.leadThreadId`, + * docs/design/lead-chat.md): `lead_thread_id` on `projection_projects`, null + * for every project before. Events rebuild it, like the project's other + * fields. + * + * A new nullable column; no row is rewritten. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + yield* sql`ALTER TABLE projection_projects ADD COLUMN lead_thread_id TEXT`; +}); diff --git a/apps/server/src/persistence/Services/ProjectionProjects.ts b/apps/server/src/persistence/Services/ProjectionProjects.ts index 56a7a8ed8..bb6438c93 100644 --- a/apps/server/src/persistence/Services/ProjectionProjects.ts +++ b/apps/server/src/persistence/Services/ProjectionProjects.ts @@ -12,6 +12,7 @@ import { ProjectId, ProjectKind, ProjectScript, + ThreadId, } from "@threadlines/contracts"; import * as Option from "effect/Option"; import * as Schema from "effect/Schema"; @@ -29,6 +30,8 @@ export const ProjectionProject = Schema.Struct({ scripts: Schema.Array(ProjectScript), /** Left out when writing a new project: it isn't muted. */ phoneAlertsMuted: Schema.optional(Schema.Boolean), + /** The project's lead chat; left out or null when it has none. */ + leadThreadId: Schema.optional(Schema.NullOr(ThreadId)), createdAt: IsoDateTime, updatedAt: IsoDateTime, deletedAt: Schema.NullOr(IsoDateTime), diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 2a312aa6c..85451ff04 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -24,6 +24,7 @@ import { usePublishMainAreaStart } from "../mainAreaLayout"; import { useServerKeybindings } from "../rpc/serverState"; import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore"; import { buildThreadRouteParams } from "../threadRoutes"; +import { readLeadChatTarget } from "../leadChat"; import { selectSidebarListShown, useUiStateStore } from "../uiStateStore"; import ThreadSidebar from "./Sidebar"; import { AppTitleBar } from "./sidebar/AppTitleBar"; @@ -111,12 +112,20 @@ function AppShellCommands({ hasList }: { readonly hasList: boolean }) { event.stopPropagation(); void navigate({ to: "/scheduled" }); } + if (command === "navigate.leadChat") { + // The lead of the open thread's project, else of the scoped project. + const leadRef = readLeadChatTarget(routeThreadRef ?? null, defaultProjectRef ?? null); + if (leadRef === null) return; + event.preventDefault(); + event.stopPropagation(); + void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(leadRef) }); + } }; window.addEventListener("keydown", onWindowKeyDown); return () => { window.removeEventListener("keydown", onWindowKeyDown); }; - }, [appHistory, keybindings, navigate, routeThreadRef, toggleList]); + }, [appHistory, defaultProjectRef, keybindings, navigate, routeThreadRef, toggleList]); useEffect(() => { const onMenuAction = window.desktopBridge?.onMenuAction; diff --git a/apps/web/src/components/ChatView.browser-harness.tsx b/apps/web/src/components/ChatView.browser-harness.tsx index bdf97e9fc..e0a93d6a9 100644 --- a/apps/web/src/components/ChatView.browser-harness.tsx +++ b/apps/web/src/components/ChatView.browser-harness.tsx @@ -909,6 +909,7 @@ export function toShellSnapshot(snapshot: OrchestrationReadModel) { ...(project.phoneAlertsMuted !== undefined ? { phoneAlertsMuted: project.phoneAlertsMuted } : {}), + ...(project.leadThreadId !== undefined ? { leadThreadId: project.leadThreadId } : {}), createdAt: project.createdAt, updatedAt: project.updatedAt, })), diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx index 4fec1cd3f..f622a6636 100644 --- a/apps/web/src/components/ChatView.sidebar.browser.tsx +++ b/apps/web/src/components/ChatView.sidebar.browser.tsx @@ -236,6 +236,82 @@ describe("ChatView (full app): sidebar", () => { } }); + it("shows the project's lead chat, and its menu stops it or names another thread instead", async () => { + const otherThreadId = "thread-lead-other" as ThreadId; + const withThreads = addThreadToSnapshot( + createSnapshotForTargetUser({ + targetMessageId: "msg-user-lead-target" as MessageId, + targetText: "lead target", + }), + otherThreadId, + ); + const capabilities = { repositoryIdentity: true, projectLead: true }; + const mounted = await mountChatView({ + viewport: DEFAULT_VIEWPORT, + snapshot: { + ...withThreads, + projects: withThreads.projects.map((project) => ({ ...project, leadThreadId: THREAD_ID })), + }, + configureFixture: (nextFixture) => { + nextFixture.serverConfig = { + ...nextFixture.serverConfig, + environment: { ...nextFixture.serverConfig.environment, capabilities }, + }; + nextFixture.welcome = { + ...nextFixture.welcome, + environment: { ...nextFixture.welcome.environment, capabilities }, + }; + }, + }); + const openRowMenu = async (threadId: ThreadId) => { + const row = await waitForElement( + () => document.querySelector(`[data-testid="thread-row-${threadId}"]`), + "The thread's sidebar row should be on screen.", + ); + const rect = row.getBoundingClientRect(); + row.dispatchEvent( + new MouseEvent("contextmenu", { + bubbles: true, + cancelable: true, + clientX: rect.left + 20, + clientY: rect.top + 8, + }), + ); + }; + const leadSets = () => + wsRequests.flatMap((request) => + request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand && + request.type === "project.lead.set" + ? [request.threadId] + : [], + ); + + try { + // The lead's row carries its mark and comes first; the chat says what it is. + await expect.element(page.getByTestId(`thread-lead-mark-${THREAD_ID}`)).toBeVisible(); + await expect.element(page.getByTestId("lead-chat-chip")).toBeVisible(); + const rowIds = [ + ...document.querySelectorAll('[data-testid^="thread-row-"]'), + ].map((row) => row.dataset.testid); + expect(rowIds[0]).toBe(`thread-row-${THREAD_ID}`); + + await openRowMenu(otherThreadId); + await page + .getByRole("button", { + name: `Make this the lead chat instead of ${THREAD_TITLE}`, + exact: true, + }) + .click(); + await vi.waitFor(() => expect(leadSets()).toEqual([otherThreadId])); + + 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])); + } finally { + await mounted.cleanup(); + } + }); + it("narrows the live list to rooms from the View button and marks it while it does", async () => { const mounted = await mountChatView({ viewport: DEFAULT_VIEWPORT, diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 15ec85b70..d060fea2b 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -160,6 +160,7 @@ import { selectWorkspaceProjectsAcrossEnvironments, useStore, } from "../store"; +import { readLeadProjectName } from "../leadChat"; import { createProjectSelectorByRef, createThreadSelectorByRef } from "../storeSelectors"; import { useUiStateStore } from "../uiStateStore"; import { @@ -2221,6 +2222,9 @@ export default function ChatView(props: ChatViewProps) { const parentEnvironmentId = remoteOrigin?.environmentId ?? environmentId; const parentThreadId = remoteOrigin?.threadId ?? activeThread?.parentThreadId ?? null; const knownParentTitle = useThreadTitle(parentEnvironmentId, parentThreadId); + const isLeadChat = useStore( + (state) => activeThreadRef !== null && readLeadProjectName(state, activeThreadRef) !== null, + ); const parentHeaderContext = useMemo(() => { if (parentThreadId === null) return null; const parentThreadRef = scopeThreadRef(parentEnvironmentId, parentThreadId); @@ -8768,6 +8772,7 @@ export default function ChatView(props: ChatViewProps) { taskProgress={taskProgress} forkContext={forkHeaderContext} parentContext={parentHeaderContext} + isLeadChat={isLeadChat} outsideOrigin={activeThread.outsideOrigin ?? null} onOpenParentThread={headerHandlers.onOpenParentThread} backgroundRuns={headerBackgroundRuns} diff --git a/apps/web/src/components/CommandPaletteDialog.tsx b/apps/web/src/components/CommandPaletteDialog.tsx index f3ab4f90d..dc60e082e 100644 --- a/apps/web/src/components/CommandPaletteDialog.tsx +++ b/apps/web/src/components/CommandPaletteDialog.tsx @@ -59,6 +59,7 @@ import { Trash2Icon, UsersRoundIcon, MonitorUpIcon, + FlagIcon, FolderSyncIcon, WaypointsIcon, CalendarClockIcon, @@ -101,6 +102,12 @@ import { holdThreadDetailForOpen, prewarmHighlightedThread } from "../environmen import { useHandleNewThread } from "../hooks/useHandleNewThread"; import { useInboxThreads } from "../hooks/useInboxThreads"; import { useThreadMenu } from "../hooks/useThreadMenu"; +import { + createLeadChat, + environmentSupportsProjectLead, + leadSettingRefusal, + projectLeadRef, +} from "../leadChat"; import { useWorktreePickup } from "../hooks/useWorktreePickup"; import type { ThreadMenuAction } from "./threadMenu.logic"; import { useIsMobile } from "../hooks/useMediaQuery"; @@ -470,9 +477,18 @@ function getAddProjectCloneDirectoryName( const PALETTE_THREAD_ACTIONS: Partial< Record< ThreadMenuAction, - { readonly title: string; readonly searchTerms: string[]; readonly icon: ReactNode } + { + /** Absent: the menu item's own words, for an action whose words change. */ + readonly title?: string; + readonly searchTerms: string[]; + readonly icon: ReactNode; + } > > = { + lead: { + searchTerms: ["lead chat", "lead", "coordinate", "project lead"], + icon: , + }, rename: { title: "Rename thread", searchTerms: ["rename", "title", "name"], @@ -2197,7 +2213,7 @@ export function OpenCommandPaletteDialog() { kind: "action", value: `action:thread-${item.id}`, searchTerms: offered.searchTerms, - title: offered.title, + title: offered.title ?? item.label, icon: offered.icon, run: async () => { await threadMenu.run(item.id, target); @@ -2206,6 +2222,68 @@ export function OpenCommandPaletteDialog() { } } + // Lead chats (docs/design/lead-chat.md): one "Go to" per project that has + // one, and "New lead chat" for the project in scope when it has none. + for (const project of projects) { + const leadRef = projectLeadRef(useStore.getState(), project); + if (leadRef === null) continue; + actionItems.push({ + kind: "action", + value: `action:lead-chat:${scopedThreadKey(leadRef)}`, + searchTerms: ["lead chat", "lead", project.name], + title: "Go to lead chat", + description: project.name, + icon: , + shortcutCommand: "navigate.leadChat", + run: async () => { + await navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(leadRef), + }); + }, + }); + } + 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); + if ( + leadScopeProject !== undefined && + leadScopeProject.kind === "workspace" && + environmentSupportsProjectLead(leadScopeProject.environmentId) && + leadSettingRefusal(leadScopeProject.environmentId) === null && + projectLeadRef(useStore.getState(), leadScopeProject) === null + ) { + actionItems.push({ + kind: "action", + value: "action:new-lead-chat", + searchTerms: ["new lead chat", "lead chat", "lead", "coordinate"], + title: "New lead chat", + description: leadScopeProject.name, + icon: , + run: async () => { + const leadRef = await createLeadChat(leadScopeProject); + if (leadRef !== null) { + await navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(leadRef), + }); + } + }, + }); + } + actionItems.push({ kind: "action", value: "action:usage", diff --git a/apps/web/src/components/Sidebar.logic.test.ts b/apps/web/src/components/Sidebar.logic.test.ts index 49b73c2e4..15cd46e0a 100644 --- a/apps/web/src/components/Sidebar.logic.test.ts +++ b/apps/web/src/components/Sidebar.logic.test.ts @@ -1269,6 +1269,19 @@ describe("inbox done lifecycle", () => { ).toBe(true); }); + it("keeps a project's lead chat like a pinned thread: no idle or landing filing", () => { + const stale = { ...base, latestUserMessageAt: "2026-07-24T12:00:00.000Z" }; + const options = { + now: NOW, + autoDoneAfterDays: 2, + pullRequestSettledAt: "2026-07-28T11:30:00.000Z", + lead: true, + }; + expect(isThreadDone(stale, null, options)).toBe(false); + // The user's own word still files it. + expect(isThreadDone(stale, { state: "done", at: NOW }, options)).toBe(true); + }); + it("files a thread at once when its pull request lands, unless it is pinned", () => { // A merged branch is finished work: it does not wait out the idle timer. const fresh = { ...base, latestUserMessageAt: "2026-07-28T11:00:00.000Z" }; @@ -1651,6 +1664,23 @@ describe("the inbox's sorts", () => { ]); }); + it("puts a project's lead chat first in every sort, ahead of the pins", () => { + const threads = [ + thread("quiet-lead", 1), + thread("busy", 2, { lastMessageDay: 29 }), + thread("pinned", 3, { pinned: true }), + ]; + const isLead = (entry: { readonly id: string }) => entry.id === "quiet-lead"; + expect(ids(sortInboxThreadsBy(threads, "recent", [], isLead))).toEqual([ + "quiet-lead", + "pinned", + "busy", + ]); + expect( + ids(sortInboxThreadsBy(threads, "custom", [key("busy"), key("quiet-lead")], isLead)), + ).toEqual(["quiet-lead", "pinned", "busy"]); + }); + it("keeps a custom order through activity, with threads it hasn't placed at the bottom", () => { const threads = [ thread("second", 1, { lastMessageDay: 29 }), diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.ts index 513cfd265..ad8f3c5a3 100644 --- a/apps/web/src/components/Sidebar.logic.ts +++ b/apps/web/src/components/Sidebar.logic.ts @@ -877,6 +877,11 @@ export function isThreadDone( * threads" is on: whether that parent is wrapped. Absent: rule 4 is off. */ readonly childWrapUp?: { readonly parentDone: boolean } | null; + /** + * Its project's lead chat (docs/design/lead-chat.md): kept like a pinned + * thread, so no idle or pull request rule files it away. + */ + readonly lead?: boolean; }, ): boolean { const childWrapUp = options.childWrapUp ?? null; @@ -890,7 +895,7 @@ export function isThreadDone( { held: () => !canMarkThreadDone(thread, { now: options.now, handedBackCompletionSeen }), freshOverride: () => freshThreadDoneOverride(thread, override), - pinned: thread.pinnedAt !== null, + pinned: thread.pinnedAt !== null || options.lead === true, childFinished: childWrapUp !== null && (handedBackCompletionSeen || childWrapUp.parentDone), filedByPullRequest: () => isFiledByPullRequest(thread, override, options.pullRequestSettledAt), @@ -1061,6 +1066,8 @@ export function fileInboxThreads(input: { readonly wrapUpIdleThreads: boolean; /** When the thread's pull requests landed, if a landing should file it; null otherwise. */ readonly pullRequestSettledAt: (thread: SidebarThreadSummary, threadKey: string) => string | null; + /** Scoped keys of the projects' lead chats; see `staysOnTop`. */ + readonly leadThreadKeys?: ReadonlySet; }): FiledInboxThread[] { const prepared = input.threads.map((thread) => { const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)); @@ -1097,6 +1104,7 @@ export function fileInboxThreads(input: { autoDoneAfterDays: input.wrapUpIdleThreads ? INBOX_AUTO_DONE_AFTER_DAYS : null, pullRequestSettledAt: input.pullRequestSettledAt(item.thread, item.threadKey), childWrapUp, + lead: input.leadThreadKeys?.has(item.threadKey) === true, }, ); doneByKey.set(item.threadKey, isDone); @@ -1132,6 +1140,18 @@ export function isUnreadFinishedWork(entry: { }); } +/** + * Whether an inbox row stays at the top of its list: pinned, or its project's + * lead chat (docs/design/lead-chat.md). The sort, the fold, the custom order + * and the line under the pins all read this one rule. + */ +export function staysOnTop(entry: { + readonly thread: { readonly pinnedAt: string | null }; + readonly isLead?: boolean | undefined; +}): boolean { + return entry.thread.pinnedAt !== null || entry.isLead === true; +} + /** * Pins are a deliberate, stable group at the top. Everything else tracks the * user's latest message rather than background agent activity. @@ -1182,6 +1202,17 @@ export function sortInboxThreadsBy( threads: readonly T[], sort: InboxSort, customOrder: readonly string[], + /** A project's lead chat goes first, ahead of the pins, in every sort. */ + isLead: (thread: T) => boolean = () => false, +): T[] { + const sorted = sortInboxThreadsWithoutLeads(threads, sort, customOrder); + return [...sorted.filter(isLead), ...sorted.filter((thread) => !isLead(thread))]; +} + +function sortInboxThreadsWithoutLeads( + threads: readonly T[], + sort: InboxSort, + customOrder: readonly string[], ): T[] { if (sort === "recent") { return sortInboxThreads(threads); @@ -1298,16 +1329,26 @@ export function trimInboxCustomOrder( /** The rows a live row can swap with: under the same group header, on the same side of the pins. */ export function inboxCustomOrderPeers< - R extends { readonly entry: { readonly threadKey: string; readonly thread: InboxSortInput } }, + R extends { + readonly entry: { + readonly threadKey: string; + readonly thread: InboxSortInput; + readonly isLead?: boolean | undefined; + }; + }, >(rows: readonly R[], threadKey: string, groupKeyOf: (row: R) => string | null): string[] { const row = rows.find((candidate) => candidate.entry.threadKey === threadKey); if (row === undefined) return []; + // The lead chat has no peers: it stays first. + if (row.entry.isLead === true) return []; const group = groupKeyOf(row); - const pinned = row.entry.thread.pinnedAt !== null; + const pinned = staysOnTop(row.entry); return rows .filter( (candidate) => - (candidate.entry.thread.pinnedAt !== null) === pinned && groupKeyOf(candidate) === group, + candidate.entry.isLead !== true && + staysOnTop(candidate.entry) === pinned && + groupKeyOf(candidate) === group, ) .map((candidate) => candidate.entry.threadKey); } @@ -2495,12 +2536,17 @@ export function groupInboxLiveRows( /** How many lines between pinned and unpinned rows the list draws: one per group with both. */ export function countInboxPinDividers< - R extends { readonly entry: { readonly thread: { readonly pinnedAt: string | null } } }, + R extends { + readonly entry: { + readonly thread: { readonly pinnedAt: string | null }; + readonly isLead?: boolean | undefined; + }; + }, >(rows: readonly R[], groupKeyOf: (row: R) => string | null): number { const pinned = new Set(); const unpinned = new Set(); for (const row of rows) { - (row.entry.thread.pinnedAt === null ? unpinned : pinned).add(groupKeyOf(row)); + (staysOnTop(row.entry) ? pinned : unpinned).add(groupKeyOf(row)); } return [...pinned].filter((group) => unpinned.has(group)).length; } diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 7ccd1b443..10d8a8db9 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -103,6 +103,7 @@ import { shouldClearThreadSelectionOnMouseDown, sortDoneThreads, sortInboxThreadsBy, + staysOnTop, describeInboxGroupMenu, countInboxPinDividers, moveInInboxGroupOrder, @@ -470,6 +471,15 @@ function InboxWrappedDayLabel({ group }: { group: WrappedDayGroup }) { ); } +/** + * Where a row says its work lives: a project's lead chat says "Lead" there, + * with the project's name when the row names one ("Lead · threadlines"). + */ +function leadRowPlace(isLead: boolean, projectLabel: string | null): string | null { + if (!isLead) return projectLabel; + return projectLabel === null ? "Lead" : `Lead · ${projectLabel}`; +} + /** What the line between pinned and unpinned rows takes up; see {@link InboxPinDivider}. */ const INBOX_PIN_DIVIDER_PX = 5; @@ -942,6 +952,7 @@ export default function Sidebar() { heads.map((entry) => entry.thread), inboxSort, inboxCustomOrder, + (thread) => lookup(thread).isLead, ).map(lookup), sortDone: (heads) => sortDoneThreads( @@ -1029,10 +1040,11 @@ export default function Sidebar() { const hiddenByGroup = groupKey !== null && collapsedInboxGroups[groupKey] === true && + !row.entry.isLead && !inboxLiveRowHolds(row, routeThreadKey); const isFamily = row.children.length > 0 || row.remoteChildren.length > 0; return { - pinned: row.entry.thread.pinnedAt !== null, + pinned: staysOnTop(row.entry), alwaysShown: inboxLiveRowHasAttention(row) || inboxLiveRowHolds(row, routeThreadKey) || @@ -1084,7 +1096,7 @@ export default function Sidebar() { inboxLiveRowHasAttention(row) || inboxLiveRowHolds(row, routeThreadKey) || inboxLiveRowHolds(row, renamingThreadKey), - isPinned: (row) => row.entry.thread.pinnedAt !== null, + isPinned: (row) => staysOnTop(row.entry), limit: liveFoldLimit + revealedLiveCount, // New threads go to the bottom of a custom order, so a fold would hide // the newest ones. Every row there is where the user put it. @@ -1297,9 +1309,11 @@ export default function Sidebar() { working: counts.working, collapsed, }, + // A folded group still shows its project's lead chat: it never folds. rows: collapsed ? group.rows.filter( (row) => + row.entry.isLead || row.entry.threadKey === routeThreadKey || inboxLiveRowHoldsOpenChild(row, routeThreadKey), ) @@ -2250,8 +2264,9 @@ export default function Sidebar() { rowIndex, ) => ( - {entry.thread.pinnedAt === null && - section.rows[rowIndex - 1]?.entry.thread.pinnedAt != null ? ( + {!staysOnTop(entry) && + section.rows[rowIndex - 1] !== undefined && + staysOnTop(section.rows[rowIndex - 1]!.entry) ? ( ) : null} @@ -2262,9 +2277,11 @@ export default function Sidebar() { // header right above it already does. Scoped // to projects, it still names it: the menu that // says so is out of sight. - projectLabel={ - sidebarGrouping !== "project" ? entry.projectLabel : null - } + projectLabel={leadRowPlace( + entry.isLead, + sidebarGrouping !== "project" ? entry.projectLabel : null, + )} + isLead={entry.isLead} // Under a project group's header the project's // mark is said once, there. showProjectMark={sidebarGrouping !== "project"} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index 31cb7e01e..4c7ba093e 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -258,6 +258,8 @@ import { resolveComposerSkillReferences } from "../../providerSkillReferences"; import { useIsPhoneViewport } from "../../hooks/useMediaQuery"; import { ComposerDictationControl } from "./ComposerDictationControl"; import { useDictation } from "../../dictation/useDictation"; +import { useStore } from "../../store"; +import { readLeadProjectName } from "../../leadChat"; const ATTACHMENT_SIZE_LIMIT_LABEL = `${Math.round(PROVIDER_SEND_TURN_MAX_IMAGE_BYTES / (1024 * 1024))}MB`; @@ -1613,6 +1615,8 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) }), [canReferenceWorkspaceFiles, composerSkills, roomMentionAgents.length], ); + // The project's lead chat invites work by name. + const leadProjectName = useStore((state) => readLeadProjectName(state, routeThreadRef)); const defaultComposerPlaceholder = useMemo( () => buildDefaultComposerPlaceholder({ @@ -1620,8 +1624,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) canInvokeSkills: composerSkills.some((skill) => skill.enabled), canMentionAgents: roomMentionAgents.length > 0, recipientName: roomsShown && roomAgents.inRoom ? roomAgents.recipient.name : undefined, + leadProjectName: leadProjectName ?? undefined, }), [ + leadProjectName, canReferenceWorkspaceFiles, composerSkills, roomAgents.inRoom, diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index f144b2015..db7c75ad1 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -15,6 +15,7 @@ import { CornerDownRightIcon, FolderInputIcon, FolderOpenIcon, + FlagIcon, GitForkIcon, GlobeIcon, MessagesSquareIcon, @@ -117,6 +118,8 @@ interface ChatHeaderProps { forkContext: ForkHeaderContext | null; /** Set on a thread another thread's agent started; it stays after separating. */ parentContext?: ParentThreadHeaderContext | null | undefined; + /** The thread is its project's lead chat (docs/design/lead-chat.md). */ + isLeadChat?: boolean | undefined; /** Set on a thread an agent outside Threadlines started (docs/design/outside-agents.md). */ outsideOrigin?: OutsideAgentRef | null | undefined; backgroundRuns: ReadonlyArray; @@ -308,6 +311,7 @@ export const ChatHeader = memo(function ChatHeader({ taskProgress, forkContext, parentContext = null, + isLeadChat = false, outsideOrigin = null, backgroundRuns, activeThreadRef, @@ -424,6 +428,14 @@ export const ChatHeader = memo(function ChatHeader({ {parentContext ? ( ) : null} + {isLeadChat ? ( + + + + + ) : null} {outsideOrigin ? : null} {activeProjectName && !isGitRepo && sourceControlAvailable && ( diff --git a/apps/web/src/components/chat/ProjectThreadMap.tsx b/apps/web/src/components/chat/ProjectThreadMap.tsx index 4a962e98f..38dd5dbda 100644 --- a/apps/web/src/components/chat/ProjectThreadMap.tsx +++ b/apps/web/src/components/chat/ProjectThreadMap.tsx @@ -1,4 +1,5 @@ import { + parseScopedThreadKey, scopedProjectKey, scopedThreadKey, scopeProjectRef, @@ -8,6 +9,7 @@ import { PULL_REQUEST_SETTLED_LIST_LIMIT, type ScopedProjectRef } from "@threadl import { useNavigate } from "@tanstack/react-router"; import { useId, useMemo, useState } from "react"; import { useShallow } from "zustand/react/shallow"; +import { FlagIcon } from "lucide-react"; import { useRelativeTimeTick } from "../../hooks/useRelativeTimeTick"; import { @@ -16,10 +18,12 @@ import { } from "../../lib/pullRequestsReactQuery"; import { cn } from "../../lib/utils"; import { + selectProjectByRef, selectProjectsAcrossEnvironments, selectSidebarThreadsAcrossEnvironments, useStore, } from "../../store"; +import { projectLeadRef } from "../../leadChat"; import { buildThreadRouteParams } from "../../threadRoutes"; import { formatRelativeTimeLabel } from "../../timestampFormat"; import type { SidebarThreadSummary } from "../../types"; @@ -208,6 +212,15 @@ export function ProjectThreadMap({ }) { const navigate = useNavigate(); const map = useProjectThreadMap(memberProjectRefs); + // The project's lead chat, when one of its copies has one: a link beside the caption. + const leadThreadKey = useStore((state) => { + for (const projectRef of memberProjectRefs) { + const project = selectProjectByRef(state, projectRef); + const leadRef = project === undefined ? null : projectLeadRef(state, project); + if (leadRef !== null) return scopedThreadKey(leadRef); + } + return null; + }); const nowMs = useRelativeTimeTick(60_000); const [activeKey, setActiveKey] = useState(null); const gradientId = useId().replaceAll(":", ""); @@ -525,6 +538,25 @@ export function ProjectThreadMap({ {part.text} ))} + {leadThreadKey !== null ? ( + + ) : null}

); diff --git a/apps/web/src/components/chat/composerPlaceholder.ts b/apps/web/src/components/chat/composerPlaceholder.ts index 31b3b8c78..1ff413b9e 100644 --- a/apps/web/src/components/chat/composerPlaceholder.ts +++ b/apps/web/src/components/chat/composerPlaceholder.ts @@ -32,8 +32,14 @@ export function buildDefaultComposerPlaceholder( * model button has little room for its name on a phone. */ recipientName?: string | undefined; + /** The thread is this project's lead chat (docs/design/lead-chat.md). */ + leadProjectName?: string | undefined; }, ): string { - const lead = input.recipientName ? `Message ${input.recipientName}` : "Ask anything"; + const lead = input.recipientName + ? `Message ${input.recipientName}` + : input.leadProjectName + ? `Drop work for ${input.leadProjectName} here` + : "Ask anything"; return `${lead} · ${buildComposerCapabilityHint(input)}`; } diff --git a/apps/web/src/components/sidebar/InboxRows.tsx b/apps/web/src/components/sidebar/InboxRows.tsx index 518de5cdc..8eb395e58 100644 --- a/apps/web/src/components/sidebar/InboxRows.tsx +++ b/apps/web/src/components/sidebar/InboxRows.tsx @@ -6,6 +6,7 @@ import { Clock3Icon, CloudIcon, CornerDownRightIcon, + FlagIcon, LinkIcon, MonitorUpIcon, GitForkIcon, @@ -725,6 +726,8 @@ export interface InboxThreadRowProps { * header, which already names the project. Default on. */ showProjectMark?: boolean | undefined; + /** Its project's lead chat (docs/design/lead-chat.md): a mark before the title. */ + isLead?: boolean | undefined; isActive: boolean; jumpLabel: string | null; /** False while the thread is moving, blocked, or pinned: live work can't be @@ -814,6 +817,7 @@ export const InboxThreadRow = memo(function InboxThreadRow(props: InboxThreadRow status, projectLabel, showProjectMark = true, + isLead = false, isActive, jumpLabel, canMarkDone, @@ -1133,6 +1137,15 @@ export const InboxThreadRow = memo(function InboxThreadRow(props: InboxThreadRow ) : null} + {isLead ? ( + + + + ) : null} {threadProject && showProjectMark ? ( setProjectPhoneAlertsMuted(members, true)); actionHandlers.set(UNMUTE_ALERTS_ITEM_ID, () => setProjectPhoneAlertsMuted(members, false)); + // The lead chat lives per computer: each copy can have its own. + const leadMembers = members.filter((member) => + environmentSupportsProjectLead(member.environmentId), + ); + const leadLeaf = (member: SidebarProjectGroupMember) => { + const leadRef = projectLeadRef(useStore.getState(), member); + const id = `lead:${member.physicalProjectKey}`; + actionHandlers.set(id, async () => { + const target = leadRef ?? (await createLeadChat(member)); + if (target !== null) { + await navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(target), + }); + } + }); + return { id, opens: leadRef !== null }; + }; + const leadItems: ContextMenuItem[] = []; + // Starting one where agents can't start threads would give a lead + // that can start nothing: offered, greyed out, with the reason. + const newLeadItem = (member: SidebarProjectGroupMember, label: string) => { + const refusal = leadSettingRefusal(member.environmentId); + return refusal === null + ? { label } + : { + label: `${label}: ${refusal.charAt(0).toLowerCase()}${refusal.slice(1).replace(/\.$/, "")}`, + disabled: true, + }; + }; + if (leadMembers.length === 1) { + const leaf = leadLeaf(leadMembers[0]!); + leadItems.push({ + id: leaf.id, + ...(leaf.opens + ? { label: "Open lead chat" } + : newLeadItem(leadMembers[0]!, "New lead chat")), + }); + } else if (leadMembers.length > 1) { + leadItems.push({ + id: "lead:submenu", + label: "Lead chat", + children: leadMembers.map((member) => { + const leaf = leadLeaf(member); + const where = formatProjectMemberActionLabel(member, project.groupedProjectCount); + return { + id: leaf.id, + ...(leaf.opens + ? { label: `Open: ${where}` } + : newLeadItem(member, `New: ${where}`)), + }; + }), + }); + } + const clicked = await api.contextMenu.show( [ - buildTargetedItem("rename", "Rename project"), + ...leadItems, + { + ...buildTargetedItem("rename", "Rename project"), + ...(leadItems.length > 0 ? { separatorBefore: true } : {}), + }, buildTargetedItem("grouping", "Project grouping…"), buildTargetedItem("copy-path", "Copy Project Path"), ...(setupSource !== null @@ -514,7 +582,7 @@ export const ProjectScopeMenu = memo(function ProjectScopeMenu(props: ProjectSco await actionHandlers.get(clicked)?.(); })(); }, - [handleRemoveProject, openProjectGroupingDialog, openProjectRenameDialog], + [handleRemoveProject, navigate, openProjectGroupingDialog, openProjectRenameDialog], ); const closeProjectRenameDialog = useCallback(() => { diff --git a/apps/web/src/components/threadMenu.logic.ts b/apps/web/src/components/threadMenu.logic.ts index 2b66fa0e0..9679b6cd5 100644 --- a/apps/web/src/components/threadMenu.logic.ts +++ b/apps/web/src/components/threadMenu.logic.ts @@ -1,5 +1,7 @@ import type { ContextMenuItem } from "@threadlines/contracts"; +import { leadMenuLabel, type LeadMenuState } from "../leadChat"; + /** Everything a thread's menu can do. Every surface that offers it offers the same. */ export type ThreadMenuAction = | "rename" @@ -10,6 +12,7 @@ export type ThreadMenuAction = | "reopen" | "move-up" | "move-down" + | "lead" | "separate" | "attach" | "stop-children" @@ -33,6 +36,8 @@ export interface ThreadMenuFacts { readonly moveOffered: boolean; /** Its agent is mid-turn: archiving waits until it stops. */ readonly running: boolean; + /** What it can do about its project's lead chat; null where that isn't offered. */ + readonly lead?: LeadMenuState | null; /** A row of the inbox's custom order, and where it can go; null anywhere else. */ readonly customOrder?: { readonly canMoveUp: boolean; @@ -82,6 +87,18 @@ export function describeThreadMenu(facts: ThreadMenuFacts): ContextMenuItem([ + { + id: "lead", + label: leadMenuLabel(facts.lead), + disabled: facts.lead.kind === "make" && facts.lead.refusal !== null, + }, + ]), + ); + } + const family: ContextMenuItem[] = []; if (facts.attachedChild) { family.push({ id: "separate", label: "Make it its own thread" }); diff --git a/apps/web/src/hooks/useInboxThreads.ts b/apps/web/src/hooks/useInboxThreads.ts index fd46dac7a..b86260697 100644 --- a/apps/web/src/hooks/useInboxThreads.ts +++ b/apps/web/src/hooks/useInboxThreads.ts @@ -42,6 +42,7 @@ import { useStore, } from "../store"; import type { Project, SidebarThreadSummary } from "../types"; +import { leadThreadKeysOf } from "../leadChat"; import { useUiStateStore } from "../uiStateStore"; import { useRelativeTimeTick } from "./useRelativeTimeTick"; import { useSettings } from "./useSettings"; @@ -70,6 +71,8 @@ export interface InboxEntry { deliveredAt: string | null; /** Wrapped by the user's own word rather than a wrap-up rule. */ wrappedByUser: boolean; + /** Its project's lead chat (docs/design/lead-chat.md); see `staysOnTop`. */ + isLead: boolean; } /** A general chat with its seen-aware status, and when the user last saw it. */ @@ -96,6 +99,8 @@ export interface InboxThreads { /** The pull requests each inbox thread's agent opened on other branches, where it has any. */ readonly linkedPullRequestsByThreadKey: ReadonlyMap; readonly nowIso: string; + /** Scoped keys of every project's lead chat. */ + readonly leadThreadKeys: ReadonlySet; readonly entries: InboxEntry[]; readonly generalChatEntries: InboxGeneralChatEntry[]; } @@ -304,9 +309,15 @@ export function useInboxThreads(): InboxThreads { settledPullRequestEntries, ]); + const leadThreadKeys = useMemo( + () => leadThreadKeysOf(projects, sidebarThreads), + [projects, sidebarThreads], + ); + const entries = useMemo( () => fileInboxThreads({ + leadThreadKeys, threads: inboxThreads, seenSources: { seenThreadOverlays, threadSeedVisitedAtById }, doneOverlays: doneThreadOverlays, @@ -337,20 +348,23 @@ export function useInboxThreads(): InboxThreads { isDone, // A pinned row never offers the wrap-up check: the pin says "keep // this here", and a hover affordance that files it away contradicts - // it. Unpinning brings the action back. + // it. Unpinning brings the action back. A lead chat is kept the same way. canMarkDone: thread.pinnedAt === null && + !leadThreadKeys.has(threadKey) && canMarkThreadDone({ ...thread, lastVisitedAt }, { now: nowIso }), doneAt: isDone ? resolveDoneTimestamp(thread, override) : null, seenAt, settledAt: resolveDoneTimestamp(thread, null), deliveredAt: thread.handedBackAt ?? null, wrappedByUser: isDone && freshThreadDoneOverride(thread, override)?.state === "done", + isLead: leadThreadKeys.has(threadKey), }; }), [ doneThreadOverlays, inboxThreads, + leadThreadKeys, linkedPullRequestsByThreadKey, nowIso, pullRequestByThreadKey, @@ -392,6 +406,7 @@ export function useInboxThreads(): InboxThreads { pullRequestByThreadKey, linkedPullRequestsByThreadKey, nowIso, + leadThreadKeys, entries, generalChatEntries, }; diff --git a/apps/web/src/hooks/useThreadMenu.ts b/apps/web/src/hooks/useThreadMenu.ts index 3f27de08f..be7972b89 100644 --- a/apps/web/src/hooks/useThreadMenu.ts +++ b/apps/web/src/hooks/useThreadMenu.ts @@ -36,6 +36,7 @@ import { } from "../store"; import type { SidebarThreadSummary } from "../types"; import { useSettings } from "./useSettings"; +import { readLeadMenuState, setProjectLead } from "../leadChat"; import { useThreadActions } from "./useThreadActions"; /** The thread a menu is for, and what only its surface knows. */ @@ -141,6 +142,7 @@ export function useThreadMenu() { moveOffered: readThreadMoveOffered(thread.environmentId, thread.moveStatus), running: isThreadTurnRunning(full?.session), customOrder: target.customOrder ?? null, + lead: readLeadMenuState(useStore.getState(), thread), }); }, []); @@ -221,6 +223,25 @@ export function useThreadMenu() { case "move": openThreadMoveDialog(threadRef); return; + case "lead": { + const lead = readLeadMenuState(useStore.getState(), thread); + if (lead === null || (lead.kind === "make" && lead.refusal !== null)) return; + const made = await setProjectLead({ + environmentId: thread.environmentId, + projectId: thread.projectId, + threadId: lead.kind === "stop" ? null : thread.id, + }); + // A lead stays at the top of the list: one the user had wrapped up + // comes back, since the user's own wrap-up outranks the lead's keep. + if ( + made && + lead.kind === "make" && + (target.inbox?.isDone === true || thread.doneOverride?.state === "done") + ) { + reopenThreadByKey(threadKey); + } + return; + } case "copy-path": { const project = selectProjectByRef( useStore.getState(), diff --git a/apps/web/src/leadChat.ts b/apps/web/src/leadChat.ts new file mode 100644 index 000000000..3d30732df --- /dev/null +++ b/apps/web/src/leadChat.ts @@ -0,0 +1,302 @@ +/** + * A project's lead chat on the client (docs/design/lead-chat.md): which + * thread leads each project, what a thread's menu offers about it, and the + * command that changes it. The rules themselves are the server's + * (@threadlines/shared/projectLead); the client reads them first so a + * disabled item can say why. + */ +import { scopedThreadKey, scopeProjectRef, scopeThreadRef } from "@threadlines/client-runtime"; +import { + DEFAULT_NEW_THREAD_RUNTIME_MODE, + DEFAULT_PROVIDER_INTERACTION_MODE, + type EnvironmentId, + type ProjectId, + type ScopedProjectRef, + type ScopedThreadRef, + type ThreadId, +} from "@threadlines/contracts"; +import { leadSetRefusal, projectLeadThreadId } from "@threadlines/shared/projectLead"; +import { agentThreadsMode } from "@threadlines/shared/serverSettings"; + +import { addComputerNotConnectedNotice } from "./components/computerConnectionNotices"; +import { failureNotice, toastManager } from "./components/ui/toast"; +import { readEnvironmentApi } from "./environmentApi"; +import { readEnvironmentDescriptor } from "./environments/runtime"; +import { newCommandId, newThreadId } from "./lib/utils"; +import { + lastUsedSelection, + readComputerConfig, + resolveNewThreadDefaults, +} from "./newThreadDefaults"; +import { + type AppState, + selectProjectByRef, + selectSidebarThreadSummaryByRef, + useStore, +} from "./store"; +import type { Project, SidebarThreadSummary } from "./types"; + +/** Whether the computer a project lives on keeps a lead chat (capability `projectLead`). */ +export function environmentSupportsProjectLead(environmentId: EnvironmentId): boolean { + return readEnvironmentDescriptor(environmentId)?.capabilities.projectLead === true; +} + +/** The project's lead thread, as a ref; null when it has none (or a ghost pointer). */ +export function projectLeadRef( + state: AppState, + project: Pick, +): ScopedThreadRef | null { + const leadThreadId = projectLeadThreadId(project, (threadId) => + leadThreadFacts( + selectSidebarThreadSummaryByRef(state, scopeThreadRef(project.environmentId, threadId)), + ), + ); + return leadThreadId === null ? null : scopeThreadRef(project.environmentId, leadThreadId); +} + +/** + * Scoped keys of every project's lead thread, on every computer in view. + * Pure over what the caller already holds, so a memo can keep it. + */ +export function leadThreadKeysOf( + projects: ReadonlyArray>, + threads: ReadonlyArray, +): ReadonlySet { + const keys = new Set(); + if (!projects.some((project) => (project.leadThreadId ?? null) !== null)) return keys; + const byKey = new Map( + threads.map((thread) => [ + scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id)), + thread, + ]), + ); + for (const project of projects) { + const leadThreadId = projectLeadThreadId(project, (threadId) => + leadThreadFacts(byKey.get(scopedThreadKey(scopeThreadRef(project.environmentId, threadId)))), + ); + if (leadThreadId !== null) { + keys.add(scopedThreadKey(scopeThreadRef(project.environmentId, leadThreadId))); + } + } + return keys; +} + +const leadThreadFacts = (thread: SidebarThreadSummary | undefined | null) => + thread === undefined || thread === null + ? null + : { + id: thread.id, + projectId: thread.projectId, + parentThreadId: thread.parentThreadId ?? null, + attachedToParent: thread.attachedToParent ?? false, + archivedAt: thread.archivedAt, + remoteOrigin: thread.remoteOrigin ?? null, + outsideOrigin: thread.outsideOrigin ?? null, + move: thread.moveStatus ?? null, + }; + +/** + * What a thread's menu offers about the lead chat: stop using it, or make + * it the lead (replacing another, and refused with a reason). Null when the + * thread's computer doesn't keep a lead chat. + */ +export type LeadMenuState = + | { readonly kind: "stop" } + | { + readonly kind: "make"; + readonly replacingTitle: string | null; + readonly refusal: string | null; + }; + +/** + * Why no thread on this computer can lead right now, from that computer's own + * settings: a lead with "Agents can start threads" off could start nothing. + * Null when it can, or when the computer's settings aren't known yet. + */ +export function leadSettingRefusal(environmentId: EnvironmentId): string | null { + const settings = readComputerConfig(environmentId)?.settings; + return settings !== undefined && agentThreadsMode(settings) === "off" + ? "Agents can't start threads. Turn it on in Settings › Threads." + : null; +} + +export function readLeadMenuState( + state: AppState, + thread: SidebarThreadSummary, +): LeadMenuState | null { + if (!environmentSupportsProjectLead(thread.environmentId)) return null; + const project = selectProjectByRef( + state, + scopeProjectRef(thread.environmentId, thread.projectId), + ); + if (project === undefined) return null; + const leadRef = projectLeadRef(state, project); + if (leadRef !== null && leadRef.threadId === thread.id) return { kind: "stop" }; + const facts = leadThreadFacts(thread)!; + const refusal = + leadSetRefusal({ id: project.id, kind: project.kind, leadThreadId: null }, facts) ?? + leadSettingRefusal(thread.environmentId); + return { + kind: "make", + replacingTitle: + leadRef === null ? null : (selectSidebarThreadSummaryByRef(state, leadRef)?.title ?? null), + refusal, + }; +} + +/** The menu words for a lead state. */ +export function leadMenuLabel(state: LeadMenuState): string { + if (state.kind === "stop") return "Stop using as lead chat"; + const base = + state.replacingTitle === null + ? "Make this the lead chat" + : `Make this the lead chat instead of ${state.replacingTitle}`; + return state.refusal === null + ? base + : `${base}: ${state.refusal.charAt(0).toLowerCase()}${state.refusal.slice(1).replace(/\.$/, "")}`; +} + +/** + * Makes `threadId` the project's lead chat, or (null) stops having one, on + * the project's own computer. Says so when that computer can't be reached + * or is too old to keep a lead. + */ +export async function setProjectLead(input: { + readonly environmentId: EnvironmentId; + readonly projectId: ProjectId; + readonly threadId: ThreadId | null; +}): Promise { + const failure = + input.threadId === null + ? "Couldn't stop using the lead chat" + : "Couldn't make it the lead chat"; + const api = readEnvironmentApi(input.environmentId); + if (!api) { + addComputerNotConnectedNotice({ environmentId: input.environmentId, failure }); + return false; + } + if (!environmentSupportsProjectLead(input.environmentId)) { + const label = readEnvironmentDescriptor(input.environmentId)?.label ?? "that computer"; + toastManager.add({ + type: "warning", + title: failure, + description: `Update Threadlines on ${label} to use this there.`, + }); + return false; + } + try { + await api.orchestration.dispatchCommand({ + type: "project.lead.set", + commandId: newCommandId(), + projectId: input.projectId, + threadId: input.threadId, + }); + return true; + } catch (error) { + toastManager.add(failureNotice({ title: failure, error })); + return false; + } +} + +/** Reads the store now: the lead of the project a thread belongs to. */ +export function readProjectLeadRefForThread(threadRef: ScopedThreadRef): ScopedThreadRef | null { + const state = useStore.getState(); + const thread = selectSidebarThreadSummaryByRef(state, threadRef); + if (!thread) return null; + const project = selectProjectByRef( + state, + scopeProjectRef(thread.environmentId, thread.projectId), + ); + return project === undefined ? null : projectLeadRef(state, project); +} + +/** + * "New lead chat": makes a thread in the project's own folder (no worktree), + * with the computer's default agent, makes it the lead and returns it. Null + * when it couldn't, having said why. + */ +export async function createLeadChat( + project: Pick, +): Promise { + const failure = "Couldn't start a lead chat"; + const api = readEnvironmentApi(project.environmentId); + if (!api) { + addComputerNotConnectedNotice({ environmentId: project.environmentId, failure }); + return null; + } + const settingRefusal = leadSettingRefusal(project.environmentId); + if (settingRefusal !== null) { + toastManager.add({ type: "warning", title: failure, description: settingRefusal }); + return null; + } + const config = readComputerConfig(project.environmentId); + const modelSelection = + (config === null ? null : resolveNewThreadDefaults(config).modelSelection) ?? + project.defaultModelSelection ?? + lastUsedSelection(); + if (modelSelection === null) { + toastManager.add({ + type: "warning", + title: failure, + description: "Pick a default agent for new threads in Settings first.", + }); + return null; + } + const threadId = newThreadId(); + try { + await api.orchestration.dispatchCommand({ + type: "thread.create", + commandId: newCommandId(), + threadId, + projectId: project.id, + title: "Lead chat", + modelSelection, + runtimeMode: DEFAULT_NEW_THREAD_RUNTIME_MODE, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: null, + worktreePath: null, + createdAt: new Date().toISOString(), + }); + } catch (error) { + toastManager.add(failureNotice({ title: failure, error })); + return null; + } + const made = await setProjectLead({ + environmentId: project.environmentId, + projectId: project.id, + threadId, + }); + return made ? scopeThreadRef(project.environmentId, threadId) : null; +} + +/** + * Where "Go to lead chat" goes: the lead of the open thread's project, else + * the lead of `fallbackProject` (the project in scope). Null when neither has one. + */ +export function readLeadChatTarget( + openThread: ScopedThreadRef | null, + fallbackProject: ScopedProjectRef | null, +): ScopedThreadRef | null { + const fromThread = openThread === null ? null : readProjectLeadRefForThread(openThread); + if (fromThread !== null) return fromThread; + if (fallbackProject === null) return null; + const state = useStore.getState(); + const project = selectProjectByRef(state, fallbackProject); + return project === undefined ? null : projectLeadRef(state, project); +} + +/** + * The project's name when `threadRef` is its lead chat, else null. A + * primitive, so a store selector built on it redraws only when it changes. + */ +export function readLeadProjectName(state: AppState, threadRef: ScopedThreadRef): string | null { + const thread = selectSidebarThreadSummaryByRef(state, threadRef); + if (!thread) return null; + const project = selectProjectByRef( + state, + scopeProjectRef(thread.environmentId, thread.projectId), + ); + if (project === undefined) return null; + const leadRef = projectLeadRef(state, project); + return leadRef !== null && leadRef.threadId === thread.id ? project.name : null; +} diff --git a/apps/web/src/newThreadDefaults.ts b/apps/web/src/newThreadDefaults.ts index 511e1dd19..e530e2858 100644 --- a/apps/web/src/newThreadDefaults.ts +++ b/apps/web/src/newThreadDefaults.ts @@ -199,7 +199,7 @@ function draftActiveSelection(draftId: DraftId): ModelSelection | null { } /** The model last picked on this device, if any. */ -function lastUsedSelection(): ModelSelection | null { +export function lastUsedSelection(): ModelSelection | null { const state = useComposerDraftStore.getState(); const active = state.stickyActiveProvider; return active === null ? null : (state.stickyModelSelectionByProvider[active] ?? null); diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts index 537b8219f..3d1332034 100644 --- a/apps/web/src/store.ts +++ b/apps/web/src/store.ts @@ -831,6 +831,7 @@ function mapProject( updatedAt: project.updatedAt, scripts: mapProjectScripts(project.scripts), phoneAlertsMuted: project.phoneAlertsMuted === true, + leadThreadId: project.leadThreadId ?? null, }; } @@ -2646,6 +2647,9 @@ function applyEnvironmentOrchestrationEvent( ...(event.payload.phoneAlertsMuted !== undefined ? { phoneAlertsMuted: event.payload.phoneAlertsMuted } : {}), + ...(event.payload.leadThreadId !== undefined + ? { leadThreadId: event.payload.leadThreadId } + : {}), updatedAt: event.payload.updatedAt, }; return { diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts index 91b9283e8..15406015b 100644 --- a/apps/web/src/types.ts +++ b/apps/web/src/types.ts @@ -198,6 +198,11 @@ export interface Project { scripts: ProjectScript[]; /** This project's threads send no phone alerts. */ phoneAlertsMuted?: boolean | undefined; + /** + * The project's lead chat (docs/design/lead-chat.md). Read it through + * `projectLeadThreadId`, which ignores a pointer at an archived thread. + */ + leadThreadId?: ThreadId | null | undefined; } export interface Thread { diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md new file mode 100644 index 000000000..eceb837ba --- /dev/null +++ b/docs/design/lead-chat.md @@ -0,0 +1,493 @@ +# Lead chat: one place to run a project + +Status: plan rev 3 (Nov 16 2026), being built in four pieces (see Build order). GPT-6.1 Sol reviewed rev 1 (13 findings) +and the two redesigned parts of rev 2 (6 findings). Each was checked against the code +and all hold; the answers are in "Changes from review" at the end. Rev 3's answers to +the second pass were not reviewed again. Awaiting Will's go. + +## Goal + +Each project can have one **lead chat**. The user drops work into it (a bug, a stack +trace, a list of tasks). Its agent answers small questions itself, starts a thread for +new work, or passes the message to the thread already working in that area, and tells +the user when the threads it started finish. Beside it, a **Threads** panel shows the +project's threads grouped by what needs the user. + +This is Threadlines' answer to Claude Code's Projects beta (Sep 2026: +code.claude.com/docs/en/claude-projects). We take the product idea and build it from +what we have: child threads (docs/design/child-threads.md), the pull request watcher, +scheduled and event tasks, linked computers. No second orchestration system. + +What we do better than Projects, on purpose: + +- **Any agent can lead.** Claude, Codex, OpenCode, Muse, Pi, and ACP agents that take + our tools. Their coordinator is Claude only. +- **It runs on the user's computers,** with their tools, hooks and sign-ins, and can + start threads on linked computers (`thread_start`'s `computer`). +- **The lead can pass work to threads the user started by hand,** not only its own. +- **The lead is replaceable.** What is in flight lives in the threads and the panel, + not in the lead's memory, so a fresh lead chat picks up from `thread_list`. + +## Decisions (each is hard to undo; the reasons are here so they can be argued) + +1. **The lead is a role on an ordinary thread, named by a pointer on the project.** + `leadThreadId` on the project, at most one per project per computer. Not a new + thread kind and not a flag on the thread: one pointer makes "at most one" true by + construction, and every existing thread feature (rooms, fork, revert, queue) keeps + working without a second code path. +2. **The lead's own threads are an ordinary family.** Threads it starts are attached + children, fold under its sidebar row and report back, exactly as today. No new + sidebar grouping. The Threads panel is where the whole project is seen. +3. **Passing work to a thread the lead did not start is one-way.** The message lands + in that thread as the lead's, the thread does the work, and the user sees the result + there. Nothing comes back to the lead by itself; it reads the thread when asked. + + Rev 1 had the answer come back as a report. Sol's review showed what that costs: + every place that finds a request does it through the thread's parent (turn-end + delivery, the error and quiet-answer settles, taking back a queued message, archive, + delete, revert, the report's own validity check, Stop's epoch, the done alert), so + answers from a thread with no parent would need a second lookup in about ten places, + plus a new rule for a target that hands the work to its own children. One-way needs + none of it, because the code already runs a request-kind message in a thread that is + not an attached child with nothing bound to it (a separated child's leftover + messages take this path today: decider.ts "The request this turn answers was + cancelled" applies only to attached children, and the binding at turn start finds + no request and emits nothing). A thread the user started is the user's; its result + belongs in front of the user, with its normal alert. Report-back for passes can be + added later without undoing anything here. + +4. **The lead never wakes for work it did not ask for.** Only answers from threads it + started reach it. This keeps usage predictable; the panel shows everything else. +5. **Role text rides the per-turn context, not the system prompt.** It is the one + hook that reaches every provider (ACP agents hear no system instructions of ours) + and has the thread in scope. Claude's system prompt append must not differ between + threads (prompt cache), so it cannot go there. +6. **A usage limit with a known reset pauses agent-started work instead of failing + it,** when "Continue at reset" is on, for threads on this computer. Without this a + lead left alone stops at the first limit: the child fails, the report turn fails on + the same limit, and both wait for the user. +7. **The board is a right-panel tab, not a page and not a sidebar mode.** It sits + beside the conversation where work is handed out, works as a sheet on a phone, and + costs no eighth rail destination. + +Out of scope here, with the seam named so they fit later: a project brief and shared +project notes (they append to the lead's role text and to a child's first-message +preamble, both built in `ProviderCommandReactor`), one Pause for a whole project, and +usage per project. + +## User-facing behavior + +Words below are the on-screen words. Copy follows the repo's copy rules (no em dashes). + +### Making and unmaking a lead + +- **Thread menu** (sidebar row menu and the chat header's title menu): "Make this the + lead chat". On the lead: "Stop using as lead chat". When another thread is the lead: + "Make this the lead chat instead of ". +- **Project menu** (the project picker's "…" and its context menu): "Open lead chat" + when there is one, else "New lead chat". New lead chat creates a thread in the + project folder (no worktree), makes it the lead and opens it. +- **Command palette:** "Go to lead chat" (one entry per project that has one), "New + lead chat", "Make this thread the lead chat" / "Stop using as lead chat". +- **Keybinding command** `navigate.leadChat` (lead of the open thread's project, else of + the scoped project). No default key. +- **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). +- **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 + 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 + threads it started stay its family. + +### Sidebar + +- The lead's row carries a lead glyph before its title and "Lead" in place of the + project name on its second line (the project name stays when several projects are in + scope: "Lead · <project>"). +- It sorts first: ahead of pinned rows, never folded, never wrapped by the idle or + pull request rules. In project grouping it is the first row of its group. +- Its children fold under it as any family does. Nothing else changes. + +### Chat + +- Header chip "Lead chat", built like the "Started by" chip. +- Empty composer placeholder: "Drop work for <project> here". +- The first time a thread becomes the lead on this device, the Threads panel opens. +- A message the lead passed into another thread is authored "<lead title>" there, as a + parent's messages are in a child today. + +### Starting several threads (approval card, every parent, not only the lead) + +The card "<agent> wants to start N threads" gets a checkbox per row, all checked. The +button reads "Start all" or "Start 3". Unchecked rows are declined in the same answer +and the agent is told which. "Not now" is unchanged. The checkboxes show only when the +thread's server says it can take a partial answer (capability `childStartSelection`); +an older linked server would start the whole batch, so there the card stays as it is. + +### Threads panel (right-panel tab "Threads") + +Available on every thread of a workspace project; one line in the `+` menu: "This +project's threads." Lists the project's threads on every computer in view, in groups. +A thread goes in the first group that fits, in this order: + +| Order | Group | A thread is here when | +| ----- | ---------------- | ------------------------------------------------------------------------------------------------- | +| 1 | Done | the sidebar files it as wrapped, and it was wrapped in the last 7 days (older ones are not shown) | +| 2 | Needs you | Pending Approval, Awaiting Input, Failed, or Plan Ready | +| 3 | Working | Working, Starting, Answering, Waiting, Checking back, Continues at reset | +| 4 | Landing | its open pull request has auto-merge on or is in the merge queue | +| 5 | Ready for review | it has an open, non-draft pull request | +| 6 | Idle | everything else | + +Drawn in the order Needs you, Ready for review, Working, Landing, Idle, Done (Done +closed by default, like the sidebar's Wrapped shelf). + +- **Filing comes first.** "Wrapped" is the sidebar's own answer (`fileInboxThreads`), + not a status: a failed thread the user looked at and wrapped keeps its Failed status + and still belongs in Done. One exception keeps review work visible: a wrapped thread + whose pull request is still open goes to Landing or Ready for review, not Done (a + finished child wraps itself the moment it hands back, pull request still open). +- Rows are one line, like a family's child rows: status dot, title, the existing pull + request badge, a state word (for Ready for review, the Pull requests page's reason: + "Review required", "Changes requested", "Checks failing", "Approved"), clock, + provider glyph, computer mark when not this one. Click opens the thread. The row menu + is the sidebar's thread menu. +- Header: counts ("2 need you · 3 working"), and a "Lead chat" link when the open + thread is not the lead. +- Groups with nothing in them are not drawn. More than 8 in a group folds behind "Show + N more". +- Phone: the panel's existing sheet. +- What the client knows without detail reads: status and filing per thread, each + thread's pull request (state, draft, auto-merge) from `useInboxThreads`, and review + decision and checks from the open list matched by repository and branch. Merge-queue + position is a detail read and is not shown. + +## Agent side + +### Role text + +Added to the context of **every turn that starts in the lead**, whatever started it (a +person, a scheduled or event task, a report from one of its threads, a retry, a +continue). A report turn keeps its own framing line as well. + +``` +This thread is the lead chat for the project "<title>". 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 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. +``` + +- It is a preference, not a fence: we cannot remove file tools on every provider. +- **Paths that do not carry it, by decision:** a message steered into a running turn + (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. + +### Tools + +- **`thread_send` from the lead to a thread it did not start** ("a pass"). Allowed when + the target: is open, in the same project, on this computer, top-level or a child the + user made its own, not the lead, not a General Chat, not a room, not from an outside + agent or another computer, has no move pending, and is not held by the user's Stop. + Refusals say why: an attached child of another thread, "Message the thread that + started it."; a room, "Rooms take work from the user."; a stopped thread, "The user + stopped that thread. It takes work again once they write there." The result says + plainly that nothing comes back: `sent` or `queued` with `reportsBack: false`. + - **Why no rooms.** In a room the agent answering can hand the work to another agent, + whose turn no longer carries the pass (agentRequestDecisions.ts), and the slot can + be another agent's. Refusing rooms keeps every rule below true without a second set + of room rules. + - **A Stop that lands after the pass was queued** holds it like any agent message: + it waits until the user writes in that thread. That is what Stop means. + - **Access.** The pass carries the lead's access and interaction mode as a ceiling, + and the ceiling stays on the message for good. It is checked when the tool is + called **and at every decision that starts a turn from that message**: sent at + once, sent from the queue, retried, resent. The check is against the target's modes + at that moment (a user message queued ahead can widen them: agent messages run with + the thread's current modes, decider.ts send-queued; retry and resend start a turn + 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, + 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 + the lead chat passed on. Do the work here, or say what should be started."). + 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. + - 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 + as they do for any message, and need no word to the lead. +- **`thread_send` to its own children, `thread_stop`:** unchanged. The lead cannot stop + 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. +- **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 + task keeps a budget per event, bounded by the task's own daily run limit. +- **Outside agents and assistants:** the project listing they read gains optional + `leadThreadId`, so "send this to the project's lead" needs no thread id from the user. +- **Tool descriptions** say the lead's extra reach in one sentence each; ACP agents + learn rules only from descriptions. + +### What a passed-to thread hears + +A new framing line, chosen when the message's sender is not this thread's parent: "The +project's lead chat "<title>" passed this on. It is from another agent, not typed by +the user. Your reply stays in this thread, where the user reads it." + +## Data model + +### Project (`packages/contracts/src/orchestration.ts`) + +- `OrchestrationProject.leadThreadId?: ThreadId | null` and the same on the shell. + Template end to end: `phoneAlertsMuted` (#759, migration 100): optional field, + capability flag (`projectLead` in `environment.ts`) so a client hides the actions on + an older server, additive column `lead_thread_id TEXT` (next migration, 116; no row + rewrite). +- Command `project.lead.set { projectId, threadId: ThreadId | null }`. A command of its + own, not `project.meta.update`, because it validates a thread and cascades. It emits + the existing `project.meta-updated` event with a `leadThreadId` field rather than a + new event type (decided while building): every reader of project changes (the shell + stream, the web store, the git fetch supervisor) already follows that event, so none + can miss a lead change. +- Decider refuses with the reasons listed under "Not allowed". Setting a lead while + another exists replaces it in the same decision. +- Cascades, decided on the server: `thread.archive`, `thread.delete` and + `project.delete` clear the pointer in the same decision. `thread.parent-attachment.set + { attached: true }` on the lead is refused (a lead is top-level). The thread-move + decision refuses the lead with words only (no new refusal code: the move's + `refusalCode` is a closed set older peers decode). +- Readers treat a pointer at a missing, archived or deleted thread as no lead, so a + replay of old events or a cascade that an older build missed cannot leave a ghost. +- Linked computers keep separate project records, so each computer can have its own + lead for the same repository. The client shows each lead with its computer's mark and + the menus act on the project record of the thread's own computer. No fan-out. + +### A pass (`ThreadMessageOrigin`) + +- The passed message is a user-role message in the target with + `fromThread { threadId: <lead>, requestId: <new id>, kind: "request" }` and a new + optional field `ceiling?: { runtimeMode, interactionMode }`. No request is recorded on + the lead, so there is nothing to settle, hold, cancel or recover. `ceiling` marks a + pass: no other message has it. +- Command `thread.lead.pass` (server-only, from the tool handler). In one decision: + `message-sent` and `follow-up-queued` on the target, and the lead's send counter. The + decider re-checks every rule the handler checked. Idempotent per caller turn, keyed + like the other thread tools. +- Pure rule `leadPassRefusal(lead, target, project)` in + `packages/shared/src/childThreads.ts`, used by the handler and the decider. +- When the ceiling refuses a queued entry, the decision takes it back (`cancelled`), + writes the one-line activity in the target and adds a pending note on the lead (the + existing `pendingNotes`, delivered on its next turn). If the lead is gone, only the + first two. +- One helper, `passCeilingRefusal(message, thread)`, is called by every decision that + 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). +- 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). + +### Approval answer + +`thread.child-request.respond` gains optional `requestIds` with `choice: "start"`: +those start, the rest of the batch settles `declined` with one note naming them. +Absent means the whole batch. Capability `childStartSelection` gates the checkboxes. + +### Limits + +`childStartRefusal` and `childSendRefusal` take the caller's limits from one function +`childRequestLimits({ isLead })`; the constants stay as the defaults. + +## Usage limits: pause, not failure + +This applies to every parent, and is what makes a lead safe to leave. It is the +riskiest piece: it changes the child-request state machine. Only with +`continueAfterUsageLimits` on (default stays off; the setting's words change to say it +now covers threads an agent started). + +**Covered:** a request whose child is on this computer, and a report turn in a +top-level thread. **Not covered, fails as today:** a child on a linked computer (its +request lives in the other computer's link ledger, LinkRequests.ts, with its own +restart rules and older peers), a thread another computer started here, a child +stopped on a Codex goal that is `usageLimited` (its continue sets the goal active +again and sends no message, decider.ts ~4473, so there is nothing to bind the request +to), scheduled-run turns, room-agent requests, outside-agent turns. + +**The rule.** A covered request whose answering turn failed on a usage limit is held +while its child is either waiting to continue at the reset, or running the continue +turn Threadlines sent for it. It settles through the normal turn-end path when that +continue turn ends. It settles `failed`, with today's words, when the wait or the +continue ends any other way. + +- **Arming** (`withArmedContinueAtReset`, decider.ts). With the setting on, the wait is + also armed when the stopped turn was started by a `fromThread` message that is a + request with an open, same-computer request, or a report in a thread with no parent + to answer. Never when the user stopped that turn, and never while the thread's Stop + hold is set: a limit failure that arrives after Stop must not bring the turn back. + The fire re-checks the hold. +- **Holding.** Ingestion writes the failed session (which arms or does not) before it + routes the turn's end, so `childDeliveryForTurnEnd` can read the answer: a failed + turn whose child's session has the wait armed for this failure is not settled. The + request stays `running`. No new status value. +- **Rebinding.** `thread.continue-at-reset.fire` on a child with a held request emits, + in the same decision, `child-request-updated` on the parent with the continue + message's id as `childMessageId` (a new optional field on that event). The continue + turn's end then answers the request through the normal path. +- **The continue never runs.** After the fire the wait is already cleared, and the + user's own message can overtake the continue (ProviderCommandReactor, + `continueOvertaken`), leaving it unsent. The rule that takes back a parent's request + when its queued message is removed (`settleParentRequestsForUnqueued`) is widened to + "the message a request is bound to will never start a turn": an overtaken or unsent + continue settles the request `failed` ("the user took over before it could + continue"). +- **The wait ends without a fire** (skip, the switch turned off, the user starts a + turn, archive, a reset that is given up): the held request settles `failed` **in the + decision that clears the wait**, through one helper called wherever `continueAtReset` + goes from set to null without a fire. It cannot be left to the session-error settle + in `ChildThreadReactor`: that only runs for a stopped or errored session, and a user + turn moves the session to starting, running and ready, where nothing would ever + settle the request (its message id cannot match the user's turn). That reactor settle + only needs to skip a child whose wait is armed. +- **Restart.** A `running` request whose child has the wait armed is kept (the wait is + persisted). One bound to a continue that was in flight follows today's rule for a + turn a restart cut off. +- **Parent side.** Stop, wrap and archive on the parent settle a held request as they + settle any open one; the child still continues at the reset on its own, as children + keep running today. +- On screen nothing new: the child shows "Continues at reset", the parent "Waiting · N + threads". + +To check while building, not assumed: whether a scheduled run into an existing thread +(`each_run: this_thread`) has any "finish the run" duty. If it has none, include those +turns too, since an event-fed lead is the main unattended case. + +## 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 + 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 + agent. +- **Contracts:** project field and command, two capability flags, the origin's + `ceiling`, respond's `requestIds`, the update event's `childMessageId`, summary + fields. All optional and additive; no closed set gains a value. +- **Reverse states:** make lead ↔ stop; replace; archive or delete clears; "Start 3" ↔ + declined rows are told to the agent; a pass that cannot run is taken back and both + sides are told. +- **App guide:** a topic `lead-chat`; the threads topic's sidebar paragraph and the + child-threads topic mention it. No new settings row, so no new place; the + `continueAfterUsageLimits` place's words change. +- **Alerts:** unchanged. A lead's report turn finishing alerts like any finished turn; a + passed-to thread alerts like any thread. + +## Build order + +Four pieces, each its own branch and pull request. 1, 2 and 4 touch the same decider +files and go in that order from one builder. 3 is web only and can run beside 2 once +piece 1's contracts are committed. + +1. **Lead role.** Project field, command, cascades, migration, capability; role text + on every turn start; limits; menus, palette, keybinding command, 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 + answers, Sidebar.logic sort and wrap rules, one browser test for the menu round + trip. +2. **Passing and choosing what starts.** `thread.lead.pass`, `leadPassRefusal`, the + ceiling at call and at turn start, no fan-out, the framing line, `thread_list` + fields, outside project listing; `requestIds` on respond, its capability and the + card's checkboxes. Tests: handler outcome for each refusal; a pass into a hand-made + thread runs and stays there; the target's access widened by a queued user message is + caught at turn start; partial start; + whole-batch start against a server without the capability; a retried pass over + its ceiling is refused; a room and a stopped thread are refused as targets; a + pass-started thread still cannot start threads after a retry or a continue, and can + again once the user writes. +3. **Threads panel.** Pure grouping in a `projectBoard.logic.ts` that shares the + status-to-group table with `ProjectThreadMap.logic.ts` (one table, so they cannot + drift) and takes the sidebar's filing as an input, fed by `useInboxThreads`. Tab + registration in `rightPanelTabs.ts`. Tests: the grouping as data, including a + wrapped failed thread and a wrapped child with an open pull request; one browser + test. +4. **Usage limit pause.** As above. Before building, this section gets its own review + pass against the code as it stands after piece 2. Tests: arming for request and + report turns and not after Stop; hold → fire → answered; hold → skip → failed; the + user writes during the wait → failed at once; the user overtakes the continue → + failed; restart with a held request; a linked child and a `usageLimited` goal still + fail as today. + +Live check before calling it done, on a throwaway stack (never `~/.threadlines/userdata`): +a Claude lead starts a Codex thread and a Claude thread and hears back from both, +passes a follow-up into a thread made by hand, the lead role moves to another thread +mid-flight, and a faked usage limit (the stand-in agent) holds and resumes a request. + +## Changes from review + +Rev 1, first pass: + +| # | Finding | Answer | +| --- | ------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | +| 1 | Answers from a thread with no parent have no route (lookups go by parent) | Passes are one-way; no request exists to route (decision 3) | +| 2 | Such a report is rejected later as a detached child's | Same | +| 3 | Access ceiling checked only at submit; a queued user message can widen it | Checked again when the message is about to start its turn; taken back if over | +| 4 | Partial approval starts every thread on an older server | Capability `childStartSelection` gates the checkboxes | +| 5 | Unqueue, Stop, archive, delete, revert do not know such requests | No request, so the target's own rules are complete | +| 6 | Stop may not raise an epoch for a lead with only such reports | No such reports | +| 7 | A continue overtaken by the user leaves the rebound request orphaned | "Bound message will never start a turn" settles it `failed` | +| 8 | The pause cannot resume a linked computer's request | Linked children are not covered and fail as today, stated | +| 9 | Arming for report turns can bring back a turn the user stopped | Never armed after Stop or under the hold; the fire re-checks | +| 10 | A target that hands work to its children answers too early | No answer is awaited | +| 11 | Settling cancels the target's done alert even without `handed-back` | No settle event for a pass | +| 12 | Role text misses steers, side answers, retries | On every turn start; steers and side answers excluded by decision | +| 13 | A wrapped failed thread lands in "Needs you" | Filing is checked before status | + +Rev 2, second pass (the one-way pass and the usage limit pause only). Sol confirmed +that an unattached thread runs an unbound request-kind message with nothing to settle, +and that the failed session is written before the turn's end is routed. + +| # | Finding | Answer | +| --- | ------------------------------------------------------------------ | ------------------------------------------------------------------- | +| 1 | Retry and resend start a turn without the ceiling check | The ceiling is checked by every decision that starts a turn from it | +| 2 | A room hand-off sheds the no-fan-out mark | Rooms are not pass targets; no-fan-out is a fact on the thread | +| 3 | A user turn clears the wait and the held request is never settled | Settled in the decision that clears the wait | +| 4 | A Codex goal's continue sends no message to bind to | Not covered; fails as today | +| 5 | A pass into a thread held by Stop can sit queued for good | Refused when the hold is known; a later Stop holds it, by design | +| 6 | The rule in `callerRefusal` would also block sends to own children | The rule lives in `childStartRefusal` only | + +## Ideas not in this plan + +- **Hearing back from passes.** Possible later: it needs request lookup that does not + go through lineage, in about ten places. +- **A real cap on threads working at once per project** (extra starts wait for a free + slot). Claude's is "a preference, not a cap"; here each thread is a local worktree + with builds running, so a real cap protects the machine as well as the usage limit. +- **Auto-fix on by default for threads a lead starts,** so a failed check is fixed + without the user (Claude does this). +- **Project brief, shared notes, project pause, usage per project** (see Out of scope). diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 0d9e64adf..1c0391afe 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -187,6 +187,12 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ * a busy room's message to Grok when the agent at work finishes instead. */ grokAnswersOnTheSide: Schema.optionalKey(Schema.Boolean), + /** + * A project can have a lead chat (`OrchestrationProject.leadThreadId`, + * `project.lead.set`, docs/design/lead-chat.md). Older servers omit it and + * would refuse the command, so clients hide the lead actions for them. + */ + projectLead: Schema.optionalKey(Schema.Boolean), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index d0190a480..0f84ae646 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -63,6 +63,7 @@ const STATIC_KEYBINDING_COMMANDS = [ "sidebar.toggle", "navigate.fleet", "navigate.scheduled", + "navigate.leadChat", "navigate.back", "navigate.forward", ...MODEL_PICKER_KEYBINDING_COMMANDS, diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts index 6aa4fe489..ab320fa12 100644 --- a/packages/contracts/src/orchestration.ts +++ b/packages/contracts/src/orchestration.ts @@ -441,6 +441,12 @@ export const OrchestrationProject = Schema.Struct({ scripts: Schema.Array(ProjectScript), /** This project's threads send no phone alerts. Absent means they do. */ phoneAlertsMuted: Schema.optional(Schema.Boolean), + /** + * The project's lead chat (docs/design/lead-chat.md). Absent or null: none. + * Read it through `projectLeadThreadId` (@threadlines/shared/projectLead), + * which treats a pointer at an archived or missing thread as none. + */ + leadThreadId: Schema.optional(Schema.NullOr(ThreadId)), createdAt: IsoDateTime, updatedAt: IsoDateTime, deletedAt: Schema.NullOr(IsoDateTime), @@ -2895,6 +2901,12 @@ export const OrchestrationProjectShell = Schema.Struct({ scripts: Schema.Array(ProjectScript), /** This project's threads send no phone alerts. Absent means they do. */ phoneAlertsMuted: Schema.optional(Schema.Boolean), + /** + * The project's lead chat (docs/design/lead-chat.md). Absent or null: none. + * Read it through `projectLeadThreadId` (@threadlines/shared/projectLead), + * which treats a pointer at an archived or missing thread as none. + */ + leadThreadId: Schema.optional(Schema.NullOr(ThreadId)), createdAt: IsoDateTime, updatedAt: IsoDateTime, }); @@ -3208,6 +3220,18 @@ const ProjectMetaUpdateCommand = Schema.Struct({ phoneAlertsMuted: Schema.optional(Schema.Boolean), }); +/** + * Make a thread the project's lead chat, or (null) stop having one. A command + * of its own rather than part of `project.meta.update`: it checks the thread + * and replaces any other lead in the same decision. + */ +const ProjectLeadSetCommand = Schema.Struct({ + type: Schema.Literal("project.lead.set"), + commandId: CommandId, + projectId: ProjectId, + threadId: Schema.NullOr(ThreadId), +}); + const ProjectDeleteCommand = Schema.Struct({ type: Schema.Literal("project.delete"), commandId: CommandId, @@ -4087,6 +4111,7 @@ const ThreadCommandRequestDismissCommand = Schema.Struct({ const DispatchableClientOrchestrationCommand = Schema.Union([ ProjectCreateCommand, ProjectMetaUpdateCommand, + ProjectLeadSetCommand, ProjectDeleteCommand, ThreadCreateCommand, ThreadDeleteCommand, @@ -4140,6 +4165,7 @@ export type DispatchableClientOrchestrationCommand = export const ClientOrchestrationCommand = Schema.Union([ ProjectCreateCommand, ProjectMetaUpdateCommand, + ProjectLeadSetCommand, ProjectDeleteCommand, ThreadCreateCommand, ThreadDeleteCommand, @@ -5431,6 +5457,8 @@ export const ProjectMetaUpdatedPayload = Schema.Struct({ defaultModelSelection: Schema.optional(Schema.NullOr(ModelSelection)), scripts: Schema.optional(Schema.Array(ProjectScript)), phoneAlertsMuted: Schema.optional(Schema.Boolean), + /** Set by `project.lead.set` and by the cascades that end a lead. */ + leadThreadId: Schema.optional(Schema.NullOr(ThreadId)), updatedAt: IsoDateTime, }); diff --git a/packages/shared/package.json b/packages/shared/package.json index 9b57ee03f..ef69b2f2b 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -427,6 +427,10 @@ "types": "./src/childThreads.ts", "import": "./src/childThreads.ts" }, + "./projectLead": { + "types": "./src/projectLead.ts", + "import": "./src/projectLead.ts" + }, "./threadFiling": { "types": "./src/threadFiling.ts", "import": "./src/threadFiling.ts" diff --git a/packages/shared/src/childThreads.test.ts b/packages/shared/src/childThreads.test.ts index 09903644c..3ba62fb40 100644 --- a/packages/shared/src/childThreads.test.ts +++ b/packages/shared/src/childThreads.test.ts @@ -92,6 +92,15 @@ describe("childStartRefusal", () => { count: 4, })?.outcome, ).toBe("limit"); + // A project's lead chat gets twice the budget. + expect( + childStartRefusal(caller({ childRequests: state }), { + from: PRIMARY, + callerTurnId: TURN, + count: 4, + isLead: true, + }), + ).toBeNull(); }); it("refuses outside the caller's own turn and after Stop", () => { diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts index 357e04830..f8d508f03 100644 --- a/packages/shared/src/childThreads.ts +++ b/packages/shared/src/childThreads.ts @@ -95,10 +95,33 @@ function callerRefusal( return null; } +/** Threads a project's lead chat may start, and messages it may send, per user message. */ +export const LEAD_THREAD_START_LIMIT = 10; +export const LEAD_THREAD_SEND_LIMIT = 20; + +/** + * A thread's budget for starting and messaging threads per user message. The + * project's lead chat (docs/design/lead-chat.md) gets twice the usual. + */ +export function childRequestLimits(input: { readonly isLead: boolean }): { + readonly starts: number; + readonly sends: number; +} { + return input.isLead + ? { starts: LEAD_THREAD_START_LIMIT, sends: LEAD_THREAD_SEND_LIMIT } + : { starts: CHILD_THREAD_START_LIMIT, sends: CHILD_THREAD_SEND_LIMIT }; +} + /** Why starting `count` threads is refused, or null when every rule allows it. */ export function childStartRefusal( thread: ChildRequestCaller, - input: { readonly from: RoomAgentRef; readonly callerTurnId: TurnId; readonly count: number }, + input: { + readonly from: RoomAgentRef; + readonly callerTurnId: TurnId; + readonly count: number; + /** The caller is its project's lead chat. */ + readonly isLead?: boolean; + }, ): ChildRequestRefusal | null { const caller = callerRefusal(thread, input); if (caller !== null) { @@ -111,10 +134,11 @@ export function childStartRefusal( }; } const used = thread.childRequests.startsSinceUser; - if (used + input.count > CHILD_THREAD_START_LIMIT) { + const limit = childRequestLimits({ isLead: input.isLead === true }).starts; + if (used + input.count > limit) { return { outcome: "limit", - detail: `Agents can start ${CHILD_THREAD_START_LIMIT} threads per user message, and ${used} were already asked for since the user last wrote, so these were not started. Say so in your reply, and wait for the user before starting more.`, + detail: `${input.isLead === true ? "The lead chat" : "Agents"} can start ${limit} threads per user message, and ${used} were already asked for since the user last wrote, so these were not started. Say so in your reply, and wait for the user before starting more.`, }; } return null; @@ -129,7 +153,12 @@ export function childSendRefusal( readonly attachedToParent: boolean; readonly archivedAt: string | null; } | null, - input: { readonly from: RoomAgentRef; readonly callerTurnId: TurnId }, + input: { + readonly from: RoomAgentRef; + readonly callerTurnId: TurnId; + /** The caller is its project's lead chat. */ + readonly isLead?: boolean; + }, ): ChildRequestRefusal | null { const caller = callerRefusal(thread, input); if (caller !== null) { @@ -139,10 +168,11 @@ export function childSendRefusal( if (ownRefusal !== null) { return ownRefusal; } - if (thread.childRequests.sendsSinceUser >= CHILD_THREAD_SEND_LIMIT) { + const limit = childRequestLimits({ isLead: input.isLead === true }).sends; + if (thread.childRequests.sendsSinceUser >= limit) { return { outcome: "limit", - detail: `Agents can send ${CHILD_THREAD_SEND_LIMIT} messages to their 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.`, + detail: `${input.isLead === true ? "The lead chat" : "Agents"} can send ${limit} messages to their 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; diff --git a/packages/shared/src/projectLead.ts b/packages/shared/src/projectLead.ts new file mode 100644 index 000000000..bcd2ab5bf --- /dev/null +++ b/packages/shared/src/projectLead.ts @@ -0,0 +1,98 @@ +/** + * A project's lead chat (docs/design/lead-chat.md): one ordinary thread the + * 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"; + +/** What the lead rules read from a project. */ +export interface LeadProject { + readonly id: ProjectId; + readonly kind: "workspace" | "general-chat"; + readonly leadThreadId?: ThreadId | null | undefined; +} + +/** What the lead rules read from a thread. */ +export interface LeadThread { + readonly id: ThreadId; + readonly projectId: ProjectId; + readonly parentThreadId: ThreadId | null; + readonly attachedToParent: boolean; + readonly archivedAt: string | null; + readonly deletedAt?: string | null | undefined; + readonly remoteOrigin?: unknown; + readonly outsideOrigin?: unknown; + readonly move?: unknown; + readonly pendingMove?: unknown; +} + +/** + * The project's lead thread id, or null. A pointer at a thread that is gone, + * archived or in another project counts as none, so replaying old events or + * a cascade an older build missed never leaves a ghost lead. + */ +export function projectLeadThreadId( + project: Pick<LeadProject, "id" | "leadThreadId"> | null | undefined, + findThread: (threadId: ThreadId) => LeadThread | null | undefined, +): ThreadId | null { + const leadThreadId = project?.leadThreadId ?? null; + if (project === null || project === undefined || leadThreadId === null) return null; + const thread = findThread(leadThreadId); + if ( + thread === null || + thread === undefined || + (thread.deletedAt ?? null) !== null || + thread.archivedAt !== null || + thread.projectId !== project.id + ) { + return null; + } + return leadThreadId; +} + +/** + * Why `thread` cannot become its project's lead chat, in words for the user, + * or null. The client adds the reasons only it knows (the "Agents can start + * threads" setting). + */ +export function leadSetRefusal(project: LeadProject, thread: LeadThread): string | null { + if (project.kind === "general-chat") return "General Chats can't have a lead chat."; + if (thread.projectId !== project.id) return "That thread is in another project."; + if ((thread.deletedAt ?? null) !== null) return "That thread was deleted."; + if (thread.archivedAt !== null) return "Archived threads can't be the lead chat."; + if (thread.parentThreadId !== null && thread.attachedToParent) { + return "This thread belongs to the thread that started it. Make it its own thread first."; + } + if ((thread.remoteOrigin ?? null) !== null) { + return "This thread was started from another computer."; + } + if ((thread.outsideOrigin ?? null) !== null) { + return "This thread was started by an outside agent."; + } + if ((thread.move ?? null) !== null || (thread.pendingMove ?? null) !== null) { + return "This thread is moving to another computer."; + } + return null; +} + +/** The words a lead's thread refuses a move with. */ +export const LEAD_MOVE_REFUSAL = "This is the project's lead chat. Pick another lead first."; + +/** + * Context added to every turn that starts in the lead (decision 5: per-turn + * context, so every provider hears it and Claude's system prompt stays the + * same across threads). + */ +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.', + "- 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.", + ].join("\n"); +} + +/** Added to the role text when the lead's agent came up without the thread tools. */ +export const LEAD_WITHOUT_TOOLS_TEXT = + "This agent has no thread tools here, so it cannot start or message threads. Tell the user that this agent can't coordinate the lead chat and that another agent can, and answer what you can yourself."; From c5a991754cfd9fad060fe2099b2d177b63e7a52a Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 16 Nov 2026 16:22:48 -0500 Subject: [PATCH 2/2] fix(web): drop the lead chat's keybinding command KeybindingCommand is a closed set that older clients decode strictly. A user rule naming navigate.leadChat would make an older client reject the whole keybinding list, and with it the computer's config. Go to lead chat stays in the command palette. --- apps/web/src/components/AppSidebarLayout.tsx | 11 +---------- apps/web/src/components/CommandPaletteDialog.tsx | 1 - apps/web/src/leadChat.ts | 16 ---------------- packages/contracts/src/keybindings.ts | 1 - 4 files changed, 1 insertion(+), 28 deletions(-) diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 85451ff04..2a312aa6c 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -24,7 +24,6 @@ import { usePublishMainAreaStart } from "../mainAreaLayout"; import { useServerKeybindings } from "../rpc/serverState"; import { selectThreadTerminalState, useTerminalStateStore } from "../terminalStateStore"; import { buildThreadRouteParams } from "../threadRoutes"; -import { readLeadChatTarget } from "../leadChat"; import { selectSidebarListShown, useUiStateStore } from "../uiStateStore"; import ThreadSidebar from "./Sidebar"; import { AppTitleBar } from "./sidebar/AppTitleBar"; @@ -112,20 +111,12 @@ function AppShellCommands({ hasList }: { readonly hasList: boolean }) { event.stopPropagation(); void navigate({ to: "/scheduled" }); } - if (command === "navigate.leadChat") { - // The lead of the open thread's project, else of the scoped project. - const leadRef = readLeadChatTarget(routeThreadRef ?? null, defaultProjectRef ?? null); - if (leadRef === null) return; - event.preventDefault(); - event.stopPropagation(); - void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(leadRef) }); - } }; window.addEventListener("keydown", onWindowKeyDown); return () => { window.removeEventListener("keydown", onWindowKeyDown); }; - }, [appHistory, defaultProjectRef, keybindings, navigate, routeThreadRef, toggleList]); + }, [appHistory, keybindings, navigate, routeThreadRef, toggleList]); useEffect(() => { const onMenuAction = window.desktopBridge?.onMenuAction; diff --git a/apps/web/src/components/CommandPaletteDialog.tsx b/apps/web/src/components/CommandPaletteDialog.tsx index dc60e082e..22f7a194e 100644 --- a/apps/web/src/components/CommandPaletteDialog.tsx +++ b/apps/web/src/components/CommandPaletteDialog.tsx @@ -2234,7 +2234,6 @@ export function OpenCommandPaletteDialog() { title: "Go to lead chat", description: project.name, icon: <FlagIcon className={ITEM_ICON_CLASS} />, - shortcutCommand: "navigate.leadChat", run: async () => { await navigate({ to: "/$environmentId/$threadId", diff --git a/apps/web/src/leadChat.ts b/apps/web/src/leadChat.ts index 3d30732df..0277f3439 100644 --- a/apps/web/src/leadChat.ts +++ b/apps/web/src/leadChat.ts @@ -269,22 +269,6 @@ export async function createLeadChat( return made ? scopeThreadRef(project.environmentId, threadId) : null; } -/** - * Where "Go to lead chat" goes: the lead of the open thread's project, else - * the lead of `fallbackProject` (the project in scope). Null when neither has one. - */ -export function readLeadChatTarget( - openThread: ScopedThreadRef | null, - fallbackProject: ScopedProjectRef | null, -): ScopedThreadRef | null { - const fromThread = openThread === null ? null : readProjectLeadRefForThread(openThread); - if (fromThread !== null) return fromThread; - if (fallbackProject === null) return null; - const state = useStore.getState(); - const project = selectProjectByRef(state, fallbackProject); - return project === undefined ? null : projectLeadRef(state, project); -} - /** * The project's name when `threadRef` is its lead chat, else null. A * primitive, so a store selector built on it redraws only when it changes. diff --git a/packages/contracts/src/keybindings.ts b/packages/contracts/src/keybindings.ts index 0f84ae646..d0190a480 100644 --- a/packages/contracts/src/keybindings.ts +++ b/packages/contracts/src/keybindings.ts @@ -63,7 +63,6 @@ const STATIC_KEYBINDING_COMMANDS = [ "sidebar.toggle", "navigate.fleet", "navigate.scheduled", - "navigate.leadChat", "navigate.back", "navigate.forward", ...MODEL_PICKER_KEYBINDING_COMMANDS,