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 01/11] 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 ? (
+
+
+
+ Lead chat
+
+
+ ) : 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 · ").
+- 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 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 "" there, as a
+ parent's messages are in a child today.
+
+### Starting several threads (approval card, every parent, not only the lead)
+
+The card " 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 "". 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 "" 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: , requestId: , 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 | 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 02/11] 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: ,
- 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,
From fd22ec8d99e8bd43fa27a4d405debac4cdf8effe Mon Sep 17 00:00:00 2001
From: Badcuban <108198679+badcuban@users.noreply.github.com>
Date: Mon, 16 Nov 2026 15:40:03 -0500
Subject: [PATCH 03/11] feat: the lead chat passes work to threads, and the
card starts some threads
The project's lead chat can now pass a message to a thread the user started
by hand (docs/design/lead-chat.md, piece 2 of 4). A pass is one-way: the
message lands in that thread as the lead's and the answer stays there. It
carries the lead's access as a ceiling, checked again whenever its turn
would start (from the queue, on retry and resend), and is taken back with a
line in the thread and a note for the lead when the thread has more access
by then. Rooms, threads another thread owns, threads the user stopped and
threads whose last turn failed are refused. A thread a pass started can't
start threads until a person writes there.
The approval card for several threads gets a checkbox per thread on servers
that can take a partial answer; unchecked ones are declined in the same
answer and the agent is told which. thread_list marks the lead and adds
last activity and known pull requests; outside agents see each project's
lead. Retry no longer picks a message still waiting in the queue, and the
queue moves on when a queued message is taken back instead of sent.
The thread tools' descriptions grew 383 bytes (agentContextBudget.json):
ACP agents learn the pass and lead rules only from them.
---
.../environment/Layers/ServerEnvironment.ts | 1 +
apps/server/src/guide/topics.ts | 4 +
apps/server/src/mcp/McpRoomServer.ts | 5 +
.../server/src/mcp/threadToolHandlers.test.ts | 52 ++-
apps/server/src/mcp/threadToolHandlers.ts | 193 ++++++++++-
apps/server/src/mcp/threadTools.ts | 11 +-
.../Layers/ProjectionPipeline.ts | 5 +-
.../Layers/ProjectionSnapshotQuery.ts | 27 +-
.../Layers/ProviderCommandReactor.ts | 21 +-
apps/server/src/orchestration/Schemas.ts | 2 +
.../src/orchestration/childThreadDecisions.ts | 146 ++++++--
.../orchestration/decider.projectLead.test.ts | 324 ++++++++++++++++++
apps/server/src/orchestration/decider.ts | 221 ++++++++++--
apps/server/src/orchestration/projector.ts | 19 +-
.../src/outsideAgents/connectToolHandlers.ts | 3 +-
apps/server/src/outsideAgents/connectTools.ts | 8 +-
.../src/provider/agentContextBudget.json | 2 +-
.../pullRequest/PullRequestObservations.ts | 28 +-
apps/server/src/threads/threadOperations.ts | 10 +
.../components/ChatView.agents.browser.tsx | 103 ++++++
.../chat/ComposerChildThreadsPanel.tsx | 44 ++-
apps/web/src/store.ts | 9 +-
docs/design/lead-chat.md | 10 +
packages/contracts/src/environment.ts | 6 +
packages/contracts/src/orchestration.ts | 87 +++++
packages/contracts/src/peerRpc.ts | 17 +
packages/shared/src/childThreads.ts | 191 ++++++++++-
packages/shared/src/projectLead.ts | 4 +-
28 files changed, 1471 insertions(+), 82 deletions(-)
diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.ts
index bd49d2553..b4a9bd6cb 100644
--- a/apps/server/src/environment/Layers/ServerEnvironment.ts
+++ b/apps/server/src/environment/Layers/ServerEnvironment.ts
@@ -117,6 +117,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function
pushAlerts: true,
phoneAlertControls: true,
projectLead: true,
+ childStartSelection: true,
deviceNames: true,
draftGoalSetup: true,
pullRequestSwitchesByNumber: true,
diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts
index 7bb9b1e8c..5f60e740c 100644
--- a/apps/server/src/guide/topics.ts
+++ b/apps/server/src/guide/topics.ts
@@ -112,6 +112,10 @@ A project's lead chat is a thread set up to coordinate the project; see the lead
Any thread can be the lead. Use "Make this the lead chat" in a thread's menu (right-click its row, or click the title above the chat), or the command palette. The project's menu in the project picker has Open lead chat, or New lead chat, which starts a thread in the project folder and makes it the lead. "Go to lead chat" in the command palette opens it.
+The lead can also pass a message to a thread you started by hand in the project. That is one-way: the thread works on it and answers there, not back in the lead, and it can't start threads of its own for it until you write there. The lead can't pass work into a room, a thread another thread still owns, or one you stopped. A pass never runs with more access than the lead had.
+
+When an agent asks to start several threads, the card has a checkbox per thread, so you can start some and leave the rest; the agent is told which.
+
Only one thread leads a project; making another the lead replaces it. "Stop using as lead chat" turns it back into an ordinary thread, and the threads it started stay with it. Archiving or deleting the lead ends it. A lead can't move to another computer, and each computer keeps its own lead for a project.
The lead's row sits at the top of the sidebar with a flag, says Lead where the project name goes, and never wraps up on its own. The chat shows a Lead chat label beside the title.
diff --git a/apps/server/src/mcp/McpRoomServer.ts b/apps/server/src/mcp/McpRoomServer.ts
index b97c87724..539173efa 100644
--- a/apps/server/src/mcp/McpRoomServer.ts
+++ b/apps/server/src/mcp/McpRoomServer.ts
@@ -16,6 +16,7 @@
* (scheduleTools.ts) are served here too: they need the same caller identity
* and the same per-runtime grant.
*/
+import { PullRequestObservations } from "../pullRequest/PullRequestObservations.ts";
import {
agentInvitesMode,
agentThreadsMode,
@@ -187,6 +188,7 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer(
const linkClient = yield* Effect.serviceOption(ComputerLinkClient);
const linkRepo = yield* Effect.serviceOption(ComputerLinkRepository);
const identities = yield* Effect.serviceOption(RepositoryIdentityResolver);
+ const pullRequestObservations = yield* Effect.serviceOption(PullRequestObservations);
const links =
Option.isSome(linkClient) && Option.isSome(linkRepo) && Option.isSome(identities)
? makeThreadToolLinks({
@@ -268,6 +270,9 @@ const RoomToolHandlersLive = RoomEndpointToolkit.toLayer(
snapshots
.getProjectShellById(projectId)
.pipe(Effect.map(Option.getOrUndefined), Effect.orDie),
+ ...(Option.isSome(pullRequestObservations)
+ ? { knownPullRequests: pullRequestObservations.value.known }
+ : {}),
providers: providers.getProviders,
userDefaultModel,
threadsMode: settings.getSettings.pipe(
diff --git a/apps/server/src/mcp/threadToolHandlers.test.ts b/apps/server/src/mcp/threadToolHandlers.test.ts
index 26eba1fa3..d928a9777 100644
--- a/apps/server/src/mcp/threadToolHandlers.test.ts
+++ b/apps/server/src/mcp/threadToolHandlers.test.ts
@@ -179,6 +179,8 @@ const shellOf = (thread: OrchestrationThread): OrchestrationThreadShell =>
pendingChildApproval: false,
awaitedChildThreadCount: 0,
doneOverride: null,
+ // Every real thread carries it (decoding defaults it); some fixtures leave it out.
+ linkedPullRequests: (thread as Partial).linkedPullRequests ?? [],
}) as unknown as OrchestrationThreadShell;
const mainCaller = (): McpInvocationScope => ({
@@ -210,6 +212,8 @@ const makeTools = (options: {
/** The branch checked out in a folder; any other folder has none. */
readonly branches?: Readonly>;
readonly moves?: ThreadToolMoves;
+ /** The project's lead chat (docs/design/lead-chat.md). */
+ readonly leadThreadId?: ThreadId;
}) =>
Effect.gen(function* () {
let caller = options.caller ?? makeThread();
@@ -259,7 +263,12 @@ const makeTools = (options: {
.filter((thread) => thread.projectId === PROJECT)
.map(shellOf),
),
- readProject: () => Effect.succeed({ kind: "workspace" as const, workspaceRoot: "/project" }),
+ readProject: () =>
+ Effect.succeed({
+ kind: "workspace" as const,
+ workspaceRoot: "/project",
+ leadThreadId: options.leadThreadId ?? null,
+ }),
providers: Effect.succeed(PROVIDERS),
userDefaultModel: Effect.succeed(options.userDefault ?? null),
threadsMode: Effect.succeed(options.mode ?? "auto"),
@@ -638,6 +647,47 @@ describe("thread_send", () => {
);
});
+describe("thread_send from the project's lead chat", () => {
+ it.effect("passes a message to a thread the user started, one-way", () =>
+ Effect.gen(function* () {
+ const handMade = makeChild({ id: STRANGER, parentThreadId: null, attachedToParent: false });
+ const tools = yield* makeTools({ others: [handMade], leadThreadId: PARENT });
+ const result = yield* tools.handlers.thread_send(mainCaller(), {
+ threadId: STRANGER,
+ message: "Fix the flaky test.",
+ });
+ expect(result).toMatchObject({ outcome: "sent", reportsBack: false, threadId: STRANGER });
+ const [passed] = ofType(tools.dispatched, "thread.lead.pass");
+ expect(passed).toMatchObject({ threadId: PARENT, targetThreadId: STRANGER });
+ expect(ofType(tools.dispatched, "thread.child.send")).toHaveLength(0);
+ }),
+ );
+
+ it.effect(
+ "refuses a thread another thread owns, and anything from a thread that isn't the lead",
+ () =>
+ Effect.gen(function* () {
+ const owned = makeChild({ id: STRANGER, parentThreadId: ThreadId.make("someone-else") });
+ const lead = yield* makeTools({ others: [owned], leadThreadId: PARENT });
+ const refused = yield* lead.handlers.thread_send(mainCaller(), {
+ threadId: STRANGER,
+ message: "Fix it.",
+ });
+ expect(refused.outcome).toBe("not_yours");
+ expect(refused.detail).toContain("Message the thread that started it");
+
+ const handMade = makeChild({ id: STRANGER, parentThreadId: null, attachedToParent: false });
+ const plain = yield* makeTools({ others: [handMade] });
+ const notLead = yield* plain.handlers.thread_send(mainCaller(), {
+ threadId: STRANGER,
+ message: "Fix it.",
+ });
+ expect(notLead.outcome).toBe("not_yours");
+ expect(lead.dispatched.length + plain.dispatched.length).toBe(0);
+ }),
+ );
+});
+
describe("an existing checkout", () => {
/** A thread the parent started that has finished its work, on its own branch. */
const coder = (patch: Partial = {}) =>
diff --git a/apps/server/src/mcp/threadToolHandlers.ts b/apps/server/src/mcp/threadToolHandlers.ts
index afbd4e988..1f0bca210 100644
--- a/apps/server/src/mcp/threadToolHandlers.ts
+++ b/apps/server/src/mcp/threadToolHandlers.ts
@@ -57,8 +57,10 @@ import {
childSendRefusal,
childStartRefusal,
isAttachedChild,
+ leadPassRefusal,
ownChildRefusal,
remoteChildOf,
+ withinModeCeiling,
} from "@threadlines/shared/childThreads";
import * as DateTime from "effect/DateTime";
import * as Effect from "effect/Effect";
@@ -130,7 +132,26 @@ export interface ThreadToolDeps {
readonly readProject: (
projectId: ProjectId,
) => Effect.Effect<
- Pick | undefined
+ | Pick<
+ OrchestrationProjectShell,
+ "kind" | "workspaceRoot" | "leadThreadId" | "repositoryIdentity"
+ >
+ | undefined
+ >;
+ /**
+ * A thread's pull requests as this computer already knows them, with no
+ * call to the host (PullRequestObservations.known). Absent: none listed.
+ */
+ readonly knownPullRequests?: (input: {
+ readonly repository: string | null;
+ readonly branch: string | null;
+ readonly urls: ReadonlyArray;
+ }) => Effect.Effect<
+ ReadonlyArray<{
+ readonly number: number;
+ readonly url: string;
+ readonly state: "open" | "merged" | "closed";
+ }>
>;
/** The provider snapshots: who a child could run on. */
readonly providers: Effect.Effect>;
@@ -1523,20 +1544,59 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) {
)
: [];
const scheduleAnswerWaiting = yield* waitingOnScheduleAnswers;
- return {
- outcome: "ok",
- threads: [
- ...listed.map((shell) =>
+ // Which thread leads the project, and what each listed thread's pull
+ // requests are as already known here (docs/design/lead-chat.md).
+ const project = yield* deps.readProject(thread.projectId);
+ const identity = project?.repositoryIdentity ?? null;
+ const repository =
+ identity?.owner !== undefined && identity.name !== undefined
+ ? `${identity.owner}/${identity.name}`
+ : null;
+ type KnownPullRequest = NonNullable[number];
+ const pullRequestsOf = (
+ shell: OrchestrationThreadShell,
+ ): Effect.Effect> =>
+ (deps.knownPullRequests === undefined
+ ? Effect.succeed([])
+ : deps.knownPullRequests({
+ repository,
+ branch: shell.branch,
+ urls: shell.linkedPullRequests.map((linked) => linked.url),
+ })
+ ).pipe(
+ Effect.map((known) => {
+ const byUrl = new Map(
+ known.map((entry) => [
+ entry.url,
+ { number: entry.number, url: entry.url, state: entry.state },
+ ]),
+ );
+ // One its agent opened that nobody has read yet: no state to say.
+ for (const linked of shell.linkedPullRequests) {
+ if (!byUrl.has(linked.url)) {
+ byUrl.set(linked.url, { number: linked.number, url: linked.url });
+ }
+ }
+ return [...byUrl.values()];
+ }),
+ );
+ const summaries = yield* Effect.forEach(listed, (shell) =>
+ pullRequestsOf(shell).pipe(
+ Effect.map((pullRequests): ThreadSummary =>
summarizeThread(shell, {
caller: thread,
providers,
titleOf: (threadId) => titles.get(threadId),
scheduleAnswerWaiting,
+ leadThreadId: project?.leadThreadId ?? null,
+ pullRequests,
}),
),
- ...settingUp,
- ...remote,
- ],
+ ),
+ );
+ return {
+ outcome: "ok",
+ threads: [...summaries, ...settingUp, ...remote],
} satisfies ThreadListResult;
});
@@ -1720,6 +1780,15 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) {
}
const owned = yield* ownChild(thread, scope, input.threadId);
if ("refusal" in owned) {
+ // The project's lead chat may pass a message to a thread it did not
+ // start (docs/design/lead-chat.md, "Tools"): one-way, never a move.
+ if (
+ owned.refusal.outcome === "not_yours" &&
+ checkoutReference === undefined &&
+ (yield* isLeadThread(thread))
+ ) {
+ return yield* leadPass(scope, thread, input.threadId, input.message);
+ }
return owned.refusal satisfies ThreadSendResult;
}
const childThreadId = owned.child.id;
@@ -1850,6 +1919,114 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) {
);
});
+ /**
+ * The lead chat passes `message` to a thread it did not start. Nothing is
+ * owed back: the thread answers where the user reads it. The decider checks
+ * the same rules again (leadPassRefusal) and the access ceiling.
+ */
+ const leadPass = (
+ scope: McpInvocationScope,
+ lead: OrchestrationThread,
+ targetReference: string,
+ message: string,
+ ): Effect.Effect =>
+ Effect.gen(function* () {
+ const targetId = targetReference.trim();
+ const text = message.trim();
+ if (text.length === 0) {
+ return { outcome: "refused", detail: "Say what you want from the thread." };
+ }
+ if (text.length > THREAD_PROMPT_CHAR_LIMIT) {
+ return {
+ outcome: "refused",
+ detail: `Keep the message under ${THREAD_PROMPT_CHAR_LIMIT.toLocaleString("en-US")} characters.`,
+ };
+ }
+ const callerTurnId = lead.session?.activeTurnId ?? NO_TURN;
+ const key = [
+ scope.threadId,
+ scope.participantId ?? "primary",
+ callerTurnId,
+ "thread_send:pass",
+ targetId,
+ text,
+ ].join("\u0000");
+ const requestId = ChildRequestId.make(derivedUuid(key, "request"));
+ const messageId = MessageId.make(derivedUuid(key, "message"));
+ const passedDetail = {
+ sent: "Passed on. That thread works on it where the user reads it; nothing comes back to you. Read it later with thread_read if the user asks.",
+ queued:
+ "Passed on. That thread is busy and takes it after its current turn; nothing comes back to you. Read it later with thread_read if the user asks.",
+ } as const;
+ return yield* deps.requests.join(key, () =>
+ Effect.gen(function* () {
+ const [caller, target] = yield* Effect.all([
+ deps.readThread(scope.threadId),
+ deps.readThread(ThreadId.make(targetId)),
+ ]);
+ if (caller === undefined) {
+ return { outcome: "refused", detail: GONE } satisfies ThreadSendResult;
+ }
+ // The same pass, already made in this turn: that one stands.
+ if (target?.messages.some((entry) => entry.id === messageId)) {
+ return {
+ outcome: "sent",
+ detail: passedDetail.sent,
+ threadId: targetId,
+ reportsBack: false,
+ } satisfies ThreadSendResult;
+ }
+ const refusal = leadPassRefusal(caller, target ?? null, {
+ from: from(scope),
+ callerTurnId,
+ isLead: yield* isLeadThread(caller),
+ });
+ if (refusal !== null || target === undefined) {
+ return {
+ outcome:
+ refusal?.outcome === "limit"
+ ? ("limit" as const)
+ : refusal?.outcome === "not_allowed"
+ ? ("not_yours" as const)
+ : ("refused" as const),
+ detail: refusal?.detail ?? NOT_FOUND,
+ threadId: targetId,
+ } satisfies ThreadSendResult;
+ }
+ if (!withinModeCeiling(target, caller)) {
+ return {
+ outcome: "refused",
+ detail:
+ "That thread has more access than the lead chat, so it can't take work from it. Tell the user, who can send it there.",
+ threadId: targetId,
+ } satisfies ThreadSendResult;
+ }
+ const outcome = childIsBusy(target, caller) ? ("queued" as const) : ("sent" as const);
+ const rejected = yield* dispatch({
+ type: "thread.lead.pass",
+ commandId: childRequestCommandId(requestId, "pass"),
+ threadId: scope.threadId,
+ from: from(scope),
+ callerTurnId,
+ targetThreadId: target.id,
+ requestId,
+ messageId,
+ text,
+ createdAt: yield* nowIso,
+ });
+ if (rejected !== undefined) {
+ return rejected satisfies ThreadSendResult;
+ }
+ return {
+ outcome,
+ detail: passedDetail[outcome],
+ threadId: target.id,
+ reportsBack: false,
+ } satisfies ThreadSendResult;
+ }),
+ );
+ });
+
const threadStop = (
scope: McpInvocationScope,
input: { readonly threadId: string },
diff --git a/apps/server/src/mcp/threadTools.ts b/apps/server/src/mcp/threadTools.ts
index b48a958c9..47527101b 100644
--- a/apps/server/src/mcp/threadTools.ts
+++ b/apps/server/src/mcp/threadTools.ts
@@ -140,6 +140,11 @@ export const ThreadSendResult = Schema.Struct({
]),
detail: Schema.optional(Schema.String),
threadId: Schema.optional(Schema.String),
+ /**
+ * False for a lead chat's pass to a thread it did not start
+ * (docs/design/lead-chat.md): nothing comes back from it.
+ */
+ reportsBack: Schema.optional(Schema.Boolean),
});
export type ThreadSendResult = typeof ThreadSendResult.Type;
@@ -241,7 +246,7 @@ export const ThreadStartTool = loadedOnDemand(
drivesThreads(
Tool.make("thread_start", {
description:
- "Start new threads in this project to work in parallel. Each gets its own agent session and its own git worktree off your current commit (in a project without git they share the project folder). Give each a short `title` and a self-contained `prompt`: the new thread sees none of this conversation, only its prompt. `agent` picks a model from thread_agents; leave it out to use your own model and reasoning. Unless the user asked for a model or reasoning, prefer your own model or one already in this room (thread_agents' `room`), here or on another computer: a thread on a room agent's model runs at the reasoning the user set for that agent. `agent.reasoning` sets a level instead. Threads get your current access and interaction modes, never more; `access` asks for less. `runSetup: false` skips the project's setup script, for quick research. `checkout` puts a thread in a checkout that already exists instead of a new worktree, so it sees the files as they are there, uncommitted changes included (a reviewer for work another thread just finished): no worktree or branch is made and the setup script is not run. It shares that folder with the thread it belongs to, so have only one of them work at a time. `computer` starts them on another linked computer (a name or id from thread_agents' `computers`) in its copy of this project: from your branch when you pushed it, otherwise from that computer's default branch, without your unpushed changes. With `reportBack` (default true) each thread's final reply comes back to you as a message when it finishes; with false they run on their own and nothing comes back. Returns as soon as they are recorded and does not wait for them, so don't poll: carry on, or end your turn if you have nothing else to do. At most 5 threads per call and 5 per user message.",
+ "Start new threads in this project to work in parallel. Each gets its own agent session and its own git worktree off your current commit (in a project without git they share the project folder). Give each a short `title` and a self-contained `prompt`: the new thread sees none of this conversation, only its prompt. `agent` picks a model from thread_agents; leave it out to use your own model and reasoning. Unless the user asked for a model or reasoning, prefer your own model or one already in this room (thread_agents' `room`), here or on another computer: a thread on a room agent's model runs at the reasoning the user set for that agent. `agent.reasoning` sets a level instead. Threads get your current access and interaction modes, never more; `access` asks for less. `runSetup: false` skips the project's setup script, for quick research. `checkout` puts a thread in a checkout that already exists instead of a new worktree, so it sees the files as they are there, uncommitted changes included (a reviewer for work another thread just finished): no worktree or branch is made and the setup script is not run. It shares that folder with the thread it belongs to, so have only one of them work at a time. `computer` starts them on another linked computer (a name or id from thread_agents' `computers`) in its copy of this project: from your branch when you pushed it, otherwise from that computer's default branch, without your unpushed changes. With `reportBack` (default true) each thread's final reply comes back to you as a message when it finishes; with false they run on their own and nothing comes back. Returns as soon as they are recorded and does not wait for them, so don't poll: carry on, or end your turn if you have nothing else to do. At most 5 threads per call and 5 per user message (10 in the project's lead chat).",
parameters: Schema.Struct({
threads: Schema.Array(
Schema.Struct({
@@ -279,7 +284,7 @@ export const ThreadListTool = loadedOnDemand(
readsThreads(
Tool.make("thread_list", {
description:
- 'Threads you started (`scope: "mine"`, the default), including ones the user made their own and ones on linked computers (with `computer` set, status as last heard), or this project\'s open threads (`"project"`, most recently active first, at most 30). Each has its id, title, status (working, needs the user, waiting, failed, idle, wrapped), branch, model, whether its replies come back to the thread that started it, and who started it.',
+ 'Threads you started (`scope: "mine"`, the default), including ones the user made their own and ones on linked computers (with `computer` set, status as last heard), or this project\'s open threads (`"project"`, most recently active first, at most 30). Each has its id, title, status (working, needs the user, waiting, failed, idle, wrapped), branch, model, whether its replies come back to the thread that started it, and who started it. The project\'s lead chat is marked `lead`; each also has when its work last moved and its pull requests as this computer knows them.',
parameters: Schema.Struct({
scope: Schema.optional(Schema.Literals(["mine", "project"])),
}),
@@ -323,7 +328,7 @@ export const ThreadSendTool = loadedOnDemand(
drivesThreads(
Tool.make("thread_send", {
description:
- "Send one of your threads a message: more work, a correction or a question. If it is idle it starts on it now; if it is busy it takes it after its current turn. Its reply comes back to you as a message, like a start. Only threads you started whose replies still come back to you. `checkout` first moves an idle thread into another thread's checkout, keeping its conversation, so it reads your message there (a thread that planned the work looks at what another thread built). Don't poll; end your turn if you have nothing else to do.",
+ "Send one of your threads a message: more work, a correction or a question. If it is idle it starts on it now; if it is busy it takes it after its current turn. Its reply comes back to you as a message, like a start. Only threads you started whose replies still come back to you. `checkout` first moves an idle thread into another thread's checkout, keeping its conversation, so it reads your message there (a thread that planned the work looks at what another thread built). The project's lead chat may also pass a message to an open thread in this project that it did not start (not a room, not one another thread owns, not one the user stopped): it works on it there, and nothing comes back. Don't poll; end your turn if you have nothing else to do.",
parameters: Schema.Struct({
threadId: ThreadIdParameter,
message: Schema.String.annotate({ description: "What you want it to do or answer." }),
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
index 8765afafd..ad7aff4c5 100644
--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
@@ -860,6 +860,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
case "thread.child-notes-delivered":
case "thread.child-deliveries-cancelled":
case "thread.child-requests-reset":
+ case "thread.lead-pass-recorded":
case "thread.remote-child-updated":
case "thread.remote-cancel-queued":
case "thread.remote-cancels-delivered": {
@@ -890,7 +891,9 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
state,
event.payload.requestIds,
)
- : childRequestStateOn.reset(state);
+ : event.type === "thread.lead-pass-recorded"
+ ? childRequestStateOn.leadPass(state, event.payload)
+ : childRequestStateOn.reset(state, event.payload);
if (childRequests !== state) {
yield* projectionThreadRepository.upsert({ ...existingRow.value, childRequests });
}
diff --git a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
index 188f93492..c06bbfabc 100644
--- a/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
@@ -155,6 +155,7 @@ const ProjectionProjectCatalogDbRowSchema = Schema.Struct({
kind: ProjectionProject.fields.kind,
title: ProjectionProject.fields.title,
workspaceRoot: ProjectionProject.fields.workspaceRoot,
+ leadThreadId: Schema.NullOr(ThreadId),
createdAt: ProjectionProject.fields.createdAt,
updatedAt: ProjectionProject.fields.updatedAt,
deletedAt: ProjectionProject.fields.deletedAt,
@@ -900,15 +901,22 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
execute: () =>
sql`
SELECT
- project_id AS "projectId",
- kind,
- title,
- workspace_root AS "workspaceRoot",
- created_at AS "createdAt",
- updated_at AS "updatedAt",
- deleted_at AS "deletedAt"
- FROM projection_projects
- ORDER BY created_at ASC, project_id ASC
+ p.project_id AS "projectId",
+ p.kind,
+ p.title,
+ p.workspace_root AS "workspaceRoot",
+ lead.thread_id AS "leadThreadId",
+ p.created_at AS "createdAt",
+ p.updated_at AS "updatedAt",
+ p.deleted_at AS "deletedAt"
+ FROM projection_projects p
+ -- A pointer at an archived, deleted or missing thread is no lead.
+ LEFT JOIN projection_threads lead
+ ON lead.thread_id = p.lead_thread_id
+ AND lead.project_id = p.project_id
+ AND lead.archived_at IS NULL
+ AND lead.deleted_at IS NULL
+ ORDER BY p.created_at ASC, p.project_id ASC
`,
});
@@ -2556,6 +2564,7 @@ const makeProjectionSnapshotQuery = Effect.gen(function* () {
kind: row.kind,
title: row.title,
workspaceRoot: row.workspaceRoot,
+ ...(row.leadThreadId !== null ? { leadThreadId: row.leadThreadId } : {}),
createdAt: row.createdAt,
updatedAt: row.updatedAt,
deletedAt: row.deletedAt,
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
index 4954cd6bc..fb0646c8f 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
@@ -2118,7 +2118,12 @@ const make = Effect.gen(function* () {
: undefined) ??
remoteChild?.title ??
"another thread";
- if (fromThread.kind === "request") {
+ if (fromThread.kind === "request" && fromThread.ceiling !== undefined) {
+ // A pass (docs/design/lead-chat.md): one-way, from the project's lead.
+ lines.push(
+ `The project's lead chat "${otherTitle}" passed this on. It is from another agent, not typed by the user. Your reply stays in this thread, where the user reads it. Do the work here; you can't start threads for it.`,
+ );
+ } else if (fromThread.kind === "request") {
lines.push(
thread.attachedToParent || fromThread.environmentId !== undefined
? `Another agent started this thread from the thread "${otherTitle}", and your final reply goes back to it automatically. Work in this thread's own checkout, and end with the answer it needs.`
@@ -5550,7 +5555,19 @@ const make = Effect.gen(function* () {
}),
),
);
- return;
+ // The decider can take a message back instead of starting its turn
+ // (a cancelled report, a lead chat's pass over its ceiling): then
+ // the next one goes, as nothing else will move the queue.
+ const after = yield* resolveThread(threadId);
+ const takenBack =
+ after !== undefined &&
+ after.session?.status !== "starting" &&
+ after.session?.status !== "running" &&
+ !(after.queuedFollowUps ?? []).some((queued) => queued.messageId === current);
+ const next = takenBack ? nextQueuedFollowUp(after) : undefined;
+ if (next === undefined || next.messageId === current) return;
+ candidate = next.messageId;
+ continue;
}
yield* orchestrationEngine
.dispatch({
diff --git a/apps/server/src/orchestration/Schemas.ts b/apps/server/src/orchestration/Schemas.ts
index 19558455a..e421910cd 100644
--- a/apps/server/src/orchestration/Schemas.ts
+++ b/apps/server/src/orchestration/Schemas.ts
@@ -30,6 +30,7 @@ import {
ThreadChildNotesDeliveredPayload as ContractsThreadChildNotesDeliveredPayloadSchema,
ThreadChildDeliveriesCancelledPayload as ContractsThreadChildDeliveriesCancelledPayloadSchema,
ThreadChildRequestsResetPayload as ContractsThreadChildRequestsResetPayloadSchema,
+ ThreadLeadPassRecordedPayload as ContractsThreadLeadPassRecordedPayloadSchema,
ThreadHandedBackPayload as ContractsThreadHandedBackPayloadSchema,
ThreadRemoteCancelQueuedPayload as ContractsThreadRemoteCancelQueuedPayloadSchema,
ThreadRemoteCancelsDeliveredPayload as ContractsThreadRemoteCancelsDeliveredPayloadSchema,
@@ -124,6 +125,7 @@ export const ThreadChildNotesDeliveredPayload = ContractsThreadChildNotesDeliver
export const ThreadChildDeliveriesCancelledPayload =
ContractsThreadChildDeliveriesCancelledPayloadSchema;
export const ThreadChildRequestsResetPayload = ContractsThreadChildRequestsResetPayloadSchema;
+export const ThreadLeadPassRecordedPayload = ContractsThreadLeadPassRecordedPayloadSchema;
export const ThreadHandedBackPayload = ContractsThreadHandedBackPayloadSchema;
export const ThreadRemoteChildUpdatedPayload = ContractsThreadRemoteChildUpdatedPayloadSchema;
export const ThreadRemoteCancelQueuedPayload = ContractsThreadRemoteCancelQueuedPayloadSchema;
diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts
index 81ca8296a..68f5effc3 100644
--- a/apps/server/src/orchestration/childThreadDecisions.ts
+++ b/apps/server/src/orchestration/childThreadDecisions.ts
@@ -42,6 +42,8 @@ import {
isSettingUpChildStart,
ownChildRefusal,
remoteChildOf,
+ leadPassRefusal,
+ withinModeCeiling,
} from "@threadlines/shared/childThreads";
import {
APPROVAL_ACTIVITY_KINDS,
@@ -53,6 +55,7 @@ import { activeParticipants } from "@threadlines/shared/threadParticipants";
import { handOffReplyText } from "./agentRequestDecisions.ts";
import { isProjectLeadThread } from "./commandInvariants.ts";
+
import { checkoutSelectedEvents } from "./threadCheckout.ts";
import { currentAgentModel, messageAgentModels } from "./messageAgentModels.ts";
@@ -71,17 +74,6 @@ export type ChildThreadDecision = ReadonlyArray | { readonly refus
const refuse = (refusal: string) => ({ refusal });
-/** Whether `child` asks for no more than `ceiling` allows. Plan is narrower than default. */
-export function withinModeCeiling(
- child: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },
- ceiling: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },
-): boolean {
- return (
- !exceedsRuntimeMode(child.runtimeMode, ceiling.runtimeMode) &&
- (ceiling.interactionMode !== "plan" || child.interactionMode === "plan")
- );
-}
-
/**
* A launch narrowed to its parent's access now: a request approved after the
* parent's access was lowered starts with the lower access, never the access
@@ -511,16 +503,39 @@ export function decideChildRespond(
`The user said not now to starting ${quotedList(titles)}. Don't ask again unless the user asks you to.`,
);
}
- return batch.map((request): PlannedEvent => ({
- ...baseFor(parent.id),
- type: "thread.child-request-updated",
- payload: {
- threadId: parent.id,
- requestId: request.requestId,
- status: "starting",
- updatedAt: command.createdAt,
- },
- }));
+ // Some of the batch, picked on the card: the rest are declined with it.
+ const picked = command.requestIds === undefined ? undefined : new Set(command.requestIds);
+ const starting =
+ picked === undefined ? batch : batch.filter((request) => picked.has(request.requestId));
+ if (starting.length === 0) {
+ return refuse("Pick at least one thread to start, or say not now.");
+ }
+ const declined = batch.filter((request) => !starting.includes(request));
+ const startedTitles = starting.map((request) => titleOf(readModel, request, parent));
+ return [
+ ...(declined.length === 0
+ ? []
+ : settleOpenRequests(
+ readModel,
+ baseFor,
+ parent,
+ declined,
+ "declined",
+ command.createdAt,
+ (titles) =>
+ `The user started ${quotedList(startedTitles)} but not ${quotedList(titles)}. Don't ask again for those unless the user asks you to.`,
+ )),
+ ...starting.map((request): PlannedEvent => ({
+ ...baseFor(parent.id),
+ type: "thread.child-request-updated",
+ payload: {
+ threadId: parent.id,
+ requestId: request.requestId,
+ status: "starting",
+ updatedAt: command.createdAt,
+ },
+ })),
+ ];
}
/** A message from an agent to one of its children (`thread.child.send`). */
@@ -678,6 +693,93 @@ export function decideChildSend(
];
}
+/**
+ * The lead chat passes a message to a thread it did not start
+ * (`thread.lead.pass`, docs/design/lead-chat.md, "A pass"). One-way: the
+ * message is queued in the target as the lead's, with the lead's access as
+ * its ceiling, and only the lead's send count is recorded. The tool handler
+ * checked the same rules first.
+ */
+export function decideLeadPass(
+ readModel: OrchestrationReadModel,
+ lead: OrchestrationThread,
+ command: CommandOf<"thread.lead.pass">,
+ baseFor: ChildEventBase,
+): ChildThreadDecision {
+ const target = findThread(readModel, command.targetThreadId);
+ const refusal = leadPassRefusal(lead, target, {
+ from: command.from,
+ callerTurnId: command.callerTurnId,
+ isLead: isProjectLeadThread(readModel, lead),
+ });
+ if (refusal !== null || target === null) {
+ return refuse(refusal?.detail ?? "That thread is gone.");
+ }
+ if (target.messages.some((message) => message.id === command.messageId)) {
+ return refuse("That message was already sent.");
+ }
+ const ceiling = { runtimeMode: lead.runtimeMode, interactionMode: lead.interactionMode };
+ if (!withinModeCeiling(target, ceiling)) {
+ return refuse(
+ "That thread has more access than the lead chat, so it can't take work from it. Tell the user, who can send it there.",
+ );
+ }
+ const fromThread = {
+ threadId: lead.id,
+ requestId: command.requestId,
+ kind: "request" as const,
+ ceiling,
+ ...(command.from.participantId !== null && command.from.participantId !== undefined
+ ? { passedBy: command.from.participantId }
+ : {}),
+ };
+ return [
+ {
+ ...baseFor(target.id),
+ type: "thread.message-sent",
+ payload: {
+ threadId: target.id,
+ messageId: command.messageId,
+ role: "user",
+ text: command.text,
+ attachments: [],
+ fromThread,
+ turnId: null,
+ streaming: false,
+ createdAt: command.createdAt,
+ updatedAt: command.createdAt,
+ },
+ },
+ {
+ ...baseFor(target.id),
+ type: "thread.follow-up-queued",
+ payload: {
+ threadId: target.id,
+ followUp: {
+ messageId: command.messageId,
+ text: command.text,
+ attachments: [],
+ fromThread,
+ runtimeMode: target.runtimeMode,
+ interactionMode: target.interactionMode,
+ createdAt: command.createdAt,
+ },
+ },
+ },
+ {
+ ...baseFor(lead.id),
+ type: "thread.lead-pass-recorded",
+ payload: {
+ threadId: lead.id,
+ kind: "sent",
+ messageId: command.messageId,
+ targetThreadId: target.id,
+ createdAt: command.createdAt,
+ },
+ },
+ ];
+}
+
/**
* A message to a child on a linked computer: only the parent's request is
* written here. RemoteChildReactor sends it there, where it is queued in the
@@ -1751,4 +1853,4 @@ export const isAgentQueued = (queued: {
readonly fromThread?: unknown;
}) => isAgentOrigin(queued);
-export { isAttachedChild };
+export { isAttachedChild, withinModeCeiling };
diff --git a/apps/server/src/orchestration/decider.projectLead.test.ts b/apps/server/src/orchestration/decider.projectLead.test.ts
index 99bf3d217..240025932 100644
--- a/apps/server/src/orchestration/decider.projectLead.test.ts
+++ b/apps/server/src/orchestration/decider.projectLead.test.ts
@@ -1,6 +1,11 @@
import {
+ ChildRequestBatchId,
+ ChildRequestId,
CommandId,
DEFAULT_PROVIDER_INTERACTION_MODE,
+ LEAD_PASS_NOT_RUN_ACTIVITY_KIND,
+ MessageId,
+ type OrchestrationSession,
EMPTY_AGENT_REQUEST_STATE,
EMPTY_CHILD_REQUEST_STATE,
type OrchestrationCommand,
@@ -10,7 +15,9 @@ import {
ProjectId,
ProviderInstanceId,
ThreadId,
+ TurnId,
} from "@threadlines/contracts";
+import { childStartRefusal } from "@threadlines/shared/childThreads";
import { LEAD_MOVE_REFUSAL } from "@threadlines/shared/projectLead";
import * as Effect from "effect/Effect";
import * as Exit from "effect/Exit";
@@ -213,3 +220,320 @@ describe("project lead chat", () => {
});
});
});
+
+const LEAD_TURN = TurnId.make("lead-turn-1");
+const PRIMARY = { participantId: null };
+
+function session(threadId: ThreadId, overrides: Partial = {}) {
+ return {
+ threadId,
+ status: "running",
+ providerName: "claudeAgent",
+ providerInstanceId: ProviderInstanceId.make("claudeAgent"),
+ runtimeMode: "auto-accept-edits",
+ activeTurnId: LEAD_TURN,
+ lastError: null,
+ updatedAt: now,
+ ...overrides,
+ } satisfies OrchestrationSession;
+}
+
+/** A lead at work, and a thread the user started by hand. */
+async function leadAndHandMade(target: Partial = {}) {
+ return (
+ await run(
+ readModel([
+ thread(LEAD, { session: session(LEAD), runtimeMode: "auto-accept-edits" }),
+ thread(OTHER, { runtimeMode: "approval-required", ...target }),
+ ]),
+ setLead(LEAD),
+ )
+ ).model;
+}
+
+const PASS_MESSAGE = MessageId.make("pass-message-1");
+const pass = (
+ overrides: Partial> = {},
+) =>
+ ({
+ type: "thread.lead.pass",
+ commandId: CommandId.make("pass-1"),
+ threadId: LEAD,
+ from: PRIMARY,
+ callerTurnId: LEAD_TURN,
+ targetThreadId: OTHER,
+ requestId: ChildRequestId.make("pass-request-1"),
+ messageId: PASS_MESSAGE,
+ text: "Fix the flaky checkout test.",
+ createdAt: now,
+ ...overrides,
+ }) satisfies OrchestrationCommand;
+
+const sendQueued = (messageId: MessageId): OrchestrationCommand => ({
+ type: "thread.follow-up.send-queued",
+ commandId: CommandId.make(`send-${messageId}`),
+ threadId: OTHER,
+ messageId,
+ createdAt: now,
+});
+
+describe("lead chat passes", () => {
+ it("queues a pass in a thread the lead did not start, records no request, and runs it there", async () => {
+ const start = await leadAndHandMade();
+ const passed = await run(start, pass());
+ const lead = threadIn(passed.model, LEAD);
+ const target = threadIn(passed.model, OTHER);
+ expect(lead.childRequests.open).toEqual([]);
+ expect(lead.childRequests.sendsSinceUser).toBe(1);
+ const message = target.messages.find((entry) => entry.id === PASS_MESSAGE);
+ expect(message?.fromThread).toMatchObject({
+ threadId: LEAD,
+ kind: "request",
+ ceiling: { runtimeMode: "auto-accept-edits" },
+ });
+
+ const ran = await run(passed.model, sendQueued(PASS_MESSAGE));
+ expect(ran.events.some((event) => event.type === "thread.turn-start-requested")).toBe(true);
+ // Nothing is owed back: no request settles anywhere.
+ expect(ran.events.some((event) => event.type.startsWith("thread.child-request"))).toBe(false);
+ expect(threadIn(ran.model, OTHER).childRequests.startsBlockedByPass).toBe(true);
+ });
+
+ it("refuses rooms, threads another thread owns, and threads the user stopped", async () => {
+ const room = await leadAndHandMade({
+ participants: [
+ {
+ id: "agent-1" as never,
+ handle: "Reviewer",
+ modelSelection: model,
+ addedAt: now,
+ } as never,
+ ],
+ });
+ expect(await refusal(room, pass())).toContain("Rooms take work from the user");
+ const owned = await leadAndHandMade({ parentThreadId: CHILD, attachedToParent: true });
+ expect(await refusal(owned, pass())).toContain("Message the thread that started it");
+ const stopped = await leadAndHandMade({
+ latestTurn: {
+ turnId: TurnId.make("t"),
+ state: "interrupted",
+ requestedAt: now,
+ startedAt: now,
+ completedAt: now,
+ assistantMessageId: null,
+ },
+ });
+ expect(await refusal(stopped, pass())).toContain("The user stopped that thread");
+ // A thread that is not the lead can't pass anything.
+ const notLead = (await run(await leadAndHandMade(), setLead(null))).model;
+ expect(await refusal(notLead, pass())).toContain("not a thread you started");
+ });
+
+ it("takes a pass back when a user message queued ahead widened the thread's access", async () => {
+ const passed = (await run(await leadAndHandMade(), pass())).model;
+ // The user raised the thread's access while the pass waited.
+ const widened = (
+ await run(passed, {
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("widen"),
+ threadId: OTHER,
+ runtimeMode: "full-access",
+ createdAt: now,
+ })
+ ).model;
+ const sent = await run(widened, sendQueued(PASS_MESSAGE));
+ expect(sent.events.some((event) => event.type === "thread.turn-start-requested")).toBe(false);
+ const target = threadIn(sent.model, OTHER);
+ expect(target.queuedFollowUps ?? []).toEqual([]);
+ expect(target.activities.some((entry) => entry.kind === LEAD_PASS_NOT_RUN_ACTIVITY_KIND)).toBe(
+ true,
+ );
+ expect(threadIn(sent.model, LEAD).childRequests.pendingNotes[0]?.text).toContain("did not run");
+ });
+
+ it("refuses to retry a pass above its ceiling: the user sends it themselves", async () => {
+ const ran = (
+ await run(
+ await run(await leadAndHandMade(), pass()).then((r) => r.model),
+ sendQueued(PASS_MESSAGE),
+ )
+ ).model;
+ const failed = {
+ ...ran,
+ threads: ran.threads.map((entry) =>
+ entry.id === OTHER
+ ? {
+ ...entry,
+ runtimeMode: "full-access" as const,
+ session: session(OTHER, { status: "error", activeTurnId: null, lastError: "boom" }),
+ }
+ : entry,
+ ),
+ };
+ expect(
+ await refusal(failed, {
+ type: "thread.turn.retry",
+ commandId: CommandId.make("retry"),
+ threadId: OTHER,
+ createdAt: now,
+ }),
+ ).toContain("Send it yourself to run it");
+ });
+
+ it("retries the failed turn, never a pass still waiting in the queue", async () => {
+ // The pass waits behind a turn of the user's that then fails.
+ const userMessage = MessageId.make("user-own");
+ const busy = await leadAndHandMade({
+ messages: [
+ {
+ id: userMessage,
+ role: "user",
+ text: "Mine.",
+ turnId: null,
+ streaming: false,
+ createdAt: now,
+ updatedAt: now,
+ },
+ ],
+ });
+ const passed = (await run(busy, pass())).model;
+ const failed = {
+ ...passed,
+ threads: passed.threads.map((entry) =>
+ entry.id === OTHER
+ ? {
+ ...entry,
+ session: session(OTHER, { status: "error", activeTurnId: null, lastError: "boom" }),
+ }
+ : entry,
+ ),
+ };
+ const retried = await run(failed, {
+ type: "thread.turn.retry",
+ commandId: CommandId.make("retry-own"),
+ threadId: OTHER,
+ createdAt: now,
+ });
+ const requested = retried.events.find((event) => event.type === "thread.turn-start-requested");
+ expect((requested?.payload as { messageId?: string }).messageId).toBe(userMessage);
+ expect(threadIn(retried.model, OTHER).queuedFollowUps?.map((entry) => entry.messageId)).toEqual(
+ [PASS_MESSAGE],
+ );
+ });
+
+ it("keeps a passed-to thread from starting threads through a continue, until the user writes", async () => {
+ const ran = (
+ await run(
+ await run(await leadAndHandMade(), pass()).then((r) => r.model),
+ sendQueued(PASS_MESSAGE),
+ )
+ ).model;
+ const blocked = (current: OrchestrationReadModel) =>
+ // Asked from inside a turn of its own, as thread_start is.
+ childStartRefusal(
+ { ...threadIn(current, OTHER), session: session(OTHER) },
+ { from: PRIMARY, callerTurnId: LEAD_TURN, count: 1 },
+ );
+ const idle = {
+ ...ran,
+ threads: ran.threads.map((entry) =>
+ entry.id === OTHER
+ ? { ...entry, session: session(OTHER, { status: "ready", activeTurnId: null }) }
+ : entry,
+ ),
+ };
+ const turn = (
+ id: string,
+ extra: Partial>,
+ ) =>
+ ({
+ type: "thread.turn.start",
+ commandId: CommandId.make(`turn-${id}`),
+ threadId: OTHER,
+ message: { messageId: MessageId.make(id), role: "user", text: id, attachments: [] },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ createdAt: now,
+ ...extra,
+ }) satisfies OrchestrationCommand;
+ const continued = (await run(idle, turn("continue", { trigger: "usageLimitReset" }))).model;
+ expect(blocked(continued)?.detail).toContain("the lead chat passed on");
+ // Nor does a turn no person sent (an automatic fix, a scheduled run).
+ const automatic = (
+ await run(
+ {
+ ...continued,
+ threads: continued.threads.map((entry) =>
+ entry.id === OTHER
+ ? { ...entry, session: session(OTHER, { status: "ready", activeTurnId: null }) }
+ : entry,
+ ),
+ },
+ turn("auto-fix", {}),
+ )
+ ).model;
+ expect(blocked(automatic)?.detail).toContain("the lead chat passed on");
+ const settled = {
+ ...continued,
+ threads: continued.threads.map((entry) =>
+ entry.id === OTHER
+ ? { ...entry, session: session(OTHER, { status: "ready", activeTurnId: null }) }
+ : entry,
+ ),
+ };
+ const wrote = (await run(settled, turn("user", { composer: "typed" }))).model;
+ expect(threadIn(wrote, OTHER).childRequests.startsBlockedByPass).toBeUndefined();
+ });
+
+ it("starts only the threads the user left checked, and tells the agent which it didn't", async () => {
+ const first = ChildRequestId.make("start-1");
+ const second = ChildRequestId.make("start-2");
+ const asked = (
+ await run(readModel([thread(LEAD, { session: session(LEAD) })]), {
+ type: "thread.child.start",
+ commandId: CommandId.make("ask"),
+ threadId: LEAD,
+ batchId: ChildRequestBatchId.make("batch"),
+ from: PRIMARY,
+ callerTurnId: LEAD_TURN,
+ mode: "ask",
+ children: [first, second].map((requestId, index) => ({
+ requestId,
+ childThreadId: ThreadId.make(`kid-${index}`),
+ childMessageId: MessageId.make(`kid-message-${index}`),
+ launch: {
+ title: `Task ${index + 1}`,
+ prompt: "Do it.",
+ modelSelection: model,
+ runtimeMode: "auto-accept-edits",
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ reportBack: true,
+ runSetup: true,
+ workspace: { kind: "worktree", projectCwd: "/repo", baseRef: "main" },
+ },
+ })),
+ createdAt: now,
+ })
+ ).model;
+ const answered = await run(asked, {
+ type: "thread.child-request.respond",
+ commandId: CommandId.make("respond"),
+ threadId: LEAD,
+ batchId: ChildRequestBatchId.make("batch"),
+ choice: "start",
+ requestIds: [first],
+ createdAt: now,
+ });
+ const state = threadIn(answered.model, LEAD).childRequests;
+ expect(state.open.map((request) => [request.requestId, request.status])).toEqual([
+ [first, "starting"],
+ ]);
+ expect(state.pendingNotes[0]?.text).toContain("but not 'Task 2'");
+ });
+});
+
+const threadIn = (current: OrchestrationReadModel, id: ThreadId) => {
+ const found = current.threads.find((entry) => entry.id === id);
+ if (found === undefined) throw new Error(`no thread ${id}`);
+ return found;
+};
diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts
index 4aaee8332..44efbe15c 100644
--- a/apps/server/src/orchestration/decider.ts
+++ b/apps/server/src/orchestration/decider.ts
@@ -2,6 +2,7 @@ import {
DEFAULT_PROJECT_KIND,
EMPTY_AGENT_REQUEST_STATE,
EventId,
+ LEAD_PASS_NOT_RUN_ACTIVITY_KIND,
MessageId,
type OrchestrationCommand,
type OrchestrationContinueAtReset,
@@ -48,7 +49,7 @@ import {
} from "@threadlines/shared/commandRuns";
import { isTurnAside } from "@threadlines/shared/transcriptRevert";
import { CONTINUE_AT_RESET_MESSAGE, continueAtResetTimeMs } from "@threadlines/shared/usageLimits";
-import { isAttachedChild } from "@threadlines/shared/childThreads";
+import { isAttachedChild, passCeilingRefusal } from "@threadlines/shared/childThreads";
import { leadSetRefusal } from "@threadlines/shared/projectLead";
import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests";
@@ -102,6 +103,7 @@ import {
decideChildRequestUpdate,
decideChildRespond,
decideChildSend,
+ decideLeadPass,
decideChildStart,
decideChildrenStop,
decideParentAttachmentSet,
@@ -292,24 +294,114 @@ function childEventBase(
});
}
-/** The user wrote: the per-message child thread counts start over. */
+/**
+ * The user wrote: the per-message child thread counts start over, and a
+ * lead chat's pass no longer blocks starting threads. A turn Threadlines
+ * started for the user (`keepsPassBlock`: a continue, a restart) resets the
+ * counts but keeps that block (docs/design/lead-chat.md, "No fan-out").
+ */
function resetChildRequestsForUser(
thread: OrchestrationThread,
base: () => Omit,
createdAt: string,
+ options?: { readonly keepsPassBlock?: boolean },
): ReadonlyArray {
const state = thread.childRequests;
- return state.startsSinceUser === 0 && state.sendsSinceUser === 0
+ const keepsPassBlock = options?.keepsPassBlock === true;
+ const liftsBlock = state.startsBlockedByPass === true && !keepsPassBlock;
+ return state.startsSinceUser === 0 && state.sendsSinceUser === 0 && !liftsBlock
? []
: [
{
...base(),
type: "thread.child-requests-reset",
- payload: { threadId: thread.id, createdAt },
+ payload: {
+ threadId: thread.id,
+ ...(keepsPassBlock ? { keepsPassBlock: true as const } : {}),
+ createdAt,
+ },
},
];
}
+/**
+ * Whether a person sent this message from the app (they typed it, or their
+ * signed-in device sent it). Only that lifts a lead chat's pass block: a
+ * scheduled run, an automatic fix or a continue resets the counts but keeps it.
+ */
+const personWrote = (command: {
+ readonly composer?: unknown;
+ readonly sentFrom?: unknown;
+}): boolean => command.composer !== undefined || command.sentFrom !== undefined;
+
+/**
+ * A pass whose ceiling is under the thread's access when its turn would
+ * start (docs/design/lead-chat.md, "Access"): taken off the queue, one line
+ * in the thread, and a note for the lead's next turn when it is still there.
+ */
+function passCeilingCancelEvents(
+ readModel: OrchestrationReadModel,
+ thread: OrchestrationThread,
+ queued: {
+ readonly messageId: MessageId;
+ readonly fromThread?: OrchestrationMessage["fromThread"];
+ },
+ refusal: string,
+ base: () => Omit,
+ createdAt: string,
+): PlannedOrchestrationEvent[] {
+ const origin = queued.fromThread;
+ const lead =
+ origin === undefined
+ ? undefined
+ : readModel.threads.find((entry) => entry.id === origin.threadId);
+ return [
+ {
+ ...base(),
+ type: "thread.follow-up-unqueued",
+ payload: { threadId: thread.id, messageId: queued.messageId, reason: "cancelled", createdAt },
+ },
+ {
+ ...base(),
+ type: "thread.activity-appended",
+ payload: {
+ threadId: thread.id,
+ activity: {
+ id: EventId.make(crypto.randomUUID()),
+ tone: "info",
+ kind: LEAD_PASS_NOT_RUN_ACTIVITY_KIND,
+ summary: refusal,
+ payload: { messageId: queued.messageId },
+ turnId: null,
+ createdAt,
+ },
+ },
+ },
+ ...(lead === undefined || lead.deletedAt !== null || origin === undefined
+ ? []
+ : [
+ {
+ ...base(),
+ aggregateId: lead.id,
+ type: "thread.lead-pass-recorded" as const,
+ payload: {
+ threadId: lead.id,
+ kind: "refused" as const,
+ messageId: queued.messageId,
+ targetThreadId: thread.id,
+ note: {
+ requestId: origin.requestId,
+ recipient: { participantId: origin.passedBy ?? null },
+ text: `The message you passed to "${thread.title}" (thread ${thread.id}) did not run: that thread has more access than this lead chat now. Tell the user, who can send it there.`,
+ createdAt,
+ },
+ createdAt,
+ },
+ },
+ ]),
+ ];
+}
+
type DecideOrchestrationCommandResult =
| PlannedOrchestrationEvent
| ReadonlyArray;
@@ -741,7 +833,9 @@ function decideFollowUpSubmit(
return withLeadingEvents(
[
...resetAgentRequestsForUser(targetThread, userBase, command.createdAt),
- ...resetChildRequestsForUser(targetThread, userBase, command.createdAt),
+ ...resetChildRequestsForUser(targetThread, userBase, command.createdAt, {
+ keepsPassBlock: !personWrote(command),
+ }),
...closedQuestions,
],
{
@@ -782,7 +876,9 @@ function decideFollowUpSubmit(
return withLeadingEvents(
[
...resetAgentRequestsForUser(targetThread, steerBase, command.createdAt),
- ...resetChildRequestsForUser(targetThread, steerBase, command.createdAt),
+ ...resetChildRequestsForUser(targetThread, steerBase, command.createdAt, {
+ keepsPassBlock: !personWrote(command),
+ }),
...closedQuestions,
],
{
@@ -2269,6 +2365,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
case "thread.child.start":
case "thread.child-request.respond":
case "thread.child.send":
+ case "thread.lead.pass":
case "thread.child-request.update":
case "thread.child-request.settle":
case "thread.child-notes.delivered":
@@ -2290,19 +2387,21 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
? decideChildRespond(readModel, thread, command, baseFor)
: command.type === "thread.child.send"
? decideChildSend(readModel, thread, command, baseFor)
- : command.type === "thread.child-request.update"
- ? decideChildRequestUpdate(thread, command, baseFor)
- : command.type === "thread.child-request.settle"
- ? decideChildRequestSettle(readModel, thread, command, baseFor)
- : command.type === "thread.remote-child.update"
- ? decideRemoteChildUpdate(thread, command, baseFor)
- : command.type === "thread.remote-cancels.delivered"
- ? decideRemoteCancelsDelivered(thread, command, baseFor)
- : command.type === "thread.remote-request.queue"
- ? decideRemoteRequestQueue(thread, command, baseFor)
- : command.type === "thread.remote-handed-back.record"
- ? decideRemoteHandedBackRecord(thread, command, baseFor)
- : decideChildNotesDelivered(thread, command, baseFor),
+ : command.type === "thread.lead.pass"
+ ? decideLeadPass(readModel, thread, command, baseFor)
+ : command.type === "thread.child-request.update"
+ ? decideChildRequestUpdate(thread, command, baseFor)
+ : command.type === "thread.child-request.settle"
+ ? decideChildRequestSettle(readModel, thread, command, baseFor)
+ : command.type === "thread.remote-child.update"
+ ? decideRemoteChildUpdate(thread, command, baseFor)
+ : command.type === "thread.remote-cancels.delivered"
+ ? decideRemoteCancelsDelivered(thread, command, baseFor)
+ : command.type === "thread.remote-request.queue"
+ ? decideRemoteRequestQueue(thread, command, baseFor)
+ : command.type === "thread.remote-handed-back.record"
+ ? decideRemoteHandedBackRecord(thread, command, baseFor)
+ : decideChildNotesDelivered(thread, command, baseFor),
);
}
@@ -2973,6 +3072,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
detail: "The request this turn answers was cancelled.",
});
}
+ // A lead chat's pass never starts above the access it was passed with.
+ const passStartRefusal = passCeilingRefusal(command, targetThread);
+ if (passStartRefusal !== null) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: passStartRefusal,
+ });
+ }
// An outside agent's turn (docs/design/outside-agents.md): only in a
// thread it started (any thread at Work), never above its ceiling,
// never into a busy thread (an answer's own turn passes over its
@@ -3299,12 +3406,31 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
},
]
: [];
+ // A lead chat's pass starting its turn: no threads may be started from
+ // here until the user writes (docs/design/lead-chat.md, "No fan-out").
+ const passStartedEvents: ReadonlyArray =
+ command.fromThread?.ceiling !== undefined
+ ? [
+ {
+ ...turnBase(),
+ type: "thread.lead-pass-recorded",
+ payload: {
+ threadId: command.threadId,
+ kind: "started",
+ messageId: command.message.messageId,
+ targetThreadId: command.threadId,
+ createdAt: command.createdAt,
+ },
+ },
+ ]
+ : [];
return [
userMessageEvent,
...(titleSeedEvent ? [titleSeedEvent] : []),
...(startingSessionEvent ? [startingSessionEvent] : []),
turnStartRequestedEvent,
...requestRunningEvents,
+ ...passStartedEvents,
// The user wrote: agents may make requests again. (A queued message
// sent later drops these; it counted when the user queued it.) An
// agent's message, another thread's or an outside agent's, is not
@@ -3312,7 +3438,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
...(command.fromThread === undefined && command.fromOutside === undefined
? [
...resetAgentRequestsForUser(targetThread, turnBase, command.createdAt),
- ...resetChildRequestsForUser(targetThread, turnBase, command.createdAt),
+ ...resetChildRequestsForUser(targetThread, turnBase, command.createdAt, {
+ keepsPassBlock: command.trigger !== undefined || !personWrote(command),
+ }),
...settleCandidateBeforeUserTurn(readModel, targetThread, command),
]
: []),
@@ -3349,7 +3477,14 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
// What sits beside a turn (an invite, an invited review, a message
// steered into it while it ran) is never the turn's own message, so it
// is never what a retry sends again.
- const turnMessages = targetThread.messages.filter((message) => !isTurnAside(message));
+ // Nor is a message still waiting in the queue: it hasn't run yet, and
+ // runs from there in its turn.
+ const queuedIds = new Set(
+ (targetThread.queuedFollowUps ?? []).map((queued) => queued.messageId),
+ );
+ const turnMessages = targetThread.messages.filter(
+ (message) => !isTurnAside(message) && !queuedIds.has(message.id),
+ );
if (!session || (command.type === "thread.turn.retry" && session.lastError === null)) {
return yield* new OrchestrationCommandInvariantError({
commandType: command.type,
@@ -3386,6 +3521,15 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
detail: `This message came from ${lastUserMessage.fromOutside.name}, outside Threadlines. Ask it to send it again, or write it yourself.`,
});
}
+ // A lead chat's pass runs again only within the access it was passed
+ // with; above it, the user sends it themselves.
+ const retryPassRefusal = passCeilingRefusal(lastUserMessage, targetThread);
+ if (retryPassRefusal !== null) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail: `${retryPassRefusal} Send it yourself to run it.`,
+ });
+ }
// A failed turn is retried with the agent that failed it: the slot
// still holds that agent's session.
const retryParticipantId = sessionSlotParticipantId(session);
@@ -3464,6 +3608,27 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
return [
retrySessionEvent,
retryTurnStartRequestedEvent,
+ // A lead chat's pass, run again: still no threads started from it.
+ ...(lastUserMessage.fromThread?.ceiling !== undefined
+ ? [
+ {
+ ...withEventBase({
+ aggregateKind: "thread",
+ aggregateId: command.threadId,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ }),
+ type: "thread.lead-pass-recorded" as const,
+ payload: {
+ threadId: command.threadId,
+ kind: "started" as const,
+ messageId: lastUserMessage.id,
+ targetThreadId: command.threadId,
+ createdAt: command.createdAt,
+ },
+ },
+ ]
+ : []),
...resetAgentRequestsForUser(
targetThread,
() =>
@@ -3711,6 +3876,20 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
) {
return [{ ...unqueuedEvent, payload: { ...unqueuedEvent.payload, reason: "cancelled" } }];
}
+ // A lead chat's pass runs only within the lead's access as it was when
+ // passed. A user message queued ahead may have widened the thread's
+ // access since; then the pass is taken back instead.
+ const passRefusal = passCeilingRefusal(queued, targetThread);
+ if (passRefusal !== null) {
+ return passCeilingCancelEvents(
+ readModel,
+ targetThread,
+ queued,
+ passRefusal,
+ sendBase,
+ command.createdAt,
+ );
+ }
// A message an agent queued carries no model: its agent's current one
// applies (the thread's own model for the thread's own agent), so a
// model change since it was queued is honored.
diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index e17319969..f885ed587 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -107,6 +107,7 @@ import {
ThreadChildRequestSubmittedPayload,
ThreadChildRequestUpdatedPayload,
ThreadChildRequestsResetPayload,
+ ThreadLeadPassRecordedPayload,
ThreadHandedBackPayload,
ThreadRemoteCancelQueuedPayload,
ThreadRemoteCancelsDeliveredPayload,
@@ -990,7 +991,23 @@ export function projectEvent(
"payload",
).pipe(
Effect.map((payload) =>
- updateChildRequests(nextBase, payload.threadId, childRequestStateOn.reset),
+ updateChildRequests(nextBase, payload.threadId, (state) =>
+ childRequestStateOn.reset(state, payload),
+ ),
+ ),
+ );
+
+ case "thread.lead-pass-recorded":
+ return decodeForEvent(
+ ThreadLeadPassRecordedPayload,
+ event.payload,
+ event.type,
+ "payload",
+ ).pipe(
+ Effect.map((payload) =>
+ updateChildRequests(nextBase, payload.threadId, (state) =>
+ childRequestStateOn.leadPass(state, payload),
+ ),
),
);
diff --git a/apps/server/src/outsideAgents/connectToolHandlers.ts b/apps/server/src/outsideAgents/connectToolHandlers.ts
index 93113ef72..9f9986d37 100644
--- a/apps/server/src/outsideAgents/connectToolHandlers.ts
+++ b/apps/server/src/outsideAgents/connectToolHandlers.ts
@@ -307,7 +307,7 @@ export interface ConnectToolDeps {
export type ConnectProject = Pick<
OrchestrationProjectCatalogEntry,
"id" | "kind" | "title" | "workspaceRoot"
->;
+> & { readonly leadThreadId?: ThreadId | null | undefined };
type Refusal = {
readonly outcome: "limit" | "not_allowed";
@@ -748,6 +748,7 @@ export const makeConnectToolHandlers = (
projectId: project.id,
name: project.title,
folder: assistant ? lastPathSegment(project.workspaceRoot) : project.workspaceRoot,
+ ...(project.leadThreadId != null ? { leadThreadId: project.leadThreadId } : {}),
})),
} satisfies ProjectsResult;
});
diff --git a/apps/server/src/outsideAgents/connectTools.ts b/apps/server/src/outsideAgents/connectTools.ts
index 8bfb9599e..d8971b457 100644
--- a/apps/server/src/outsideAgents/connectTools.ts
+++ b/apps/server/src/outsideAgents/connectTools.ts
@@ -129,7 +129,13 @@ export const ProjectsResult = Schema.Struct({
detail: Detail,
retryAfterSeconds: RetryAfter,
projects: Schema.Array(
- Schema.Struct({ projectId: Schema.String, name: Schema.String, folder: Schema.String }),
+ Schema.Struct({
+ projectId: Schema.String,
+ name: Schema.String,
+ folder: Schema.String,
+ /** The project's lead chat: send work for the project there. Absent: none. */
+ leadThreadId: Schema.optional(Schema.String),
+ }),
),
});
export type ProjectsResult = typeof ProjectsResult.Type;
diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json
index e815b4b96..35d4964cf 100644
--- a/apps/server/src/provider/agentContextBudget.json
+++ b/apps/server/src/provider/agentContextBudget.json
@@ -16,5 +16,5 @@
"show_page"
],
"upFrontToolDefinitionBytes": 16834,
- "onDemandToolDefinitionBytes": 48382
+ "onDemandToolDefinitionBytes": 48765
}
diff --git a/apps/server/src/pullRequest/PullRequestObservations.ts b/apps/server/src/pullRequest/PullRequestObservations.ts
index c0d180c8f..b34542d40 100644
--- a/apps/server/src/pullRequest/PullRequestObservations.ts
+++ b/apps/server/src/pullRequest/PullRequestObservations.ts
@@ -167,6 +167,16 @@ export interface PullRequestObservationsShape {
) => Effect.Effect, E, R>;
/** Every record kept, oldest change first, then each change as it lands. */
readonly stream: Stream.Stream;
+ /**
+ * What is already known about a thread's pull requests, with no call to the
+ * host: the one from its branch in `repository` (`owner/name`), and the ones
+ * at `urls`. Pull requests nobody has read yet are left out.
+ */
+ readonly known: (input: {
+ readonly repository: string | null;
+ readonly branch: string | null;
+ readonly urls: ReadonlyArray;
+ }) => Effect.Effect>;
}
export class PullRequestObservations extends Context.Service<
@@ -239,7 +249,23 @@ export const make = Effect.gen(function* () {
}),
);
- return { observe, stream } satisfies PullRequestObservationsShape;
+ const known: PullRequestObservationsShape["known"] = (input) =>
+ Ref.get(state).pipe(
+ Effect.map((current) => {
+ const repository = input.repository?.toLowerCase() ?? null;
+ const urls = new Set(input.urls);
+ return Array.from(current.records.values(), (entry) => entry.observation).filter(
+ (observation) =>
+ urls.has(observation.url) ||
+ (repository !== null &&
+ input.branch !== null &&
+ observation.repository.toLowerCase() === repository &&
+ observation.headBranch === input.branch),
+ );
+ }),
+ );
+
+ return { observe, stream, known } satisfies PullRequestObservationsShape;
});
export const layer = Layer.effect(PullRequestObservations, make);
diff --git a/apps/server/src/threads/threadOperations.ts b/apps/server/src/threads/threadOperations.ts
index ed07e175a..84e6ec42c 100644
--- a/apps/server/src/threads/threadOperations.ts
+++ b/apps/server/src/threads/threadOperations.ts
@@ -277,6 +277,10 @@ export const summarizeThread = (
readonly titleOf: (threadId: ThreadId) => string | undefined;
/** Threads a scheduled-task card waits in (ScheduledTasks.waitingThreadIds). */
readonly scheduleAnswerWaiting?: ReadonlySet;
+ /** The project's lead chat, when it has one (docs/design/lead-chat.md). */
+ readonly leadThreadId?: ThreadId | null;
+ /** Its pull requests as already known; see AgentThreadSummary.pullRequests. */
+ readonly pullRequests?: ThreadSummary["pullRequests"];
},
): ThreadSummary => {
const remoteOrigin = thread.remoteOrigin ?? null;
@@ -301,6 +305,12 @@ export const summarizeThread = (
? "you"
: (input.titleOf(thread.parentThreadId) ?? thread.parentThreadId),
...(input.caller !== undefined && thread.id === input.caller.id ? { you: true } : {}),
+ ...((input.leadThreadId ?? null) === thread.id ? { lead: true } : {}),
+ lastActivityAt:
+ thread.latestTurn?.completedAt ?? thread.latestTurn?.startedAt ?? thread.updatedAt,
+ ...(input.pullRequests !== undefined && input.pullRequests.length > 0
+ ? { pullRequests: input.pullRequests }
+ : {}),
};
};
diff --git a/apps/web/src/components/ChatView.agents.browser.tsx b/apps/web/src/components/ChatView.agents.browser.tsx
index 768125632..064561ff0 100644
--- a/apps/web/src/components/ChatView.agents.browser.tsx
+++ b/apps/web/src/components/ChatView.agents.browser.tsx
@@ -1120,6 +1120,9 @@ describe("ChatView (full app): agent browser tabs and rooms", () => {
);
expect(neverMadeReport?.querySelector("button[data-thread-message-author]")).toBeNull();
+ // This server can't take a partial answer: no checkboxes, and Start
+ // answers for the whole batch.
+ expect(panel.querySelector('[data-slot="checkbox"]')).toBeNull();
[...panel.querySelectorAll("button")]
.find((button) => button.textContent === "Start")
?.click();
@@ -1134,6 +1137,106 @@ describe("ChatView (full app): agent browser tabs and rooms", () => {
).toMatchObject({ batchId, choice: "start" }),
{ timeout: 8_000, interval: 16 },
);
+ const respond = wsRequests.find(
+ (request) =>
+ request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
+ (request as { type?: string }).type === "thread.child-request.respond",
+ ) as { requestIds?: unknown } | undefined;
+ expect(respond?.requestIds).toBeUndefined();
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
+ it("starts only the threads left checked, where the server takes a partial answer", async () => {
+ const base = createSnapshotForTargetUser({
+ targetMessageId: "msg-user-child-select" as MessageId,
+ targetText: "child select target",
+ });
+ const batchId = ChildRequestBatchId.make("batch-select");
+ const capabilities = { repositoryIdentity: true, childStartSelection: true };
+ const ask = (index: number, title: string) => ({
+ requestId: ChildRequestId.make(`request-select-${index}`),
+ batchId,
+ kind: "start" as const,
+ from: { participantId: null },
+ callerTurnId: "turn-select" as TurnId,
+ deliveryEpoch: 0,
+ status: "awaiting_user" as const,
+ childThreadId: `thread-child-select-${index}` as ThreadId,
+ childMessageId: `msg-child-select-${index}` as MessageId,
+ launch: {
+ title,
+ prompt: `${title}.`,
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
+ runtimeMode: "full-access" as const,
+ interactionMode: "default" as const,
+ reportBack: true,
+ runSetup: true,
+ workspace: { kind: "project_folder" as const },
+ },
+ createdAt: isoAt(301),
+ });
+ const mounted = await mountChatView({
+ viewport: DEFAULT_VIEWPORT,
+ configureFixture: (nextFixture) => {
+ nextFixture.serverConfig = {
+ ...nextFixture.serverConfig,
+ environment: { ...nextFixture.serverConfig.environment, capabilities },
+ };
+ nextFixture.welcome = {
+ ...nextFixture.welcome,
+ environment: { ...nextFixture.welcome.environment, capabilities },
+ };
+ },
+ snapshot: {
+ ...base,
+ threads: base.threads.map((thread) =>
+ thread.id === THREAD_ID
+ ? {
+ ...thread,
+ childRequests: {
+ ...EMPTY_CHILD_REQUEST_STATE,
+ startsSinceUser: 3,
+ open: [
+ ask(1, "Fix the flaky test"),
+ ask(2, "Update the docs"),
+ ask(3, "Bump the version"),
+ ],
+ },
+ }
+ : thread,
+ ),
+ },
+ });
+ try {
+ const panel = await waitForElement(
+ () => document.querySelector('[data-testid="child-threads-panel"]'),
+ "Unable to find the approval card.",
+ );
+ const startButton = () =>
+ [...panel.querySelectorAll("button")].find((button) =>
+ button.textContent?.startsWith("Start"),
+ );
+ expect(startButton()?.textContent).toBe("Start all");
+ await page.getByRole("checkbox", { name: "Start Update the docs" }).click();
+ await vi.waitFor(() => expect(startButton()?.textContent).toBe("Start 2"));
+ startButton()?.click();
+ await vi.waitFor(
+ () =>
+ expect(
+ wsRequests.find(
+ (request) =>
+ request._tag === ORCHESTRATION_WS_METHODS.dispatchCommand &&
+ (request as { type?: string }).type === "thread.child-request.respond",
+ ),
+ ).toMatchObject({
+ batchId,
+ choice: "start",
+ requestIds: ["request-select-1", "request-select-3"],
+ }),
+ { timeout: 8_000, interval: 16 },
+ );
} finally {
await mounted.cleanup();
}
diff --git a/apps/web/src/components/chat/ComposerChildThreadsPanel.tsx b/apps/web/src/components/chat/ComposerChildThreadsPanel.tsx
index 9a35406f1..d33ce207c 100644
--- a/apps/web/src/components/chat/ComposerChildThreadsPanel.tsx
+++ b/apps/web/src/components/chat/ComposerChildThreadsPanel.tsx
@@ -6,7 +6,9 @@ import type { PendingChildThreads } from "~/childThreads";
import { readEnvironmentApi } from "~/environmentApi";
import { cn, newCommandId } from "~/lib/utils";
import { formatChildThreadCount } from "../Sidebar.logic";
+import { readEnvironmentDescriptor } from "~/environments/runtime";
import { Button } from "../ui/button";
+import { Checkbox } from "../ui/checkbox";
import { failureNotice, toastManager } from "../ui/toast";
import { addComputerNotConnectedNotice } from "../computerConnectionNotices";
import { ProviderInstanceIcon } from "./ProviderInstanceIcon";
@@ -44,6 +46,17 @@ export const ComposerChildThreadsPanel = memo(function ComposerChildThreadsPanel
const { request } = props;
const [responding, setResponding] = useState(false);
const [showPrompts, setShowPrompts] = useState(false);
+ // Several threads: each can be left out, where the thread's server can
+ // take a partial answer (an older one would start the whole batch).
+ const selectable =
+ request.threads.length > 1 &&
+ readEnvironmentDescriptor(props.threadRef.environmentId)?.capabilities.childStartSelection ===
+ true;
+ const [unchecked, setUnchecked] = useState>(() => new Set());
+ const checkedIds = request.threads
+ .map((thread) => thread.requestId)
+ .filter((requestId) => !unchecked.has(requestId));
+ const allChecked = checkedIds.length === request.threads.length;
const respond = async (choice: "start" | "decline") => {
const api = readEnvironmentApi(props.threadRef.environmentId);
@@ -62,6 +75,7 @@ export const ComposerChildThreadsPanel = memo(function ComposerChildThreadsPanel
threadId: props.threadRef.threadId,
batchId: request.batchId,
choice,
+ ...(choice === "start" && selectable && !allChecked ? { requestIds: checkedIds } : {}),
createdAt: new Date().toISOString(),
});
} catch (error) {
@@ -98,7 +112,31 @@ export const ComposerChildThreadsPanel = memo(function ComposerChildThreadsPanel
)}
data-testid="child-threads-panel-thread"
>
- {thread.title}
+ {selectable ? (
+ {
+ setUnchecked((current) => {
+ const updated = new Set(current);
+ if (next) updated.delete(thread.requestId);
+ else updated.add(thread.requestId);
+ return updated;
+ });
+ }}
+ />
+ ) : null}
+
+ {thread.title}
+ void respond("start")}
>
- Start
+ {!selectable ? "Start" : allChecked ? "Start all" : `Start ${checkedIds.length}`}
diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts
index 3d1332034..9575d424a 100644
--- a/apps/web/src/store.ts
+++ b/apps/web/src/store.ts
@@ -3671,7 +3671,14 @@ function applyEnvironmentOrchestrationEvent(
);
case "thread.child-requests-reset":
- return updateChildRequestState(state, event.payload.threadId, childRequestStateOn.reset);
+ return updateChildRequestState(state, event.payload.threadId, (current) =>
+ childRequestStateOn.reset(current, event.payload),
+ );
+
+ case "thread.lead-pass-recorded":
+ return updateChildRequestState(state, event.payload.threadId, (current) =>
+ childRequestStateOn.leadPass(current, event.payload),
+ );
// Agents' settings changes (docs/design/agent-settings-changes.md),
// folded through the reducer the server's projector uses.
diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md
index eceb837ba..ff20ca45d 100644
--- a/docs/design/lead-chat.md
+++ b/docs/design/lead-chat.md
@@ -304,6 +304,16 @@ the user. Your reply stays in this thread, where the user reads it."
cleared by `thread.child-requests-reset` (the user wrote). `childStartRefusal` reads
it; `childSendRefusal` does not (both call `callerRefusal`, so the rule cannot live
there).
+- Built (piece 2): the lead's send count, the refusal note and the "started" mark ride
+ one event, `thread.lead-pass-recorded` (`kind`: `sent` on the lead, `refused` with
+ the note on the lead, `started` on the target), so nothing settles a request that
+ does not exist. The note goes to the lead's agent that passed it
+ (`fromThread.passedBy` in a room). The block lifts only when a person writes
+ (`composer` or `sentFrom` on the turn or the queued message); a continue, a restart,
+ a scheduled run or an automatic fix reset the counts with `keepsPassBlock`. A target
+ whose last turn failed is refused like a stopped one, since its queue is held the
+ same way. Retry never picks a message still waiting in the queue, and the queue
+ moves on when the decider takes a message back instead of starting its turn.
- A pass does not stamp `handed-back` and emits no `child-request-settled`, so the
target's wrap rules and "done" alert are untouched (the alert rule cancels on every
`child-request-settled`, pushAlertRules.ts).
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index 1c0391afe..f1000c16f 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -193,6 +193,12 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
* would refuse the command, so clients hide the lead actions for them.
*/
projectLead: Schema.optionalKey(Schema.Boolean),
+ /**
+ * The approval card for starting several threads can start some of them
+ * (`thread.child-request.respond` `requestIds`). An older server would start
+ * the whole batch, so clients only show the checkboxes for this one.
+ */
+ childStartSelection: Schema.optionalKey(Schema.Boolean),
});
export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type;
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index ab320fa12..255d40261 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -465,6 +465,8 @@ export const OrchestrationProjectCatalogEntry = Schema.Struct({
kind: ProjectKind.pipe(Schema.withDecodingDefault(Effect.succeed(DEFAULT_PROJECT_KIND))),
title: TrimmedNonEmptyString,
workspaceRoot: TrimmedNonEmptyString,
+ /** The project's lead chat, when it has an open one (docs/design/lead-chat.md). */
+ leadThreadId: Schema.optional(ThreadId),
createdAt: IsoDateTime,
updatedAt: IsoDateTime,
deletedAt: Schema.NullOr(IsoDateTime),
@@ -635,6 +637,22 @@ export const ThreadMessageOrigin = Schema.Struct({
* With no child to check, only Stop or a wrap (the delivery epoch) cancels it.
*/
neverMade: Schema.optional(Schema.Boolean),
+ /**
+ * A pass (docs/design/lead-chat.md): the project's lead chat passed this
+ * message into a thread it did not start. The lead's access and interaction
+ * mode when it passed it, kept on the message for good: every decision that
+ * starts a turn from it refuses when the thread has more access by then.
+ * Nothing is owed back for a pass: no request is recorded on the lead.
+ * Only a pass carries it.
+ */
+ ceiling: Schema.optional(
+ Schema.Struct({
+ runtimeMode: RuntimeMode,
+ interactionMode: ProviderInteractionMode,
+ }),
+ ),
+ /** A pass: the lead's agent that passed it (a room's agent), for its notes. Absent: its own. */
+ passedBy: Schema.optional(ThreadParticipantId),
});
export type ThreadMessageOrigin = typeof ThreadMessageOrigin.Type;
@@ -1248,6 +1266,13 @@ export type ThreadCheckoutSwitchDeferredPayload = typeof ThreadCheckoutSwitchDef
* turn is refused (CheckpointRevert).
*/
export const ThreadCheckoutMovedActivityKind = "thread.checkout.moved";
+
+/**
+ * A lead chat's pass that never ran here: its turn would have started with
+ * more access than the lead had when it passed it (docs/design/lead-chat.md,
+ * "Access"). Payload `{ messageId }`; the summary is the line the chat shows.
+ */
+export const LEAD_PASS_NOT_RUN_ACTIVITY_KIND = "lead-chat.pass-not-run";
export const ThreadCheckoutMovedPayload = Schema.Struct({
/** The thread whose checkout it moved into, with its title then. */
ownerThreadId: ThreadId,
@@ -2636,6 +2661,12 @@ export const OrchestrationChildRequestState = Schema.Struct({
remoteChildren: Schema.optional(Schema.Array(RemoteChildThread)),
/** Cancels still owed to linked computers, oldest first. Absent: none. */
remoteCancels: Schema.optional(Schema.Array(RemoteChildCancel)),
+ /**
+ * A message the lead chat passed on started a turn here since the user
+ * last wrote (docs/design/lead-chat.md, "No fan-out"): this thread's agents
+ * can't start threads until the user writes here. Absent: they can.
+ */
+ startsBlockedByPass: Schema.optional(Schema.Literal(true)),
});
export type OrchestrationChildRequestState = typeof OrchestrationChildRequestState.Type;
@@ -3971,6 +4002,12 @@ const ThreadChildRequestRespondCommand = Schema.Struct({
threadId: ThreadId,
batchId: ChildRequestBatchId,
choice: Schema.Literals(["start", "decline"]),
+ /**
+ * With `start`: only these of the batch start, and the rest are declined in
+ * the same answer (capability `childStartSelection`). Absent: the whole
+ * batch.
+ */
+ requestIds: Schema.optional(Schema.Array(ChildRequestId)),
createdAt: IsoDateTime,
});
@@ -4864,6 +4901,26 @@ const ThreadChildSendCommand = Schema.Struct({
createdAt: IsoDateTime,
});
+/**
+ * The project's lead chat passes a message into a thread it did not start
+ * (docs/design/lead-chat.md, "A pass"). Server only, from `thread_send`.
+ * One-way: the message lands in `targetThreadId` as the lead's, and nothing
+ * is recorded on the lead but its send count. `requestId` names the pass
+ * (`fromThread.requestId` on the message); `ceiling` is the lead's access.
+ */
+const ThreadLeadPassCommand = Schema.Struct({
+ type: Schema.Literal("thread.lead.pass"),
+ commandId: CommandId,
+ threadId: ThreadId,
+ from: RoomAgentRef,
+ callerTurnId: TurnId,
+ targetThreadId: ThreadId,
+ requestId: ChildRequestId,
+ messageId: MessageId,
+ text: TrimmedNonEmptyString,
+ createdAt: IsoDateTime,
+});
+
/** Child threads: a request moved on (set up, its turn started, background wait). */
const ThreadChildRequestUpdateCommand = Schema.Struct({
type: Schema.Literal("thread.child-request.update"),
@@ -5270,6 +5327,7 @@ const InternalOrchestrationCommand = Schema.Union([
ThreadNativeSessionFallBackCommand,
ThreadChildStartCommand,
ThreadChildSendCommand,
+ ThreadLeadPassCommand,
ThreadChildRequestUpdateCommand,
ThreadChildRequestSettleCommand,
ThreadChildNotesDeliveredCommand,
@@ -5365,6 +5423,7 @@ export const OrchestrationEventType = Schema.Literals([
"thread.child-notes-delivered",
"thread.child-deliveries-cancelled",
"thread.child-requests-reset",
+ "thread.lead-pass-recorded",
"thread.remote-child-updated",
"thread.remote-cancel-queued",
"thread.remote-cancels-delivered",
@@ -5828,6 +5887,29 @@ export const ThreadChildDeliveriesCancelledPayload = Schema.Struct({
/** The user wrote: the per-message child thread counts start over. */
export const ThreadChildRequestsResetPayload = Schema.Struct({
threadId: ThreadId,
+ /**
+ * A turn Threadlines started for the user (a continue at the reset, after a
+ * restart or an account switch), not the user writing: the counts start
+ * over, but a pass's block on starting threads stays.
+ */
+ keepsPassBlock: Schema.optional(Schema.Literal(true)),
+ createdAt: IsoDateTime,
+});
+
+/**
+ * The lead chat's passes (docs/design/lead-chat.md, "A pass"). On the lead:
+ * `sent` counts one toward its sends since the user wrote; `refused` (the
+ * passed message could not run, its ceiling was over) leaves `note` for the
+ * lead's next turn. On the thread passed to: `started` (the pass started its
+ * turn there) blocks its agents from starting threads until the user writes.
+ */
+export const ThreadLeadPassRecordedPayload = Schema.Struct({
+ threadId: ThreadId,
+ kind: Schema.Literals(["sent", "refused", "started"]),
+ /** The pass's message, in the thread it was passed to. */
+ messageId: MessageId,
+ targetThreadId: ThreadId,
+ note: Schema.optional(ChildRequestNote),
createdAt: IsoDateTime,
});
@@ -6493,6 +6575,11 @@ export const OrchestrationEvent = Schema.Union([
type: Schema.Literal("thread.child-requests-reset"),
payload: ThreadChildRequestsResetPayload,
}),
+ Schema.Struct({
+ ...EventBaseFields,
+ type: Schema.Literal("thread.lead-pass-recorded"),
+ payload: ThreadLeadPassRecordedPayload,
+ }),
Schema.Struct({
...EventBaseFields,
type: Schema.Literal("thread.remote-child-updated"),
diff --git a/packages/contracts/src/peerRpc.ts b/packages/contracts/src/peerRpc.ts
index 5e1687c2a..cee087905 100644
--- a/packages/contracts/src/peerRpc.ts
+++ b/packages/contracts/src/peerRpc.ts
@@ -62,6 +62,23 @@ export const AgentThreadSummary = Schema.Struct({
you: Schema.optional(Schema.Boolean),
/** The linked computer it runs on; absent: this one. */
computer: Schema.optional(Schema.String),
+ /** Its project's lead chat (docs/design/lead-chat.md). */
+ lead: Schema.optional(Schema.Boolean),
+ /** When its work last moved: its latest turn, else its last change. */
+ lastActivityAt: Schema.optional(Schema.String),
+ /**
+ * Its pull requests, as this computer already knows them (no call to the
+ * host): `state` where a read has said.
+ */
+ pullRequests: Schema.optional(
+ Schema.Array(
+ Schema.Struct({
+ number: Schema.Number,
+ url: Schema.String,
+ state: Schema.optional(Schema.Literals(["open", "merged", "closed"])),
+ }),
+ ),
+ ),
});
export type AgentThreadSummary = typeof AgentThreadSummary.Type;
diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts
index f8d508f03..14bb1a8a5 100644
--- a/packages/shared/src/childThreads.ts
+++ b/packages/shared/src/childThreads.ts
@@ -23,11 +23,16 @@ import {
type RemoteThreadFiling,
type RoomAgentRef,
type LocalChildStart,
+ type ProviderInteractionMode,
+ type RuntimeMode,
type ThreadId,
type ThreadParticipantId,
type TurnId,
} from "@threadlines/contracts";
+import { exceedsRuntimeMode } from "./runtimeMode.ts";
+import { isRoomThread } from "./threadParticipants.ts";
+
/** What the rules read from a thread an agent works in. */
export interface ChildRequestCaller {
readonly id: ThreadId;
@@ -127,6 +132,16 @@ export function childStartRefusal(
if (caller !== null) {
return caller;
}
+ // No fan-out (docs/design/lead-chat.md): one message in a lead chat must
+ // not start threads through every thread it is passed to. Messaging this
+ // thread's own children still works (childSendRefusal doesn't check it).
+ if (thread.childRequests.startsBlockedByPass === true) {
+ return {
+ outcome: "not_allowed",
+ detail:
+ "This thread is working on something the lead chat passed on. Do the work here, or say what should be started.",
+ };
+ }
if (input.count < 1 || input.count > CHILD_THREADS_PER_CALL) {
return {
outcome: "refused",
@@ -244,6 +259,133 @@ export function childAttachRefusal(
return null;
}
+/** Whether `child` asks for no more than `ceiling` allows. Plan is narrower than default. */
+export function withinModeCeiling(
+ child: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },
+ ceiling: { readonly runtimeMode: RuntimeMode; readonly interactionMode: ProviderInteractionMode },
+): boolean {
+ return (
+ !exceedsRuntimeMode(child.runtimeMode, ceiling.runtimeMode) &&
+ (ceiling.interactionMode !== "plan" || child.interactionMode === "plan")
+ );
+}
+
+/** What the pass rules read from the thread a lead chat passes a message to. */
+export interface LeadPassTarget {
+ readonly id: ThreadId;
+ readonly projectId: string;
+ readonly parentThreadId: ThreadId | null;
+ readonly attachedToParent: boolean;
+ readonly archivedAt: string | null;
+ readonly deletedAt?: string | null | undefined;
+ readonly participants: Parameters[0]["participants"];
+ readonly remoteOrigin?: unknown;
+ readonly outsideOrigin?: unknown;
+ readonly move?: unknown;
+ readonly pendingMove?: unknown;
+ readonly agentRequests: { readonly hold: boolean };
+ readonly latestTurn: { readonly state: string } | null;
+}
+
+/**
+ * Why the project's lead chat may not pass a message to `target`, a thread it
+ * did not start (docs/design/lead-chat.md, "Tools"), or null. The caller has
+ * already sent a thread it started down the child path. `isLead` is whether
+ * the caller is its project's lead chat now.
+ */
+export function leadPassRefusal(
+ lead: ChildRequestCaller & { readonly projectId: string },
+ target: LeadPassTarget | null,
+ input: {
+ readonly from: RoomAgentRef;
+ readonly callerTurnId: TurnId;
+ readonly isLead: boolean;
+ },
+): ChildRequestRefusal | null {
+ const caller = callerRefusal(lead, input);
+ if (caller !== null) {
+ return caller;
+ }
+ if (!input.isLead) {
+ return {
+ outcome: "not_allowed",
+ detail: "That is not a thread you started. You can only message or stop your own threads.",
+ };
+ }
+ if (target === null || (target.deletedAt ?? null) !== null) {
+ return { outcome: "refused", detail: "That thread is gone." };
+ }
+ if (target.id === lead.id) {
+ return { outcome: "refused", detail: "That is this thread." };
+ }
+ if (target.projectId !== lead.projectId) {
+ return { outcome: "refused", detail: "That thread is in another project." };
+ }
+ if (target.archivedAt !== null) {
+ return { outcome: "refused", detail: "That thread is archived." };
+ }
+ if (isAttachedChild(target)) {
+ return {
+ outcome: "not_allowed",
+ detail:
+ "Another thread started that one and still owns it. Message the thread that started it.",
+ };
+ }
+ if (isRoomThread(target)) {
+ return { outcome: "not_allowed", detail: "Rooms take work from the user." };
+ }
+ if ((target.remoteOrigin ?? null) !== null || (target.outsideOrigin ?? null) !== null) {
+ return {
+ outcome: "not_allowed",
+ detail: "That thread was started from another computer or by an outside agent.",
+ };
+ }
+ if ((target.move ?? null) !== null || (target.pendingMove ?? null) !== null) {
+ return { outcome: "refused", detail: "That thread is moving to another computer." };
+ }
+ // What it was last told to stop doing, or failed at, holds its queue until
+ // the user writes there: a pass would sit there unseen.
+ if (target.agentRequests.hold || target.latestTurn?.state === "interrupted") {
+ return {
+ outcome: "refused",
+ detail: "The user stopped that thread. It takes work again once they write there.",
+ };
+ }
+ if (target.latestTurn?.state === "error") {
+ return {
+ outcome: "refused",
+ detail: "That thread's last turn failed. It takes work again once the user writes there.",
+ };
+ }
+ const limit = childRequestLimits({ isLead: true }).sends;
+ if (lead.childRequests.sendsSinceUser >= limit) {
+ return {
+ outcome: "limit",
+ detail: `The lead chat can send ${limit} messages to threads per user message, and that many were sent since the user last wrote, so this one was not. Say so in your reply, and wait for the user before sending more.`,
+ };
+ }
+ return null;
+}
+
+/**
+ * Why a stored message can't start a turn in `thread` now: it is a pass whose
+ * ceiling is under the thread's access at this moment. Every decision that
+ * starts a turn from a stored message asks (send-queued, retry, resend).
+ */
+export function passCeilingRefusal(
+ message: {
+ readonly fromThread?:
+ | { readonly ceiling?: Parameters[1] | undefined }
+ | undefined;
+ },
+ thread: Parameters[0],
+): string | null {
+ const ceiling = message.fromThread?.ceiling;
+ return ceiling === undefined || withinModeCeiling(thread, ceiling)
+ ? null
+ : "Not run: this thread has more access than the lead chat.";
+}
+
/** Requests whose answers are still owed, as the parent's sidebar row counts them. */
export const awaitedChildRequestCount = (state: OrchestrationChildRequestState): number =>
state.open.filter((request) => request.status !== "awaiting_user").length;
@@ -536,10 +678,51 @@ export const childRequestStateOn = {
deliveryEpoch: number,
): OrchestrationChildRequestState =>
state.deliveryEpoch === deliveryEpoch ? state : { ...state, deliveryEpoch },
- reset: (state: OrchestrationChildRequestState): OrchestrationChildRequestState =>
- state.startsSinceUser === 0 && state.sendsSinceUser === 0
- ? state
- : { ...state, startsSinceUser: 0, sendsSinceUser: 0 },
+ /**
+ * The user wrote (or, with `keepsPassBlock`, Threadlines started a turn for
+ * them): the per-message counts start over, and unless kept, a pass's
+ * block on starting threads lifts.
+ */
+ reset: (
+ state: OrchestrationChildRequestState,
+ options?: { readonly keepsPassBlock?: boolean | undefined },
+ ): OrchestrationChildRequestState => {
+ const liftsBlock = state.startsBlockedByPass === true && options?.keepsPassBlock !== true;
+ if (state.startsSinceUser === 0 && state.sendsSinceUser === 0 && !liftsBlock) {
+ return state;
+ }
+ const { startsBlockedByPass: _block, ...rest } = state;
+ return {
+ ...(liftsBlock ? rest : state),
+ startsSinceUser: 0,
+ sendsSinceUser: 0,
+ };
+ },
+ /** The lead chat's passes (`thread.lead-pass-recorded`); see its payload. */
+ leadPass: (
+ state: OrchestrationChildRequestState,
+ pass: {
+ readonly kind: "sent" | "refused" | "started";
+ readonly note?: ChildRequestNote | undefined;
+ },
+ ): OrchestrationChildRequestState => {
+ switch (pass.kind) {
+ case "sent":
+ return { ...state, sendsSinceUser: state.sendsSinceUser + 1 };
+ case "started":
+ return state.startsBlockedByPass === true ? state : { ...state, startsBlockedByPass: true };
+ case "refused": {
+ const note = pass.note;
+ return note === undefined ||
+ state.pendingNotes.some((entry) => entry.requestId === note.requestId)
+ ? state
+ : {
+ ...state,
+ pendingNotes: [...state.pendingNotes, note].slice(-CHILD_REQUEST_NOTE_LIMIT),
+ };
+ }
+ }
+ },
};
/**
diff --git a/packages/shared/src/projectLead.ts b/packages/shared/src/projectLead.ts
index bcd2ab5bf..3e902bc39 100644
--- a/packages/shared/src/projectLead.ts
+++ b/packages/shared/src/projectLead.ts
@@ -87,9 +87,9 @@ export function leadRoleText(projectTitle: string): string {
return [
`This thread is the lead chat for the project "${projectTitle}". The user drops work here and you coordinate it.`,
"- Answer quick questions yourself. Do not change files in this thread.",
- '- For work, call thread_list with scope "project" first. If a thread you started already works in that area, send it the message with thread_send. Otherwise start one thread per independent task with thread_start, each with a brief that stands on its own.',
+ '- For work, call thread_list with scope "project" first. If an open thread already works in that area, pass the message on with thread_send. Otherwise start one thread per independent task with thread_start, each with a brief that stands on its own.',
"- Say in a line or two what went where. When a report comes back, tell the user what finished and what needs them. Do not repeat the report.",
- "- Threads you started report back by themselves. Do not poll them.",
+ "- Threads you started report back by themselves. Do not poll them. A thread you did not start does not report back: the user sees its answer there.",
].join("\n");
}
From 2dd30607f7bb1d5038ea8a88fa60b9449bce7029 Mon Sep 17 00:00:00 2001
From: Badcuban <108198679+badcuban@users.noreply.github.com>
Date: Mon, 16 Nov 2026 15:39:13 -0500
Subject: [PATCH 04/11] feat(web): a Threads panel groups a project's threads
by what needs you
A lead chat hands work to many threads, and there was no single place to see
how they were all doing: the sidebar shows families, not the whole project.
A new right-panel tab, Threads ("This project's threads."), on every thread of
a workspace project. It lists the project's threads on every computer in view
in six groups: Needs you, Ready for review, Working, Landing, Idle, and Done
(wrapped in the last 7 days, closed by default). Filing comes first, from the
sidebar's own InboxEntry.isDone, except that a wrapped thread whose pull
request is still open stays under Ready for review or Landing. Ready for
review rows say what the pull request waits on, with the Pull requests page's
own wording. Groups over 8 fold behind "Show N more". Rows are one line like
the sidebar's child rows; a click opens the thread with the tab still beside
it, and right-click is the sidebar's thread menu. The header counts what needs
you and links to the lead chat from other threads.
- projectBoard.logic.ts holds the pure grouping; the status-to-group table now
lives in threadStatusGroups.ts, read by it and by the new-thread map.
- The first time a thread becomes a lead on this device, its Threads tab
opens: setProjectLead queues the tab and the thread route opens it.
- The badge's click handler moved to useOpenThreadPullRequest so the sidebar
and the panel share it.
- App guide: the lead-chat topic describes the panel.
---
apps/server/src/guide/topics.ts | 14 +-
.../components/ChatView.panels.browser.tsx | 98 +++++
apps/web/src/components/Sidebar.tsx | 44 +-
.../src/components/chat/ProjectBoardPanel.tsx | 398 ++++++++++++++++++
.../components/chat/ProjectThreadMap.logic.ts | 44 +-
.../components/chat/RightPanelTabStrip.tsx | 2 +
.../chat/projectBoard.logic.test.ts | 168 ++++++++
.../src/components/chat/projectBoard.logic.ts | 211 ++++++++++
.../src/components/chat/threadStatusGroups.ts | 46 ++
.../pull-requests/pullRequests.logic.ts | 18 +
apps/web/src/components/sidebar/InboxRows.tsx | 4 +-
apps/web/src/diffRouteSearch.test.ts | 1 +
apps/web/src/diffRouteSearch.ts | 20 +-
.../web/src/hooks/useOpenThreadPullRequest.ts | 56 +++
apps/web/src/leadChat.ts | 23 +-
apps/web/src/rightPanelTabs.test.ts | 19 +-
apps/web/src/rightPanelTabs.ts | 60 ++-
.../routes/_chat.$environmentId.$threadId.tsx | 59 ++-
18 files changed, 1194 insertions(+), 91 deletions(-)
create mode 100644 apps/web/src/components/chat/ProjectBoardPanel.tsx
create mode 100644 apps/web/src/components/chat/projectBoard.logic.test.ts
create mode 100644 apps/web/src/components/chat/projectBoard.logic.ts
create mode 100644 apps/web/src/components/chat/threadStatusGroups.ts
create mode 100644 apps/web/src/hooks/useOpenThreadPullRequest.ts
diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts
index 5f60e740c..fc95325ef 100644
--- a/apps/server/src/guide/topics.ts
+++ b/apps/server/src/guide/topics.ts
@@ -107,7 +107,17 @@ A project's lead chat is a thread set up to coordinate the project; see the lead
{
id: "lead-chat",
title: "Lead chat",
- keywords: ["lead chat", "lead", "coordinator", "project lead", "orchestrator", "drop work"],
+ keywords: [
+ "lead chat",
+ "lead",
+ "coordinator",
+ "project lead",
+ "orchestrator",
+ "drop work",
+ "threads panel",
+ "project threads",
+ "board",
+ ],
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.
@@ -120,6 +130,8 @@ Only one thread leads a project; making another the lead replaces it. "Stop usin
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 Threads tab in the right sidebar shows the project's threads on every computer you can see, grouped as Needs you, Ready for review, Working, Landing, Idle and Done. Open it from the sidebar's list of panels or its + menu, on any thread of the project; it opens by itself the first time a thread becomes the lead on this device. A thread you wrapped up goes under Done (for 7 days, closed until you open it) unless its pull request is still open, which keeps it under Ready for review or Landing. Ready for review says what the pull request waits on, as the Pull requests page does. Click a row to open the thread, or right-click it for the thread's menu. The top line counts what needs you and what's working, with a Lead chat link when you're on another thread.
+
The lead's agent is told its role at the start of every turn. It may start 10 threads and send 20 messages to them per message you send, instead of 5 and 10. It needs {place:threads.agentThreads} to be on, and an agent that can't use the thread tools says so. General chats, a thread another thread still owns, and threads from another computer or an outside agent can't be the lead.`,
},
{
diff --git a/apps/web/src/components/ChatView.panels.browser.tsx b/apps/web/src/components/ChatView.panels.browser.tsx
index 1ad441667..e259162c8 100644
--- a/apps/web/src/components/ChatView.panels.browser.tsx
+++ b/apps/web/src/components/ChatView.panels.browser.tsx
@@ -40,6 +40,9 @@ import {
waitForLayout,
waitForElement,
waitForServerConfigToApply,
+ addThreadToSnapshot,
+ markThreadDoneInTest,
+ setSidebarThreadWork,
mountChatView,
openProjectMenu,
registerChatViewSuiteHooks,
@@ -207,6 +210,101 @@ describe("ChatView (full app): right panel and header actions", () => {
tile.click();
}
+ it("groups the project's threads in the Threads tab and opens one from its row", async () => {
+ const approvalId = "thread-board-approval" as ThreadId;
+ const workingId = "thread-board-working" as ThreadId;
+ const wrappedId = "thread-board-wrapped" as ThreadId;
+ const titles: Record = {
+ [approvalId]: "Needs an approval",
+ [workingId]: "Busy fixing",
+ [wrappedId]: "Finished last night",
+ };
+ const base = createSnapshotForTargetUser({
+ targetMessageId: "msg-user-board" as MessageId,
+ targetText: "board",
+ });
+ const snapshot = [approvalId, workingId, wrappedId].reduce(
+ (current, threadId) => addThreadToSnapshot(current, threadId),
+ base,
+ );
+ const mounted = await mountChatView({
+ viewport: WIDE_FOOTER_VIEWPORT,
+ snapshot: {
+ ...snapshot,
+ threads: snapshot.threads.map((thread) =>
+ titles[thread.id] ? { ...thread, title: titles[thread.id]! } : thread,
+ ),
+ },
+ });
+
+ try {
+ setSidebarThreadWork(LOCAL_ENVIRONMENT_ID, approvalId, "needs-you");
+ setSidebarThreadWork(LOCAL_ENVIRONMENT_ID, workingId, "working");
+ markThreadDoneInTest(`${LOCAL_ENVIRONMENT_ID}:${wrappedId}`, NOW_ISO);
+
+ const railToggle = await waitForElement(
+ () =>
+ document.querySelector('button[aria-label="Toggle panel"]') as HTMLButtonElement | null,
+ "Unable to find the rail toggle.",
+ );
+ railToggle.click();
+ await openRightPanelSurfaceFromLauncher("threads");
+
+ const rowsIn = (group: string) =>
+ [
+ ...document.querySelectorAll(
+ `[data-project-board-group='${group}'] [data-testid^='project-board-row-']`,
+ ),
+ ].map((row) => row.getAttribute("data-testid")!.replace("project-board-row-", ""));
+ await vi.waitFor(
+ () => {
+ expect(mounted.router.state.location.search).toMatchObject({ threads: "1" });
+ expect(
+ [...document.querySelectorAll("[data-project-board-group]")].map((group) =>
+ group.getAttribute("data-project-board-group"),
+ ),
+ ).toEqual(["needsYou", "working", "idle", "done"]);
+ expect(rowsIn("needsYou")).toEqual([approvalId]);
+ expect(rowsIn("working")).toEqual([workingId]);
+ expect(rowsIn("idle")).toEqual([THREAD_ID]);
+ // Done starts closed, like the sidebar's Wrapped shelf.
+ expect(rowsIn("done")).toEqual([]);
+ expect(document.querySelector("[data-testid='project-board-counts']")?.textContent).toBe(
+ "1 needs you · 1 working",
+ );
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+
+ (document.querySelector("[data-testid='project-board-toggle-done']") as HTMLElement).click();
+ await vi.waitFor(() => expect(rowsIn("done")).toEqual([wrappedId]), {
+ timeout: 8_000,
+ interval: 16,
+ });
+
+ (
+ document.querySelector(`[data-testid='project-board-row-${approvalId}']`) as HTMLElement
+ ).click();
+ await vi.waitFor(
+ () => {
+ expect(mounted.router.state.location.pathname).toBe(
+ `/${LOCAL_ENVIRONMENT_ID}/${approvalId}`,
+ );
+ // The board comes along, so the next row is one click away.
+ expect(mounted.router.state.location.search).toMatchObject({ threads: "1" });
+ expect(
+ document
+ .querySelector(`[data-testid='project-board-row-${approvalId}']`)
+ ?.getAttribute("data-active"),
+ ).toBe("true");
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+ } finally {
+ await mounted.cleanup();
+ }
+ });
+
it("builds a tab strip from the launcher and switches between its tabs", async () => {
const mounted = await mountChatView({
viewport: WIDE_FOOTER_VIEWPORT,
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index 10d8a8db9..c7381263b 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -45,6 +45,7 @@ import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { preserveRightPanelSearchParamsForDraftNavigation } from "../diffRouteSearch";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { type InboxEntry, useInboxThreads } from "../hooks/useInboxThreads";
+import { useOpenThreadPullRequest } from "../hooks/useOpenThreadPullRequest";
import { useThreadMenu } from "../hooks/useThreadMenu";
import { useTouchHoldMenu } from "../hooks/useTouchHoldMenu";
import { useIsMobile } from "../hooks/useMediaQuery";
@@ -1619,48 +1620,7 @@ export default function Sidebar() {
],
);
- /**
- * The pull request badge. A plain click opens the thread's Pull request tab,
- * which is where the app can actually show it; a modifier or the middle
- * button is the browser's "open it somewhere else" gesture, and the host is
- * that somewhere else.
- */
- const openPrLink = useCallback(
- (
- event: React.MouseEvent,
- pullRequest: Pick,
- threadRef: ScopedThreadRef,
- ) => {
- event.preventDefault();
- event.stopPropagation();
-
- if (!(event.metaKey || event.ctrlKey || event.button === 1)) {
- closeSheet();
- void navigate({
- to: "/$environmentId/$threadId",
- params: buildThreadRouteParams(threadRef),
- search: { pullRequest: "1", pullRequestNumber: pullRequest.number },
- });
- return;
- }
-
- const api = readLocalApi();
- if (!api) {
- toastManager.add({ type: "error", title: "Can't open links here" });
- return;
- }
-
- void api.shell.openExternal(pullRequest.url).catch((error) => {
- toastManager.add(
- failureNotice({
- title: "Couldn't open the pull request",
- error,
- }),
- );
- });
- },
- [closeSheet, navigate],
- );
+ const openPrLink = useOpenThreadPullRequest(closeSheet);
const attemptArchiveThread = useCallback(
async (threadRef: ScopedThreadRef) => {
diff --git a/apps/web/src/components/chat/ProjectBoardPanel.tsx b/apps/web/src/components/chat/ProjectBoardPanel.tsx
new file mode 100644
index 000000000..eaa272922
--- /dev/null
+++ b/apps/web/src/components/chat/ProjectBoardPanel.tsx
@@ -0,0 +1,398 @@
+/**
+ * The Threads tab: a project's threads on every computer in view, grouped by
+ * what needs the user (docs/design/lead-chat.md, "Threads panel"). The
+ * grouping is projectBoard.logic's; the filing, statuses and pull requests are
+ * the sidebar's own (useInboxThreads), so a thread reads the same here as in
+ * its sidebar row.
+ */
+import { scopedThreadKey, scopeProjectRef, scopeThreadRef } from "@threadlines/client-runtime";
+import type { EnvironmentId, ProjectId, ScopedThreadRef, ThreadId } from "@threadlines/contracts";
+import { CheckIcon, ChevronDownIcon, FlagIcon } from "lucide-react";
+import React, { memo, useCallback, useMemo, useState } from "react";
+
+import { type InboxEntry, useInboxThreads } from "../../hooks/useInboxThreads";
+import { useOpenThreadPullRequest } from "../../hooks/useOpenThreadPullRequest";
+import { useThreadMenu } from "../../hooks/useThreadMenu";
+import { useTouchHoldMenu } from "../../hooks/useTouchHoldMenu";
+import { projectLeadRef } from "../../leadChat";
+import { cn } from "../../lib/utils";
+import { selectProjectByRef, useStore } from "../../store";
+import {
+ findThreadOpenPullRequestEntry,
+ resolveNeedsYouReason,
+ type ThreadPullRequest,
+} from "../pull-requests/pullRequests.logic";
+import { RelativeTimeLabel } from "../RelativeTimeLabel";
+import {
+ ThreadEnvironmentBadge,
+ ThreadProviderGlyph,
+ ThreadPullRequestBadge,
+ ThreadStatusText,
+ threadPullRequestList,
+} from "../sidebar/InboxRows";
+import {
+ deriveProjectBoard,
+ foldProjectBoardGroup,
+ formatProjectBoardCounts,
+ type ProjectBoardGroup,
+ type ProjectBoardGroupId,
+ type ProjectBoardRow,
+ type ProjectBoardThreadInput,
+} from "./projectBoard.logic";
+
+interface BoardThread extends ProjectBoardThreadInput {
+ readonly entry: InboxEntry;
+ /** Every pull request it has, for the row's badge. */
+ readonly threadPullRequests: readonly ThreadPullRequest[];
+}
+
+const NO_PULL_REQUESTS: readonly ThreadPullRequest[] = [];
+
+/** The board's threads: the project's inbox entries, with what their pull requests wait on. */
+function useProjectBoard(environmentId: EnvironmentId, projectId: ProjectId) {
+ const inbox = useInboxThreads();
+ const {
+ entries,
+ linkedPullRequestsByThreadKey,
+ nowIso,
+ openPullRequests,
+ projects,
+ pullRequestByThreadKey,
+ resolveProjectKeyForRef,
+ } = inbox;
+ return useMemo(() => {
+ // The logical project, so copies of it on other computers are on the board too.
+ const projectKey = resolveProjectKeyForRef(scopeProjectRef(environmentId, projectId));
+ const threads = entries.flatMap((entry): BoardThread[] => {
+ if (entry.projectKey !== projectKey) return [];
+ const { thread } = entry;
+ const pullRequests = threadPullRequestList(
+ pullRequestByThreadKey.get(entry.threadKey) ?? null,
+ linkedPullRequestsByThreadKey.get(entry.threadKey) ?? NO_PULL_REQUESTS,
+ );
+ return [
+ {
+ key: entry.threadKey,
+ entry,
+ threadPullRequests: pullRequests,
+ statusLabel: entry.status?.label ?? null,
+ isDone: entry.isDone,
+ doneAt: entry.doneAt,
+ activityAt: thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt,
+ pullRequests: pullRequests.map((pullRequest) => {
+ // Review and checks live on the open listing's row, not the thread's reading.
+ const listed =
+ pullRequest.state === "open"
+ ? findThreadOpenPullRequestEntry({
+ thread,
+ number: pullRequest.number,
+ projects,
+ openEntries: openPullRequests.entries,
+ })
+ : undefined;
+ return {
+ state: pullRequest.state,
+ isDraft: pullRequest.isDraft,
+ autoMergeEnabled: pullRequest.autoMergeEnabled,
+ reviewReason: listed === undefined ? null : resolveNeedsYouReason(listed),
+ };
+ }),
+ },
+ ];
+ });
+ return deriveProjectBoard(threads, Date.parse(nowIso));
+ }, [
+ entries,
+ environmentId,
+ linkedPullRequestsByThreadKey,
+ nowIso,
+ openPullRequests.entries,
+ projectId,
+ projects,
+ pullRequestByThreadKey,
+ resolveProjectKeyForRef,
+ ]);
+}
+
+export const ProjectBoardPanel = memo(function ProjectBoardPanel({
+ environmentId,
+ threadId,
+ projectId,
+ onOpenThread,
+}: {
+ environmentId: EnvironmentId;
+ /** The thread open in the chat beside the panel. */
+ threadId: ThreadId;
+ projectId: ProjectId;
+ onOpenThread: (threadRef: ScopedThreadRef) => void;
+}) {
+ const { groups, counts } = useProjectBoard(environmentId, projectId);
+ const leadThreadId = useStore((state) => {
+ const project = selectProjectByRef(state, scopeProjectRef(environmentId, projectId));
+ return project === undefined ? null : (projectLeadRef(state, project)?.threadId ?? null);
+ });
+ const activeThreadKey = scopedThreadKey(scopeThreadRef(environmentId, threadId));
+ const [doneOpen, setDoneOpen] = useState(false);
+ const [expandedGroups, setExpandedGroups] = useState>(
+ () => new Set(),
+ );
+ const threadMenu = useThreadMenu();
+ const openPrLink = useOpenThreadPullRequest();
+ const openRowMenu = useCallback(
+ (entry: InboxEntry, position: { readonly x: number; readonly y: number }) => {
+ void threadMenu.open(
+ {
+ threadRef: scopeThreadRef(entry.thread.environmentId, entry.thread.id),
+ inbox: { isDone: entry.isDone, canMarkDone: entry.canMarkDone },
+ },
+ position,
+ );
+ },
+ [threadMenu],
+ );
+
+ return (
+
+ );
+});
diff --git a/apps/web/src/components/chat/ProjectThreadMap.logic.ts b/apps/web/src/components/chat/ProjectThreadMap.logic.ts
index 8afcb22e7..10c67a53e 100644
--- a/apps/web/src/components/chat/ProjectThreadMap.logic.ts
+++ b/apps/web/src/components/chat/ProjectThreadMap.logic.ts
@@ -1,4 +1,10 @@
import type { ThreadStatusPill } from "../Sidebar.logic";
+import {
+ THREAD_STATUS_PRESENTATION,
+ type ThreadStatusGroup,
+ type ThreadStatusPresentation,
+ type ThreadStatusTone,
+} from "./threadStatusGroups";
/**
* The new-thread screen's drawing of a project: the main line, a loop above it
@@ -7,40 +13,10 @@ import type { ThreadStatusPill } from "../Sidebar.logic";
* tested as data and the component only paints it.
*/
-export type ThreadMapTone = "amber" | "red" | "violet" | "blue" | "cyan" | "emerald";
+export type ThreadMapTone = ThreadStatusTone;
/** How the caption counts a thread, which is coarser than its colour. */
-export type ThreadMapGroup = "needsYou" | "working" | "finished";
-
-interface ThreadMapStatusPresentation {
- readonly tone: ThreadMapTone;
- readonly group: ThreadMapGroup;
- /** Lower claims a lane first when there are more threads than lanes. */
- readonly rank: number;
-}
-
-/**
- * One row per sidebar status, so the map's dots are the sidebar's dots. Keyed
- * by the label union: a status added there fails to compile here until it is
- * given a colour and a place in the count.
- */
-const STATUS_PRESENTATION: Readonly<
- Record
-> = {
- "Pending Approval": { tone: "amber", group: "needsYou", rank: 0 },
- "Awaiting Input": { tone: "amber", group: "needsYou", rank: 0 },
- Failed: { tone: "red", group: "needsYou", rank: 0 },
- "Plan Ready": { tone: "violet", group: "needsYou", rank: 1 },
- Working: { tone: "blue", group: "working", rank: 2 },
- Starting: { tone: "blue", group: "working", rank: 2 },
- Answering: { tone: "blue", group: "working", rank: 2 },
- Waiting: { tone: "cyan", group: "working", rank: 2 },
- Completed: { tone: "emerald", group: "finished", rank: 3 },
- // Settled, and an agent will come back by itself: a wait, after a result.
- "Checking back": { tone: "cyan", group: "working", rank: 3 },
- // Stopped by a usage limit, and continues by itself once it resets.
- "Continues at reset": { tone: "cyan", group: "working", rank: 3 },
-};
+export type ThreadMapGroup = ThreadStatusGroup;
/** More lanes than this and the drawing stops reading as a glance. */
export const THREAD_MAP_MAX_LANES = 4;
@@ -93,11 +69,11 @@ export function deriveThreadMapLanes(threads: readonly ThreadMapThreadInput[]):
const candidates: {
readonly thread: ThreadMapThreadInput;
readonly statusLabel: ThreadStatusPill["label"];
- readonly presentation: ThreadMapStatusPresentation;
+ readonly presentation: ThreadStatusPresentation;
}[] = [];
for (const thread of threads) {
if (thread.statusLabel === null) continue;
- const presentation = STATUS_PRESENTATION[thread.statusLabel];
+ const presentation = THREAD_STATUS_PRESENTATION[thread.statusLabel];
counts[presentation.group] += 1;
candidates.push({ thread, statusLabel: thread.statusLabel, presentation });
}
diff --git a/apps/web/src/components/chat/RightPanelTabStrip.tsx b/apps/web/src/components/chat/RightPanelTabStrip.tsx
index cc6bc985f..c376f3c1c 100644
--- a/apps/web/src/components/chat/RightPanelTabStrip.tsx
+++ b/apps/web/src/components/chat/RightPanelTabStrip.tsx
@@ -23,6 +23,7 @@ import {
FileDiffIcon,
GitPullRequestIcon,
ImagesIcon,
+ ListTreeIcon,
PlusIcon,
XIcon,
} from "lucide-react";
@@ -54,6 +55,7 @@ export const RIGHT_PANEL_TAB_ICONS: Readonly> = {
pullRequest: GitPullRequestIcon,
agents: BotIcon,
media: ImagesIcon,
+ threads: ListTreeIcon,
};
/** Labelled while they fit, all icons once they do not. Never a mix: dropping
diff --git a/apps/web/src/components/chat/projectBoard.logic.test.ts b/apps/web/src/components/chat/projectBoard.logic.test.ts
new file mode 100644
index 000000000..5f289a293
--- /dev/null
+++ b/apps/web/src/components/chat/projectBoard.logic.test.ts
@@ -0,0 +1,168 @@
+import { describe, expect, it } from "vite-plus/test";
+
+import {
+ deriveProjectBoard,
+ foldProjectBoardGroup,
+ formatProjectBoardCounts,
+ PROJECT_BOARD_GROUP_FOLD_AT,
+ type ProjectBoardPullRequestInput,
+ type ProjectBoardThreadInput,
+} from "./projectBoard.logic";
+
+const HOUR_MS = 60 * 60 * 1_000;
+const DAY_MS = 24 * HOUR_MS;
+const NOW_MS = Date.parse("2026-11-16T20:00:00.000Z");
+const ago = (ms: number) => new Date(NOW_MS - ms).toISOString();
+
+function thread(
+ key: string,
+ overrides: Partial = {},
+): ProjectBoardThreadInput {
+ return {
+ key,
+ statusLabel: null,
+ isDone: false,
+ doneAt: null,
+ activityAt: ago(HOUR_MS),
+ pullRequests: [],
+ ...overrides,
+ };
+}
+
+function openPullRequest(
+ overrides: Partial = {},
+): ProjectBoardPullRequestInput {
+ return {
+ state: "open",
+ isDraft: false,
+ autoMergeEnabled: false,
+ reviewReason: null,
+ ...overrides,
+ };
+}
+
+/** The board as group id → thread keys, in drawing order. */
+function board(threads: readonly ProjectBoardThreadInput[]) {
+ return deriveProjectBoard(threads, NOW_MS).groups.map((group) => [
+ group.id,
+ group.rows.map((row) => row.thread.key),
+ ]);
+}
+
+describe("deriveProjectBoard", () => {
+ it("sorts threads into the plan's groups and draws them in its order", () => {
+ expect(
+ board([
+ thread("wrapped", { isDone: true, doneAt: ago(DAY_MS) }),
+ thread("idle"),
+ thread("landing", { pullRequests: [openPullRequest({ autoMergeEnabled: true })] }),
+ thread("working", { statusLabel: "Waiting" }),
+ thread("review", { pullRequests: [openPullRequest()] }),
+ thread("approval", { statusLabel: "Pending Approval" }),
+ thread("limited", { statusLabel: "Continues at reset" }),
+ thread("plan", { statusLabel: "Plan Ready" }),
+ ]),
+ ).toEqual([
+ ["needsYou", ["approval", "plan"]],
+ ["readyForReview", ["review"]],
+ ["working", ["limited", "working"]],
+ ["landing", ["landing"]],
+ ["idle", ["idle"]],
+ ["done", ["wrapped"]],
+ ]);
+ });
+
+ it("files a wrapped failed thread under Done, not Needs you", () => {
+ expect(
+ board([thread("failed", { statusLabel: "Failed", isDone: true, doneAt: ago(HOUR_MS) })]),
+ ).toEqual([["done", ["failed"]]]);
+ });
+
+ it("keeps a wrapped child with an open pull request up for review or landing", () => {
+ expect(
+ board([
+ thread("handed-back", {
+ statusLabel: "Completed",
+ isDone: true,
+ doneAt: ago(HOUR_MS),
+ pullRequests: [openPullRequest({ reviewReason: "Checks failing" })],
+ }),
+ thread("auto-merging", {
+ isDone: true,
+ doneAt: ago(HOUR_MS),
+ pullRequests: [openPullRequest({ autoMergeEnabled: true })],
+ }),
+ // A draft is not up for review, so the wrap stands.
+ thread("draft", {
+ isDone: true,
+ doneAt: ago(HOUR_MS),
+ pullRequests: [openPullRequest({ isDraft: true })],
+ }),
+ ]),
+ ).toEqual([
+ ["readyForReview", ["handed-back"]],
+ ["landing", ["auto-merging"]],
+ ["done", ["draft"]],
+ ]);
+ });
+
+ it("leaves a thread wrapped more than 7 days ago off the board", () => {
+ expect(
+ board([
+ thread("last-week", { isDone: true, doneAt: ago(8 * DAY_MS) }),
+ thread("yesterday", { isDone: true, doneAt: ago(DAY_MS) }),
+ ]),
+ ).toEqual([["done", ["yesterday"]]]);
+ });
+
+ it("puts a thread at work ahead of its pull request, and a merged one in Idle", () => {
+ expect(
+ board([
+ thread("fixing", { statusLabel: "Working", pullRequests: [openPullRequest()] }),
+ thread("merged", { pullRequests: [{ ...openPullRequest(), state: "merged" }] }),
+ ]),
+ ).toEqual([
+ ["working", ["fixing"]],
+ ["idle", ["merged"]],
+ ]);
+ });
+
+ it("words a review row with the Pull requests page's reason", () => {
+ const { groups } = deriveProjectBoard(
+ [
+ thread("changes", {
+ pullRequests: [openPullRequest({ reviewReason: "Changes requested" })],
+ }),
+ ],
+ NOW_MS,
+ );
+ expect(groups[0]?.rows[0]?.pullRequestWord).toBe("changes requested");
+ });
+
+ it("counts what the header names", () => {
+ const { counts } = deriveProjectBoard(
+ [
+ thread("a", { statusLabel: "Awaiting Input" }),
+ thread("b", { statusLabel: "Failed" }),
+ thread("c", { statusLabel: "Working" }),
+ thread("d", { pullRequests: [openPullRequest()] }),
+ ],
+ NOW_MS,
+ );
+ expect(formatProjectBoardCounts(counts)).toBe("2 need you · 1 to review · 1 working");
+ expect(formatProjectBoardCounts({ needsYou: 0, readyForReview: 0, working: 0 })).toBe(
+ "Nothing needs you",
+ );
+ });
+});
+
+describe("foldProjectBoardGroup", () => {
+ it("folds a long group behind Show N more until it is expanded", () => {
+ const rows = Array.from({ length: PROJECT_BOARD_GROUP_FOLD_AT + 3 }, (_, index) => index);
+ expect(foldProjectBoardGroup(rows, false)).toEqual({
+ shown: rows.slice(0, PROJECT_BOARD_GROUP_FOLD_AT),
+ hiddenCount: 3,
+ });
+ expect(foldProjectBoardGroup(rows, true)).toEqual({ shown: rows, hiddenCount: 0 });
+ });
+});
diff --git a/apps/web/src/components/chat/projectBoard.logic.ts b/apps/web/src/components/chat/projectBoard.logic.ts
new file mode 100644
index 000000000..36f8a80d9
--- /dev/null
+++ b/apps/web/src/components/chat/projectBoard.logic.ts
@@ -0,0 +1,211 @@
+import type { ThreadStatusPill } from "../Sidebar.logic";
+import type { PullRequestNeedsYouReason } from "../pull-requests/pullRequests.logic";
+import { THREAD_STATUS_PRESENTATION } from "./threadStatusGroups";
+
+/**
+ * The Threads panel's sorting of a project's threads by what needs the user
+ * (docs/design/lead-chat.md, "Threads panel"). Pure, so the board is tested as
+ * data and the panel only paints it.
+ */
+
+export type ProjectBoardGroupId =
+ | "needsYou"
+ | "readyForReview"
+ | "working"
+ | "landing"
+ | "idle"
+ | "done";
+
+/** The order the groups are drawn in. A thread is placed by a different order; see `placeThread`. */
+export const PROJECT_BOARD_GROUP_ORDER: readonly ProjectBoardGroupId[] = [
+ "needsYou",
+ "readyForReview",
+ "working",
+ "landing",
+ "idle",
+ "done",
+];
+
+export const PROJECT_BOARD_GROUP_LABELS: Readonly> = {
+ needsYou: "Needs you",
+ readyForReview: "Ready for review",
+ working: "Working",
+ landing: "Landing",
+ idle: "Idle",
+ done: "Done",
+};
+
+/** Wrapped longer ago than this and a thread is off the board. */
+export const PROJECT_BOARD_DONE_WINDOW_MS = 7 * 24 * 60 * 60 * 1_000;
+
+/** More rows than this in a group and the rest fold behind "Show N more". */
+export const PROJECT_BOARD_GROUP_FOLD_AT = 8;
+
+/** One of a thread's pull requests, as much as the board reads of it. */
+export interface ProjectBoardPullRequestInput {
+ readonly state: "open" | "merged" | "closed";
+ readonly isDraft: boolean;
+ /** Armed to land on its own, or already in the merge queue. */
+ readonly autoMergeEnabled: boolean;
+ /** What the Pull requests page says it waits on, from the open listing; null when nothing. */
+ readonly reviewReason: PullRequestNeedsYouReason | null;
+}
+
+export interface ProjectBoardThreadInput {
+ readonly key: string;
+ /** The sidebar's status for the thread, or null when it shows none. */
+ readonly statusLabel: ThreadStatusPill["label"] | null;
+ /** The sidebar files it under Wrapped (`InboxEntry.isDone`). */
+ readonly isDone: boolean;
+ /** When it was wrapped; null while not, or when that is not known. */
+ readonly doneAt: string | null;
+ /** When it last moved, newest first within a group. */
+ readonly activityAt: string;
+ /** Its own pull request first, then the ones its agent opened elsewhere. */
+ readonly pullRequests: readonly ProjectBoardPullRequestInput[];
+}
+
+export interface ProjectBoardRow {
+ readonly thread: T;
+ /**
+ * The row's word in place of its status, from its pull request: why it
+ * waits for review, or that it is landing. Null leaves the thread's own
+ * status words.
+ */
+ readonly pullRequestWord: string | null;
+}
+
+export interface ProjectBoardGroup {
+ readonly id: ProjectBoardGroupId;
+ readonly label: string;
+ readonly rows: readonly ProjectBoardRow[];
+}
+
+export interface ProjectBoardCounts {
+ readonly needsYou: number;
+ readonly readyForReview: number;
+ readonly working: number;
+}
+
+function timestampMs(iso: string | null): number {
+ if (iso === null) return 0;
+ const ms = Date.parse(iso);
+ return Number.isFinite(ms) ? ms : 0;
+}
+
+/** Its open, non-draft pull requests: the ones that put it up for review or landing. */
+function reviewablePullRequests(
+ thread: ProjectBoardThreadInput,
+): readonly ProjectBoardPullRequestInput[] {
+ return thread.pullRequests.filter(
+ (pullRequest) => pullRequest.state === "open" && !pullRequest.isDraft,
+ );
+}
+
+/** Landing or Ready for review, from its open pull requests; null when it has none up. */
+function pullRequestPlacement(
+ thread: ProjectBoardThreadInput,
+): { readonly group: "landing" | "readyForReview"; readonly word: string | null } | null {
+ const open = reviewablePullRequests(thread);
+ if (open.length === 0) return null;
+ if (open.some((pullRequest) => pullRequest.autoMergeEnabled)) {
+ return { group: "landing", word: "auto-merge" };
+ }
+ const reason = open.find((pullRequest) => pullRequest.reviewReason !== null)?.reviewReason;
+ return { group: "readyForReview", word: reason ? reason.toLowerCase() : null };
+}
+
+/**
+ * Which group a thread goes in, the first that fits, or null when it is off
+ * the board. Filing comes first: "Wrapped" is the sidebar's answer, not a
+ * status, so a failed thread the user wrapped belongs in Done. The one
+ * exception keeps review work in sight: a wrapped thread whose pull request is
+ * still open (a finished child wraps itself the moment it hands back) goes to
+ * Landing or Ready for review.
+ */
+function placeThread(
+ thread: ProjectBoardThreadInput,
+ nowMs: number,
+): { readonly group: ProjectBoardGroupId; readonly word: string | null } | null {
+ const pullRequest = pullRequestPlacement(thread);
+ if (thread.isDone) {
+ if (pullRequest !== null) return pullRequest;
+ // An undated wrap is shown rather than guessed old.
+ const wrappedMs = thread.doneAt === null ? nowMs : timestampMs(thread.doneAt);
+ return nowMs - wrappedMs <= PROJECT_BOARD_DONE_WINDOW_MS ? { group: "done", word: null } : null;
+ }
+ const statusGroup =
+ thread.statusLabel === null ? null : THREAD_STATUS_PRESENTATION[thread.statusLabel].group;
+ if (statusGroup === "needsYou") return { group: "needsYou", word: null };
+ if (statusGroup === "working") return { group: "working", word: null };
+ return pullRequest ?? { group: "idle", word: null };
+}
+
+/**
+ * The board: the groups that have anything in them, in drawing order, each
+ * newest first (Done by when it was wrapped), and the header's counts.
+ */
+export function deriveProjectBoard(
+ threads: readonly T[],
+ nowMs: number,
+): { readonly groups: readonly ProjectBoardGroup[]; readonly counts: ProjectBoardCounts } {
+ const byGroup = new Map[]>();
+ for (const thread of threads) {
+ const placement = placeThread(thread, nowMs);
+ if (placement === null) continue;
+ const rows = byGroup.get(placement.group) ?? [];
+ rows.push({ thread, pullRequestWord: placement.word });
+ byGroup.set(placement.group, rows);
+ }
+ const groups = PROJECT_BOARD_GROUP_ORDER.flatMap((id): ProjectBoardGroup[] => {
+ const rows = byGroup.get(id);
+ if (rows === undefined) return [];
+ const sortAt = (row: ProjectBoardRow) =>
+ timestampMs(
+ id === "done" ? (row.thread.doneAt ?? row.thread.activityAt) : row.thread.activityAt,
+ );
+ return [
+ {
+ id,
+ label: PROJECT_BOARD_GROUP_LABELS[id],
+ rows: rows.toSorted(
+ (left, right) =>
+ sortAt(right) - sortAt(left) || left.thread.key.localeCompare(right.thread.key),
+ ),
+ },
+ ];
+ });
+ return {
+ groups,
+ counts: {
+ needsYou: byGroup.get("needsYou")?.length ?? 0,
+ readyForReview: byGroup.get("readyForReview")?.length ?? 0,
+ working: byGroup.get("working")?.length ?? 0,
+ },
+ };
+}
+
+/** A group's rows as drawn: the first few, and how many fold behind "Show N more". */
+export function foldProjectBoardGroup(
+ rows: readonly R[],
+ expanded: boolean,
+): { readonly shown: readonly R[]; readonly hiddenCount: number } {
+ if (expanded || rows.length <= PROJECT_BOARD_GROUP_FOLD_AT) {
+ return { shown: rows, hiddenCount: 0 };
+ }
+ return {
+ shown: rows.slice(0, PROJECT_BOARD_GROUP_FOLD_AT),
+ hiddenCount: rows.length - PROJECT_BOARD_GROUP_FOLD_AT,
+ };
+}
+
+/** The header's line: "2 need you · 1 to review · 3 working", or that nothing is going on. */
+export function formatProjectBoardCounts(counts: ProjectBoardCounts): string {
+ const parts: string[] = [];
+ if (counts.needsYou > 0) {
+ parts.push(counts.needsYou === 1 ? "1 needs you" : `${counts.needsYou} need you`);
+ }
+ if (counts.readyForReview > 0) parts.push(`${counts.readyForReview} to review`);
+ if (counts.working > 0) parts.push(`${counts.working} working`);
+ return parts.length === 0 ? "Nothing needs you" : parts.join(" · ");
+}
diff --git a/apps/web/src/components/chat/threadStatusGroups.ts b/apps/web/src/components/chat/threadStatusGroups.ts
new file mode 100644
index 000000000..c5473fe22
--- /dev/null
+++ b/apps/web/src/components/chat/threadStatusGroups.ts
@@ -0,0 +1,46 @@
+import type { ThreadStatusPill } from "../Sidebar.logic";
+
+/**
+ * Where each sidebar status stands with the user, for the surfaces that sort a
+ * project's threads by it: the new-thread screen's map (ProjectThreadMap) and
+ * the Threads panel (projectBoard.logic). One table, so the two can never put
+ * the same thread in different places.
+ */
+
+export type ThreadStatusTone = "amber" | "red" | "violet" | "blue" | "cyan" | "emerald";
+
+/**
+ * How a status counts: stopped on the user, at work (or coming back by
+ * itself), or finished and not yet looked at.
+ */
+export type ThreadStatusGroup = "needsYou" | "working" | "finished";
+
+export interface ThreadStatusPresentation {
+ readonly tone: ThreadStatusTone;
+ readonly group: ThreadStatusGroup;
+ /** The map's lane priority: lower claims a lane first. */
+ readonly rank: number;
+}
+
+/**
+ * One row per sidebar status, so these dots are the sidebar's dots. Keyed by
+ * the label union: a status added there fails to compile here until it is
+ * given a colour and a group.
+ */
+export const THREAD_STATUS_PRESENTATION: Readonly<
+ Record
+> = {
+ "Pending Approval": { tone: "amber", group: "needsYou", rank: 0 },
+ "Awaiting Input": { tone: "amber", group: "needsYou", rank: 0 },
+ Failed: { tone: "red", group: "needsYou", rank: 0 },
+ "Plan Ready": { tone: "violet", group: "needsYou", rank: 1 },
+ Working: { tone: "blue", group: "working", rank: 2 },
+ Starting: { tone: "blue", group: "working", rank: 2 },
+ Answering: { tone: "blue", group: "working", rank: 2 },
+ Waiting: { tone: "cyan", group: "working", rank: 2 },
+ Completed: { tone: "emerald", group: "finished", rank: 3 },
+ // Settled, and an agent will come back by itself: a wait, after a result.
+ "Checking back": { tone: "cyan", group: "working", rank: 3 },
+ // Stopped by a usage limit, and continues by itself once it resets.
+ "Continues at reset": { tone: "cyan", group: "working", rank: 3 },
+};
diff --git a/apps/web/src/components/pull-requests/pullRequests.logic.ts b/apps/web/src/components/pull-requests/pullRequests.logic.ts
index d95778ce9..d7dbb9b43 100644
--- a/apps/web/src/components/pull-requests/pullRequests.logic.ts
+++ b/apps/web/src/components/pull-requests/pullRequests.logic.ts
@@ -1158,6 +1158,24 @@ function findNumberedListEntry(
);
}
+/**
+ * The open listing's row for one of a thread's pull requests, found by the
+ * thread's repository and the pull request's number, so a pull request its
+ * agent opened on another branch is found as well as its own. The row is
+ * where the review decision and the checks live, which the thread's own
+ * reading does not carry.
+ */
+export function findThreadOpenPullRequestEntry(input: {
+ readonly thread: Pick;
+ readonly number: number;
+ readonly projects: readonly Project[];
+ readonly openEntries: readonly PullRequestEntry[];
+}): PullRequestEntry | undefined {
+ const project = findThreadProject(input.thread, input.projects);
+ const scope = project === undefined ? null : projectRepositoryScope(project);
+ return scope === null ? undefined : findNumberedListEntry(scope, input.number, input.openEntries);
+}
+
/**
* The pull requests a thread's agent opened on other branches (its
* `linkedPullRequests`), as the composer rows, the Pull request tab and the
diff --git a/apps/web/src/components/sidebar/InboxRows.tsx b/apps/web/src/components/sidebar/InboxRows.tsx
index 8eb395e58..0d57aa0aa 100644
--- a/apps/web/src/components/sidebar/InboxRows.tsx
+++ b/apps/web/src/components/sidebar/InboxRows.tsx
@@ -139,7 +139,7 @@ const ROW_ACTIONS_CLASS_NAME =
* Every pull request a thread has, its own first, each once: a linked one can
* be the thread's own after the thread moves onto its branch.
*/
-function threadPullRequestList(
+export function threadPullRequestList(
own: ThreadPullRequest | null,
linked: readonly ThreadPullRequest[],
): readonly ThreadPullRequest[] {
@@ -153,7 +153,7 @@ function threadPullRequestList(
* so a merged branch reads the same violet wherever the thread ends up.
* Renders nothing without a pull request.
*/
-function ThreadPullRequestBadge({
+export function ThreadPullRequestBadge({
pullRequests,
provider,
threadRef,
diff --git a/apps/web/src/diffRouteSearch.test.ts b/apps/web/src/diffRouteSearch.test.ts
index 6841e4c73..3eaeddc6f 100644
--- a/apps/web/src/diffRouteSearch.test.ts
+++ b/apps/web/src/diffRouteSearch.test.ts
@@ -200,6 +200,7 @@ describe("closeRightPanelSearchParams", () => {
pullRequest: "0",
agents: "0",
media: "0",
+ threads: "0",
diffTurnId: undefined,
diffFilePath: undefined,
});
diff --git a/apps/web/src/diffRouteSearch.ts b/apps/web/src/diffRouteSearch.ts
index f84f898b0..aa2527e49 100644
--- a/apps/web/src/diffRouteSearch.ts
+++ b/apps/web/src/diffRouteSearch.ts
@@ -3,8 +3,8 @@ import { MessageId, TurnId } from "@threadlines/contracts";
/**
* The right sidebar's tabs are filed under the params they have always used:
* `sourceControl=1` is the Source tab, `diff=1` the Diff tab, `pullRequest=1`
- * the Pull request tab, `agents=1` the Agents tab, `media=1` the Media tab. At
- * most one reads as open,
+ * the Pull request tab, `agents=1` the Agents tab, `media=1` the Media tab,
+ * `threads=1` the Threads tab. At most one reads as open,
* and that one is the active tab; an explicit `0` means the sidebar is closed.
* `pullRequestNumber` names which of the thread's pull requests the Pull
* request tab shows, the way the diff params name what the Diff tab shows.
@@ -17,6 +17,7 @@ export interface DiffRouteSearch {
pullRequestNumber?: number | undefined;
agents?: "1" | "0" | undefined;
media?: "1" | "0" | undefined;
+ threads?: "1" | "0" | undefined;
diffTurnId?: TurnId | undefined;
diffFilePath?: string | undefined;
focusMessageId?: MessageId | undefined;
@@ -83,6 +84,7 @@ type RightPanelSearchKey =
| "pullRequestNumber"
| "agents"
| "media"
+ | "threads"
| "diffTurnId"
| "diffFilePath";
@@ -94,6 +96,7 @@ interface ClearedRightPanelSearchParams {
pullRequestNumber?: undefined;
agents?: undefined;
media?: undefined;
+ threads?: undefined;
diffTurnId?: undefined;
diffFilePath?: undefined;
}
@@ -113,6 +116,7 @@ export function stripRightPanelSearchParams>(
pullRequestNumber: _pullRequestNumber,
agents: _agents,
media: _media,
+ threads: _threads,
diffTurnId: _diffTurnId,
diffFilePath: _diffFilePath,
...rest
@@ -126,6 +130,7 @@ export function stripRightPanelSearchParams>(
pullRequestNumber: undefined,
agents: undefined,
media: undefined,
+ threads: undefined,
diffTurnId: undefined,
diffFilePath: undefined,
} as Omit & ClearedRightPanelSearchParams;
@@ -142,6 +147,7 @@ export function closeRightPanelSearchParams>(p
pullRequest: "0" as const,
agents: "0" as const,
media: "0" as const,
+ threads: "0" as const,
};
}
@@ -153,7 +159,7 @@ export function closeRightPanelSearchParams>(p
export function preserveRightPanelSearchParamsForDraftNavigation>(
params: T,
) {
- const { sourceControl, pullRequest, agents, media } = parseDiffRouteSearch(params);
+ const { sourceControl, pullRequest, agents, media, threads } = parseDiffRouteSearch(params);
const stripped = stripRightPanelSearchParams(params);
return {
...stripped,
@@ -161,6 +167,7 @@ export function preserveRightPanelSearchParamsForDraftNavigation): DiffRoute
: !diff && isExplicitClosedValue(search.media)
? "0"
: undefined;
+ const threads =
+ !diff && isDiffOpenValue(search.threads)
+ ? "1"
+ : !diff && isExplicitClosedValue(search.threads)
+ ? "0"
+ : undefined;
const diffTurnIdRaw =
diff && diffMode !== "workingTree" ? normalizeSearchString(search.diffTurnId) : undefined;
const diffTurnId = diffTurnIdRaw ? TurnId.make(diffTurnIdRaw) : undefined;
@@ -212,6 +225,7 @@ export function parseDiffRouteSearch(search: Record): DiffRoute
...(pullRequestNumber ? { pullRequestNumber } : {}),
...(agents ? { agents } : {}),
...(media ? { media } : {}),
+ ...(threads ? { threads } : {}),
...(diffTurnId ? { diffTurnId } : {}),
...(diffFilePath ? { diffFilePath } : {}),
...(focusMessageId ? { focusMessageId } : {}),
diff --git a/apps/web/src/hooks/useOpenThreadPullRequest.ts b/apps/web/src/hooks/useOpenThreadPullRequest.ts
new file mode 100644
index 000000000..7a52df279
--- /dev/null
+++ b/apps/web/src/hooks/useOpenThreadPullRequest.ts
@@ -0,0 +1,56 @@
+import type { ScopedThreadRef } from "@threadlines/contracts";
+import { useNavigate } from "@tanstack/react-router";
+import type React from "react";
+import { useCallback } from "react";
+
+import type { ThreadPullRequest } from "../components/pull-requests/pullRequests.logic";
+import { failureNotice, toastManager } from "../components/ui/toast";
+import { readLocalApi } from "../localApi";
+import { buildThreadRouteParams } from "../threadRoutes";
+
+/**
+ * What a thread row's pull request badge does when clicked. A plain click
+ * opens the thread's Pull request tab, which is where the app can actually
+ * show it; a modifier or the middle button is the browser's "open it
+ * somewhere else" gesture, and the host is that somewhere else.
+ * `beforeNavigate` runs before the in-app open (a phone sheet steps aside).
+ */
+export function useOpenThreadPullRequest(beforeNavigate?: () => void) {
+ const navigate = useNavigate();
+ return useCallback(
+ (
+ event: React.MouseEvent,
+ pullRequest: Pick,
+ threadRef: ScopedThreadRef,
+ ) => {
+ event.preventDefault();
+ event.stopPropagation();
+
+ if (!(event.metaKey || event.ctrlKey || event.button === 1)) {
+ beforeNavigate?.();
+ void navigate({
+ to: "/$environmentId/$threadId",
+ params: buildThreadRouteParams(threadRef),
+ search: { pullRequest: "1", pullRequestNumber: pullRequest.number },
+ });
+ return;
+ }
+
+ const api = readLocalApi();
+ if (!api) {
+ toastManager.add({ type: "error", title: "Can't open links here" });
+ return;
+ }
+
+ void api.shell.openExternal(pullRequest.url).catch((error) => {
+ toastManager.add(
+ failureNotice({
+ title: "Couldn't open the pull request",
+ error,
+ }),
+ );
+ });
+ },
+ [beforeNavigate, navigate],
+ );
+}
diff --git a/apps/web/src/leadChat.ts b/apps/web/src/leadChat.ts
index 0277f3439..b317fccd3 100644
--- a/apps/web/src/leadChat.ts
+++ b/apps/web/src/leadChat.ts
@@ -17,12 +17,15 @@ import {
} from "@threadlines/contracts";
import { leadSetRefusal, projectLeadThreadId } from "@threadlines/shared/projectLead";
import { agentThreadsMode } from "@threadlines/shared/serverSettings";
+import * as Schema from "effect/Schema";
import { addComputerNotConnectedNotice } from "./components/computerConnectionNotices";
import { failureNotice, toastManager } from "./components/ui/toast";
import { readEnvironmentApi } from "./environmentApi";
import { readEnvironmentDescriptor } from "./environments/runtime";
+import { getLocalStorageItem, setLocalStorageItem } from "./hooks/useLocalStorage";
import { newCommandId, newThreadId } from "./lib/utils";
+import { queueRightPanelTab } from "./rightPanelTabs";
import {
lastUsedSelection,
readComputerConfig,
@@ -156,10 +159,25 @@ export function leadMenuLabel(state: LeadMenuState): string {
: `${base}: ${state.refusal.charAt(0).toLowerCase()}${state.refusal.slice(1).replace(/\.$/, "")}`;
}
+/** Set once a thread on this device has become a lead: see `showThreadsPanelOnFirstLead`. */
+const FIRST_LEAD_SHOWN_KEY = "threadlines:lead-chat:threads-panel-shown";
+
+/**
+ * The first time a thread becomes the lead on this device, its Threads tab
+ * opens beside it, so the board that goes with a lead is found. Once per
+ * device: after that, opening it is the user's move.
+ */
+function showThreadsPanelOnFirstLead(threadRef: ScopedThreadRef): void {
+ if (getLocalStorageItem(FIRST_LEAD_SHOWN_KEY, Schema.Boolean) === true) return;
+ setLocalStorageItem(FIRST_LEAD_SHOWN_KEY, true, Schema.Boolean);
+ queueRightPanelTab(scopedThreadKey(threadRef), "threads");
+}
+
/**
* 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.
+ * or is too old to keep a lead. Every way of making a lead (the thread menus,
+ * the palette, "New lead chat") comes through here.
*/
export async function setProjectLead(input: {
readonly environmentId: EnvironmentId;
@@ -191,6 +209,9 @@ export async function setProjectLead(input: {
projectId: input.projectId,
threadId: input.threadId,
});
+ if (input.threadId !== null) {
+ showThreadsPanelOnFirstLead(scopeThreadRef(input.environmentId, input.threadId));
+ }
return true;
} catch (error) {
toastManager.add(failureNotice({ title: failure, error }));
diff --git a/apps/web/src/rightPanelTabs.test.ts b/apps/web/src/rightPanelTabs.test.ts
index 85b322a51..16fbf8ecb 100644
--- a/apps/web/src/rightPanelTabs.test.ts
+++ b/apps/web/src/rightPanelTabs.test.ts
@@ -45,10 +45,17 @@ function openedOn(tab: RightPanelTab): RightPanelTabsState {
describe("availableRightPanelTabs", () => {
it("offers only the surfaces a thread actually has", () => {
- expect(ALL_TABS).toEqual(["sourceControl", "diff", "pullRequest", "agents", "media"]);
+ expect(ALL_TABS).toEqual([
+ "sourceControl",
+ "diff",
+ "pullRequest",
+ "agents",
+ "media",
+ "threads",
+ ]);
// No repository, so no changes and no diff.
expect(availableRightPanelTabs({ isGeneralChat: true, isDraft: false })).toEqual(["agents"]);
- // No turn yet, so no agents and no media.
+ // No turn yet, so no agents, no media and no project board.
expect(availableRightPanelTabs({ isGeneralChat: false, isDraft: true })).toEqual([
"sourceControl",
"diff",
@@ -63,6 +70,7 @@ describe("activeRightPanelTabFromSearch", () => {
expect(activeRightPanelTabFromSearch({ sourceControl: "1" })).toBe("sourceControl");
expect(activeRightPanelTabFromSearch({ agents: "1" })).toBe("agents");
expect(activeRightPanelTabFromSearch({ media: "1" })).toBe("media");
+ expect(activeRightPanelTabFromSearch({ threads: "1" })).toBe("threads");
expect(activeRightPanelTabFromSearch({ pullRequest: "1" })).toBe("pullRequest");
expect(activeRightPanelTabFromSearch({ diff: "1" })).toBe("diff");
// The diff key wins, which is what `parseDiffRouteSearch` already enforces.
@@ -77,6 +85,7 @@ describe("activeRightPanelTabFromSearch", () => {
expect(isRightPanelClosedInSearch({ sourceControl: "0", agents: "1" })).toBe(false);
expect(isRightPanelClosedInSearch({ pullRequest: "1" })).toBe(false);
expect(isRightPanelClosedInSearch({ media: "0" })).toBe(true);
+ expect(isRightPanelClosedInSearch({ threads: "0" })).toBe(true);
});
});
@@ -104,6 +113,12 @@ describe("rightPanelTabSearchParams", () => {
pullRequest: "0",
agents: "0",
media: "1",
+ threads: "0",
+ });
+ expect(rightPanelTabSearchParams({}, "threads")).toMatchObject({
+ sourceControl: "0",
+ media: "0",
+ threads: "1",
});
});
diff --git a/apps/web/src/rightPanelTabs.ts b/apps/web/src/rightPanelTabs.ts
index a4f363780..86a26ef57 100644
--- a/apps/web/src/rightPanelTabs.ts
+++ b/apps/web/src/rightPanelTabs.ts
@@ -2,15 +2,15 @@
* The right sidebar's tab model.
*
* The sidebar is one browser-style panel with a tab strip: Source, Diff,
- * Pull request, Agents and Media are surfaces you open into it, each at most
- * once. Two things have to
+ * Pull request, Agents, Media and Threads are surfaces you open into it, each
+ * at most once. Two things have to
* agree about it — the route that renders the panel and the chat header that
* toggles it — so the state lives here rather than in either of them.
*
* Split of authority:
*
* - The URL owns the ACTIVE tab, mapped onto the params that already existed
- * (`sourceControl=1`, `diff=1`, `agents=1`, `media=1`). Deep links keep working and an
+ * (`sourceControl=1`, `diff=1`, `agents=1`, `media=1`, `threads=1`). Deep links keep working and an
* explicit `0` still means closed.
* - This module owns what the URL cannot say: which tabs are in the strip,
* whether the sidebar is showing at all (it can be open on the launcher with
@@ -29,7 +29,13 @@ import {
/** A surface the sidebar can open, and the key its active state is filed under
* in the URL. */
-export type RightPanelTab = "sourceControl" | "diff" | "pullRequest" | "agents" | "media";
+export type RightPanelTab =
+ | "sourceControl"
+ | "diff"
+ | "pullRequest"
+ | "agents"
+ | "media"
+ | "threads";
/** Launcher order and `+` menu order. The strip itself is ordered by when each
* tab was opened, like a browser's, so this is only how the fixed menus list
@@ -40,6 +46,7 @@ export const RIGHT_PANEL_TAB_ORDER: ReadonlyArray = [
"pullRequest",
"agents",
"media",
+ "threads",
];
export interface RightPanelSurface {
@@ -83,6 +90,13 @@ export const RIGHT_PANEL_SURFACES: Readonly>(
pullRequest: tab === "pullRequest" ? ("1" as const) : ("0" as const),
agents: tab === "agents" ? ("1" as const) : ("0" as const),
media: tab === "media" ? ("1" as const) : ("0" as const),
+ threads: tab === "threads" ? ("1" as const) : ("0" as const),
};
}
@@ -634,7 +653,38 @@ export function hideRightPanel(threadKey: string | null): void {
mutate(threadKey, hideRightPanelState);
}
+/**
+ * A tab something outside the route wants opened on a thread the next time
+ * its route can show it: code that has no navigation of its own (a command
+ * finishing) asks here, and the route opens it, URL and all, once the thread
+ * is on screen with that tab available. Session-scoped like the strips.
+ */
+const queuedTabByThreadKey = new Map();
+
+export function queueRightPanelTab(threadKey: string, tab: RightPanelTab): void {
+ queuedTabByThreadKey.set(threadKey, tab);
+ notify();
+}
+
+/** The tab queued for this thread, if any. The route opens it, then clears it. */
+export function useQueuedRightPanelTab(threadKey: string | null): RightPanelTab | null {
+ return useSyncExternalStore(
+ subscribe,
+ useCallback(
+ () => (threadKey ? (queuedTabByThreadKey.get(threadKey) ?? null) : null),
+ [threadKey],
+ ),
+ );
+}
+
+export function clearQueuedRightPanelTab(threadKey: string): void {
+ if (queuedTabByThreadKey.delete(threadKey)) {
+ notify();
+ }
+}
+
export function resetRightPanelTabsForTests(): void {
stateByThreadKey.clear();
+ queuedTabByThreadKey.clear();
notify();
}
diff --git a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx
index 399fca6b4..9c5d27c97 100644
--- a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx
+++ b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx
@@ -1,5 +1,5 @@
import { usePullRequestRecords } from "../environments/pullRequests/pullRequestRecordsStore";
-import { scopeProjectRef, scopeThreadRef } from "@threadlines/client-runtime";
+import { scopedThreadKey, scopeProjectRef, scopeThreadRef } from "@threadlines/client-runtime";
import type { PullRequestRef, ScopedThreadRef } from "@threadlines/contracts";
import { resolveThreadWorkingCwd } from "@threadlines/shared/threadCwd";
import { useQuery, useQueryClient } from "@tanstack/react-query";
@@ -28,6 +28,7 @@ import {
import { deriveHostedStaticThreadRouteState } from "./-chatIndexState";
import { type DiffRouteSearch, parseDiffRouteSearch } from "../diffRouteSearch";
import { AgentsPanel } from "../components/chat/AgentsPanel";
+import { ProjectBoardPanel } from "../components/chat/ProjectBoardPanel";
import {
ThreadPullRequestLinkContext,
type ThreadPullRequestLinks,
@@ -87,10 +88,12 @@ import {
autoOpenAgentsTab,
availableRightPanelTabs,
type AgentsAutoOpenEdge,
+ clearQueuedRightPanelTab,
closeRightPanelTab,
focusRightPanelTab,
hideRightPanel,
isRightPanelClosedInSearch,
+ useQueuedRightPanelTab,
useReconciledRightPanelTabs,
moveRightPanelTab,
pullRequestTabSearchParams,
@@ -621,6 +624,7 @@ function ChatThreadRouteView() {
const pullRequestOpen = activeTab === "pullRequest";
const agentsOpen = activeTab === "agents";
const mediaOpen = activeTab === "media";
+ const threadsOpen = activeTab === "threads";
// A published source outlives the navigation for a frame or two, so the rail
// only trusts one that names the thread it is rendering.
const agentsSource =
@@ -664,6 +668,21 @@ function ChatThreadRouteView() {
navigateToTab,
shouldUseDiffSheet,
]);
+ // A tab queued for this thread from outside the route (the Threads tab, the
+ // first time a thread becomes a lead on this device): opened once the thread
+ // can show it. Sheet layouts drop it rather than cover the conversation.
+ const queuedTab = useQueuedRightPanelTab(currentThreadKey);
+ useEffect(() => {
+ if (queuedTab === null || currentThreadKey === null || !availableTabs.includes(queuedTab)) {
+ return;
+ }
+ clearQueuedRightPanelTab(currentThreadKey);
+ if (shouldUseDiffSheet) {
+ return;
+ }
+ focusRightPanelTab(currentThreadKey, queuedTab);
+ navigateToTab(queuedTab);
+ }, [availableTabs, currentThreadKey, navigateToTab, queuedTab, shouldUseDiffSheet]);
// The thread's media, for the launcher's Media row: the same listing the
// Media tab opens on, so the row and the tab agree. Read only while the
// launcher is on screen; a turn landing changes the revision and so the key.
@@ -948,6 +967,34 @@ function ChatThreadRouteView() {
},
[navigate, shouldUseDiffSheet, threadRef],
);
+ // A row of the Threads tab: that thread, with its own Threads tab beside it
+ // so the board stays in view while the user works down it. On a phone the
+ // sheet steps aside so the thread is what shows.
+ const openThreadFromBoard = useCallback(
+ (target: ScopedThreadRef) => {
+ if (!threadRef) {
+ return;
+ }
+ const sameThread =
+ target.environmentId === threadRef.environmentId && target.threadId === threadRef.threadId;
+ if (sameThread) {
+ if (shouldUseDiffSheet) {
+ hideSidebar();
+ }
+ return;
+ }
+ if (!shouldUseDiffSheet) {
+ focusRightPanelTab(scopedThreadKey(target), "threads");
+ }
+ void navigate({
+ to: "/$environmentId/$threadId",
+ params: buildThreadRouteParams(target),
+ search: (previous) =>
+ rightPanelTabSearchParams(previous, shouldUseDiffSheet ? null : "threads"),
+ });
+ },
+ [hideSidebar, navigate, shouldUseDiffSheet, threadRef],
+ );
// Reorder touches only the strip's remembered order; the URL owns the
// active tab, and that does not change here.
const reorderTab = useCallback(
@@ -1058,6 +1105,16 @@ function ChatThreadRouteView() {
) : null}
+ {openTabs.includes("threads") && serverThread ? (
+
Date: Mon, 16 Nov 2026 15:45:52 -0500
Subject: [PATCH 05/11] fix(web): the Threads tab opens on a phone too, and its
badge keeps its keys
The first lead on a device opened the Threads tab only on wide layouts, and
the device's once-only flag was spent either way, so a first lead made on a
narrow window never showed the board. It now opens as the sheet there.
A board row's Enter and Space handler also caught keys from the pull request
badge inside it, so the badge opened the thread instead of its pull request.
The row now answers only its own keys.
---
.../components/ChatView.sidebar.browser.tsx | 49 +++++++++++++++++++
.../src/components/chat/ProjectBoardPanel.tsx | 2 +
.../routes/_chat.$environmentId.$threadId.tsx | 8 ++-
3 files changed, 54 insertions(+), 5 deletions(-)
diff --git a/apps/web/src/components/ChatView.sidebar.browser.tsx b/apps/web/src/components/ChatView.sidebar.browser.tsx
index f622a6636..582be3c2a 100644
--- a/apps/web/src/components/ChatView.sidebar.browser.tsx
+++ b/apps/web/src/components/ChatView.sidebar.browser.tsx
@@ -312,6 +312,55 @@ describe("ChatView (full app): sidebar", () => {
}
});
+ it("opens the Threads tab the first time a thread becomes the lead on this device, as the sheet on a narrow window", async () => {
+ const capabilities = { repositoryIdentity: true, projectLead: true };
+ const mounted = await mountChatView({
+ // Below the inline panel's breakpoint, so the panel is the sheet.
+ viewport: DEFAULT_VIEWPORT,
+ snapshot: createSnapshotForTargetUser({
+ targetMessageId: "msg-user-first-lead" as MessageId,
+ targetText: "first lead",
+ }),
+ configureFixture: (nextFixture) => {
+ nextFixture.serverConfig = {
+ ...nextFixture.serverConfig,
+ environment: { ...nextFixture.serverConfig.environment, capabilities },
+ };
+ nextFixture.welcome = {
+ ...nextFixture.welcome,
+ environment: { ...nextFixture.welcome.environment, capabilities },
+ };
+ },
+ });
+
+ try {
+ const row = await waitForElement(
+ () => document.querySelector(`[data-testid="thread-row-${THREAD_ID}"]`),
+ "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,
+ }),
+ );
+ await page.getByRole("button", { name: "Make this the lead chat", exact: true }).click();
+
+ await vi.waitFor(
+ () => {
+ expect(mounted.router.state.location.search).toMatchObject({ threads: "1" });
+ expect(document.querySelector("[data-project-board='true']")).not.toBeNull();
+ },
+ { timeout: 8_000, interval: 16 },
+ );
+ } 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/chat/ProjectBoardPanel.tsx b/apps/web/src/components/chat/ProjectBoardPanel.tsx
index eaa272922..7d8807077 100644
--- a/apps/web/src/components/chat/ProjectBoardPanel.tsx
+++ b/apps/web/src/components/chat/ProjectBoardPanel.tsx
@@ -337,6 +337,8 @@ const BoardRow = memo(function BoardRow({
)}
onClick={() => onOpenThread(threadRef)}
onKeyDown={(event) => {
+ // The pull request badge inside answers its own keys.
+ if (event.target !== event.currentTarget) return;
if (event.key !== "Enter" && event.key !== " ") return;
event.preventDefault();
onOpenThread(threadRef);
diff --git a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx
index 9c5d27c97..c42dd0f94 100644
--- a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx
+++ b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx
@@ -670,19 +670,17 @@ function ChatThreadRouteView() {
]);
// A tab queued for this thread from outside the route (the Threads tab, the
// first time a thread becomes a lead on this device): opened once the thread
- // can show it. Sheet layouts drop it rather than cover the conversation.
+ // can show it, as the sheet on a phone. It is asked for once per device, so
+ // it is never dropped.
const queuedTab = useQueuedRightPanelTab(currentThreadKey);
useEffect(() => {
if (queuedTab === null || currentThreadKey === null || !availableTabs.includes(queuedTab)) {
return;
}
clearQueuedRightPanelTab(currentThreadKey);
- if (shouldUseDiffSheet) {
- return;
- }
focusRightPanelTab(currentThreadKey, queuedTab);
navigateToTab(queuedTab);
- }, [availableTabs, currentThreadKey, navigateToTab, queuedTab, shouldUseDiffSheet]);
+ }, [availableTabs, currentThreadKey, navigateToTab, queuedTab]);
// The thread's media, for the launcher's Media row: the same listing the
// Media tab opens on, so the row and the tab agree. Read only while the
// launcher is on screen; a turn landing changes the revision and so the key.
From 1337ea004f1bc6453acb6242e6a40c63eba4cee4 Mon Sep 17 00:00:00 2001
From: Badcuban <108198679+badcuban@users.noreply.github.com>
Date: Tue, 17 Nov 2026 12:10:21 -0500
Subject: [PATCH 06/11] fix: passed work keeps the lead's access when handed
on, and known pull requests stay in their repository
A thread working on something the lead chat passed on could still message
its own threads, including one the user had raised above the lead's access,
so the lead's work could run there with more access than the lead has. The
pass's ceiling now stays on the thread (passCeiling, the narrowest of the
passes since the user wrote): sends to a child above it, or on another
computer, are refused until the user writes.
thread_list matched a branch's pull request on owner/name alone, so another
host's or another GitLab group's repository with the same short name and
branch could show up. It now matches on the project remote's host and whole
path.
---
apps/server/src/mcp/threadToolHandlers.ts | 10 +--
.../orchestration/decider.projectLead.test.ts | 52 +++++++++++-
apps/server/src/orchestration/decider.ts | 14 ++--
.../PullRequestObservations.test.ts | 25 ++++++
.../pullRequest/PullRequestObservations.ts | 19 +++--
docs/design/lead-chat.md | 21 +++--
packages/contracts/src/orchestration.ts | 27 ++++--
packages/shared/src/childThreads.ts | 82 +++++++++++++++++--
8 files changed, 205 insertions(+), 45 deletions(-)
diff --git a/apps/server/src/mcp/threadToolHandlers.ts b/apps/server/src/mcp/threadToolHandlers.ts
index 1f0bca210..bc572a18f 100644
--- a/apps/server/src/mcp/threadToolHandlers.ts
+++ b/apps/server/src/mcp/threadToolHandlers.ts
@@ -143,7 +143,7 @@ export interface ThreadToolDeps {
* call to the host (PullRequestObservations.known). Absent: none listed.
*/
readonly knownPullRequests?: (input: {
- readonly repository: string | null;
+ readonly repositoryKey: string | null;
readonly branch: string | null;
readonly urls: ReadonlyArray;
}) => Effect.Effect<
@@ -1547,11 +1547,7 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) {
// Which thread leads the project, and what each listed thread's pull
// requests are as already known here (docs/design/lead-chat.md).
const project = yield* deps.readProject(thread.projectId);
- const identity = project?.repositoryIdentity ?? null;
- const repository =
- identity?.owner !== undefined && identity.name !== undefined
- ? `${identity.owner}/${identity.name}`
- : null;
+ const repositoryKey = project?.repositoryIdentity?.canonicalKey ?? null;
type KnownPullRequest = NonNullable[number];
const pullRequestsOf = (
shell: OrchestrationThreadShell,
@@ -1559,7 +1555,7 @@ export function makeThreadToolHandlers(deps: ThreadToolDeps) {
(deps.knownPullRequests === undefined
? Effect.succeed([])
: deps.knownPullRequests({
- repository,
+ repositoryKey,
branch: shell.branch,
urls: shell.linkedPullRequests.map((linked) => linked.url),
})
diff --git a/apps/server/src/orchestration/decider.projectLead.test.ts b/apps/server/src/orchestration/decider.projectLead.test.ts
index 240025932..63d6a02c5 100644
--- a/apps/server/src/orchestration/decider.projectLead.test.ts
+++ b/apps/server/src/orchestration/decider.projectLead.test.ts
@@ -296,7 +296,55 @@ describe("lead chat passes", () => {
expect(ran.events.some((event) => event.type === "thread.turn-start-requested")).toBe(true);
// Nothing is owed back: no request settles anywhere.
expect(ran.events.some((event) => event.type.startsWith("thread.child-request"))).toBe(false);
- expect(threadIn(ran.model, OTHER).childRequests.startsBlockedByPass).toBe(true);
+ expect(threadIn(ran.model, OTHER).childRequests.passCeiling).toEqual({
+ runtimeMode: "auto-accept-edits",
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ });
+ });
+
+ it("holds what a passed-to thread sends its own threads to the pass's ceiling", async () => {
+ const RAISED = ThreadId.make("raised-child");
+ const ran = (
+ await run(
+ await run(
+ await leadAndHandMade({
+ session: session(OTHER, { status: "ready", activeTurnId: null }),
+ }),
+ pass(),
+ ).then((r) => r.model),
+ sendQueued(PASS_MESSAGE),
+ )
+ ).model;
+ const OTHER_TURN = TurnId.make("other-turn-1");
+ const own = { parentThreadId: OTHER, attachedToParent: true };
+ const working = {
+ ...ran,
+ threads: [
+ ...ran.threads.map((entry) =>
+ entry.id === OTHER
+ ? { ...entry, session: session(OTHER, { activeTurnId: OTHER_TURN }) }
+ : entry,
+ ),
+ // The user raised this one above its parent, and above the lead.
+ thread(RAISED, { ...own, runtimeMode: "full-access" }),
+ thread(CHILD, { ...own, runtimeMode: "approval-required" }),
+ ],
+ };
+ const send = (childThreadId: ThreadId): OrchestrationCommand => ({
+ type: "thread.child.send",
+ commandId: CommandId.make(`send-to-${childThreadId}`),
+ threadId: OTHER,
+ requestId: ChildRequestId.make(`send-to-${childThreadId}`),
+ from: PRIMARY,
+ callerTurnId: OTHER_TURN,
+ childThreadId,
+ childMessageId: MessageId.make(`message-to-${childThreadId}`),
+ text: "Run it with full access.",
+ createdAt: now,
+ });
+ expect(await refusal(working, send(RAISED))).toContain("more access than the lead chat");
+ const within = await run(working, send(CHILD));
+ expect(threadIn(within.model, OTHER).childRequests.open).toHaveLength(1);
});
it("refuses rooms, threads another thread owns, and threads the user stopped", async () => {
@@ -482,7 +530,7 @@ describe("lead chat passes", () => {
),
};
const wrote = (await run(settled, turn("user", { composer: "typed" }))).model;
- expect(threadIn(wrote, OTHER).childRequests.startsBlockedByPass).toBeUndefined();
+ expect(threadIn(wrote, OTHER).childRequests.passCeiling).toBeUndefined();
});
it("starts only the threads the user left checked, and tells the agent which it didn't", async () => {
diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts
index 44efbe15c..04c79fd58 100644
--- a/apps/server/src/orchestration/decider.ts
+++ b/apps/server/src/orchestration/decider.ts
@@ -308,7 +308,7 @@ function resetChildRequestsForUser(
): ReadonlyArray {
const state = thread.childRequests;
const keepsPassBlock = options?.keepsPassBlock === true;
- const liftsBlock = state.startsBlockedByPass === true && !keepsPassBlock;
+ const liftsBlock = state.passCeiling !== undefined && !keepsPassBlock;
return state.startsSinceUser === 0 && state.sendsSinceUser === 0 && !liftsBlock
? []
: [
@@ -3406,10 +3406,12 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
},
]
: [];
- // A lead chat's pass starting its turn: no threads may be started from
- // here until the user writes (docs/design/lead-chat.md, "No fan-out").
+ // A lead chat's pass starting its turn: until the user writes, no
+ // threads may be started from here, and its ceiling holds what this
+ // thread sends on (docs/design/lead-chat.md, "No fan-out").
+ const passCeiling = command.fromThread?.ceiling;
const passStartedEvents: ReadonlyArray =
- command.fromThread?.ceiling !== undefined
+ passCeiling !== undefined
? [
{
...turnBase(),
@@ -3419,6 +3421,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
kind: "started",
messageId: command.message.messageId,
targetThreadId: command.threadId,
+ ceiling: passCeiling,
createdAt: command.createdAt,
},
},
@@ -3608,7 +3611,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
return [
retrySessionEvent,
retryTurnStartRequestedEvent,
- // A lead chat's pass, run again: still no threads started from it.
+ // A lead chat's pass, run again: still held to its ceiling.
...(lastUserMessage.fromThread?.ceiling !== undefined
? [
{
@@ -3624,6 +3627,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
kind: "started" as const,
messageId: lastUserMessage.id,
targetThreadId: command.threadId,
+ ceiling: lastUserMessage.fromThread.ceiling,
createdAt: command.createdAt,
},
},
diff --git a/apps/server/src/pullRequest/PullRequestObservations.test.ts b/apps/server/src/pullRequest/PullRequestObservations.test.ts
index 22a30b2b9..4d824541f 100644
--- a/apps/server/src/pullRequest/PullRequestObservations.test.ts
+++ b/apps/server/src/pullRequest/PullRequestObservations.test.ts
@@ -130,4 +130,29 @@ describe("PullRequestObservations", () => {
assert.strictEqual(first[0]?.number, 7);
}),
);
+
+ it.effect("finds a branch's pull request only in the same repository on the same host", () =>
+ Effect.gen(function* () {
+ const observations = yield* make;
+ const gitlab = (path: string, number: number): PullRequestRead =>
+ read({
+ provider: "gitlab",
+ repository: path,
+ number,
+ url: `https://gitlab.com/${path}/-/merge_requests/${number}`,
+ });
+ yield* observations.observe(Effect.succeed(1), () => [
+ gitlab("org/app", 1),
+ gitlab("org/public/app", 2),
+ read({ number: 3, url: "https://ghe.example.com/org/app/pull/3", repository: "org/app" }),
+ ]);
+ const numbersAt = (repositoryKey: string) =>
+ observations
+ .known({ repositoryKey, branch: "fix-it", urls: [] })
+ .pipe(Effect.map((known) => known.map((entry) => entry.number)));
+ assert.deepStrictEqual(yield* numbersAt("gitlab.com/org/public/app"), [2]);
+ assert.deepStrictEqual(yield* numbersAt("gitlab.com/org/app"), [1]);
+ assert.deepStrictEqual(yield* numbersAt("github.com/org/app"), []);
+ }),
+ );
});
diff --git a/apps/server/src/pullRequest/PullRequestObservations.ts b/apps/server/src/pullRequest/PullRequestObservations.ts
index b34542d40..e260a3049 100644
--- a/apps/server/src/pullRequest/PullRequestObservations.ts
+++ b/apps/server/src/pullRequest/PullRequestObservations.ts
@@ -19,6 +19,7 @@ import type {
PullRequestState,
SourceControlProviderKind,
} from "@threadlines/contracts";
+import { normalizeGitRemoteUrl } from "@threadlines/shared/git";
import { pullRequestIdentityKey } from "@threadlines/shared/sourceControl";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
@@ -169,11 +170,12 @@ export interface PullRequestObservationsShape {
readonly stream: Stream.Stream;
/**
* What is already known about a thread's pull requests, with no call to the
- * host: the one from its branch in `repository` (`owner/name`), and the ones
- * at `urls`. Pull requests nobody has read yet are left out.
+ * host: the one from its branch in the repository at `repositoryKey` (its
+ * remote's host and whole path, RepositoryIdentity.canonicalKey), and the
+ * ones at `urls`. Pull requests nobody has read yet are left out.
*/
readonly known: (input: {
- readonly repository: string | null;
+ readonly repositoryKey: string | null;
readonly branch: string | null;
readonly urls: ReadonlyArray;
}) => Effect.Effect>;
@@ -252,15 +254,18 @@ export const make = Effect.gen(function* () {
const known: PullRequestObservationsShape["known"] = (input) =>
Ref.get(state).pipe(
Effect.map((current) => {
- const repository = input.repository?.toLowerCase() ?? null;
+ // Matched on the address, host and whole path, so another host's or
+ // another group's `owner/name` with the same branch never answers.
+ const repositoryPrefix =
+ input.repositoryKey === null ? null : `${input.repositoryKey.toLowerCase()}/`;
const urls = new Set(input.urls);
return Array.from(current.records.values(), (entry) => entry.observation).filter(
(observation) =>
urls.has(observation.url) ||
- (repository !== null &&
+ (repositoryPrefix !== null &&
input.branch !== null &&
- observation.repository.toLowerCase() === repository &&
- observation.headBranch === input.branch),
+ observation.headBranch === input.branch &&
+ normalizeGitRemoteUrl(observation.url).startsWith(repositoryPrefix)),
);
}),
);
diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md
index ff20ca45d..427ec1c9b 100644
--- a/docs/design/lead-chat.md
+++ b/docs/design/lead-chat.md
@@ -225,7 +225,10 @@ coordinate it.
Without this, one message in a lead on Automatic could start threads through every
thread it passes to. It is a fact on the thread, not on the turn, so a retry or a
continue of that work cannot shed it. `thread_send` to that thread's own children
- still works.
+ still works, held to the pass's ceiling: a child with more access than the lead,
+ or one on another computer, is refused ("Do the work here, or tell the user, who
+ can send it there."). The check is at send time; after that, only the user can
+ raise a child's access.
- A pass counts against the lead's sends per user message.
- What the target does with it is the target's business: the user's own queued
messages go first; Stop, taking the message off the queue, revert and archive work
@@ -234,7 +237,9 @@ coordinate it.
a thread it did not start.
- **`thread_list`** summaries gain optional fields: `lead` (true on the lead),
`lastActivityAt`, `pullRequests` (`number`, `url`, and `state` when the server already
- holds an observation; no network call). Every agent sees which thread is the lead.
+ holds an observation; no network call; a branch's pull request is matched on the
+ project remote's host and whole path, never on `owner/name` alone). Every agent sees
+ which thread is the lead.
- **Limits in a lead:** 10 starts and 20 sends per user message (5 and 10 elsewhere);
5 per call stays. A scheduled or event run into the lead already counts as the user
writing (`thread.follow-up.submit` resets the counters), so a lead fed by an event
@@ -299,11 +304,13 @@ the user. Your reply stays in this thread, where the user reads it."
emits `turn-start-requested` for a stored message (`thread.turn.start`,
`thread.follow-up.send-queued`, `thread.turn.retry`, `thread.turn.resend`), reading
the ceiling from the message itself.
-- No fan-out is state: optional `startsBlockedByPass?: true` on the target's
- `OrchestrationChildRequestState`, set by the decision that starts a pass's turn and
- cleared by `thread.child-requests-reset` (the user wrote). `childStartRefusal` reads
- it; `childSendRefusal` does not (both call `callerRefusal`, so the rule cannot live
- there).
+- No fan-out is state: optional `passCeiling` on the target's
+ `OrchestrationChildRequestState`, the narrowest ceiling of the passes that started
+ turns there since the user wrote. The decision that starts a pass's turn sets it
+ (its `started` record carries the ceiling); `thread.child-requests-reset` clears it
+ (the user wrote). `childStartRefusal` refuses while it is set; `childSendRefusal`
+ refuses a child above it or on another computer (both call `callerRefusal`, so the
+ rule cannot live there).
- Built (piece 2): the lead's send count, the refusal note and the "started" mark ride
one event, `thread.lead-pass-recorded` (`kind`: `sent` on the lead, `refused` with
the note on the lead, `started` on the target), so nothing settles a request that
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index 255d40261..d90d9c7c9 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -612,6 +612,16 @@ export type AgentInvitesMode = typeof AgentInvitesMode.Type;
export const AgentThreadsMode = Schema.Literals(["off", "ask", "auto"]);
export type AgentThreadsMode = typeof AgentThreadsMode.Type;
+/**
+ * The most a lead chat's pass may run with (docs/design/lead-chat.md,
+ * "Access"): the lead's access and interaction mode when it passed it.
+ */
+export const LeadPassCeiling = Schema.Struct({
+ runtimeMode: RuntimeMode,
+ interactionMode: ProviderInteractionMode,
+});
+export type LeadPassCeiling = typeof LeadPassCeiling.Type;
+
/**
* A message that crossed between a thread and one it started: a `request` its
* parent's agent wrote into the child, or a `report`, the child's answer
@@ -645,12 +655,7 @@ export const ThreadMessageOrigin = Schema.Struct({
* Nothing is owed back for a pass: no request is recorded on the lead.
* Only a pass carries it.
*/
- ceiling: Schema.optional(
- Schema.Struct({
- runtimeMode: RuntimeMode,
- interactionMode: ProviderInteractionMode,
- }),
- ),
+ ceiling: Schema.optional(LeadPassCeiling),
/** A pass: the lead's agent that passed it (a room's agent), for its notes. Absent: its own. */
passedBy: Schema.optional(ThreadParticipantId),
});
@@ -2663,10 +2668,12 @@ export const OrchestrationChildRequestState = Schema.Struct({
remoteCancels: Schema.optional(Schema.Array(RemoteChildCancel)),
/**
* A message the lead chat passed on started a turn here since the user
- * last wrote (docs/design/lead-chat.md, "No fan-out"): this thread's agents
- * can't start threads until the user writes here. Absent: they can.
+ * last wrote (docs/design/lead-chat.md, "No fan-out"): the narrowest
+ * ceiling of those passes. Until the user writes here, this thread's agents
+ * can't start threads, and message only their own threads that are within
+ * it on this computer. Absent: no pass holds them.
*/
- startsBlockedByPass: Schema.optional(Schema.Literal(true)),
+ passCeiling: Schema.optional(LeadPassCeiling),
});
export type OrchestrationChildRequestState = typeof OrchestrationChildRequestState.Type;
@@ -5910,6 +5917,8 @@ export const ThreadLeadPassRecordedPayload = Schema.Struct({
messageId: MessageId,
targetThreadId: ThreadId,
note: Schema.optional(ChildRequestNote),
+ /** `started`: the pass's ceiling, which now holds the target (`passCeiling`). */
+ ceiling: Schema.optional(LeadPassCeiling),
createdAt: IsoDateTime,
});
diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts
index 14bb1a8a5..97b5b2dc7 100644
--- a/packages/shared/src/childThreads.ts
+++ b/packages/shared/src/childThreads.ts
@@ -18,6 +18,7 @@ import {
type RemoteChildCancel,
type RemoteChildRequest,
type FamilyRemoteChild,
+ type LeadPassCeiling,
type RemoteChildStart,
type RemoteChildThread,
type RemoteThreadFiling,
@@ -30,7 +31,7 @@ import {
type TurnId,
} from "@threadlines/contracts";
-import { exceedsRuntimeMode } from "./runtimeMode.ts";
+import { exceedsRuntimeMode, saferRuntimeMode } from "./runtimeMode.ts";
import { isRoomThread } from "./threadParticipants.ts";
/** What the rules read from a thread an agent works in. */
@@ -134,8 +135,9 @@ export function childStartRefusal(
}
// No fan-out (docs/design/lead-chat.md): one message in a lead chat must
// not start threads through every thread it is passed to. Messaging this
- // thread's own children still works (childSendRefusal doesn't check it).
- if (thread.childRequests.startsBlockedByPass === true) {
+ // thread's own children still works, within the pass's ceiling
+ // (childSendRefusal).
+ if (thread.childRequests.passCeiling !== undefined) {
return {
outcome: "not_allowed",
detail:
@@ -159,7 +161,11 @@ export function childStartRefusal(
return null;
}
-/** Why sending a message to `childThreadId` is refused, or null. */
+/**
+ * Why sending a message to `childThreadId` is refused, or null. `child`'s
+ * modes are absent for a thread on another computer, whose access this
+ * computer can't hold to a pass's ceiling.
+ */
export function childSendRefusal(
thread: ChildRequestCaller,
child: {
@@ -167,6 +173,8 @@ export function childSendRefusal(
readonly parentThreadId: ThreadId | null;
readonly attachedToParent: boolean;
readonly archivedAt: string | null;
+ readonly runtimeMode?: RuntimeMode | undefined;
+ readonly interactionMode?: ProviderInteractionMode | undefined;
} | null,
input: {
readonly from: RoomAgentRef;
@@ -183,6 +191,30 @@ export function childSendRefusal(
if (ownRefusal !== null) {
return ownRefusal;
}
+ // Work the lead chat passed on keeps its ceiling when it is handed down:
+ // a pass never reaches a thread with more access than the lead's.
+ const passCeiling = thread.childRequests.passCeiling;
+ if (passCeiling !== undefined && child !== null) {
+ if (child.runtimeMode === undefined || child.interactionMode === undefined) {
+ return {
+ outcome: "not_allowed",
+ detail:
+ "This thread is working on something the lead chat passed on, and that thread is on another computer. Do the work here, or tell the user, who can send it there.",
+ };
+ }
+ if (
+ !withinModeCeiling(
+ { runtimeMode: child.runtimeMode, interactionMode: child.interactionMode },
+ passCeiling,
+ )
+ ) {
+ return {
+ outcome: "not_allowed",
+ detail:
+ "This thread is working on something the lead chat passed on, and that thread has more access than the lead chat. Do the work here, or tell the user, who can send it there.",
+ };
+ }
+ }
const limit = childRequestLimits({ isLead: input.isLead === true }).sends;
if (thread.childRequests.sendsSinceUser >= limit) {
return {
@@ -270,6 +302,34 @@ export function withinModeCeiling(
);
}
+/** The narrower of two ceilings: no more access than either allows. */
+export function narrowerModeCeiling(
+ left: LeadPassCeiling | undefined,
+ right: LeadPassCeiling,
+): LeadPassCeiling {
+ if (left === undefined) return right;
+ const narrower = {
+ runtimeMode: saferRuntimeMode(left.runtimeMode, right.runtimeMode),
+ interactionMode:
+ left.interactionMode === "plan" || right.interactionMode === "plan"
+ ? ("plan" as const)
+ : ("default" as const),
+ };
+ return narrower.runtimeMode === left.runtimeMode &&
+ narrower.interactionMode === left.interactionMode
+ ? left
+ : narrower;
+}
+
+/**
+ * What a `started` record without a ceiling holds the thread to: the least
+ * access there is. Every decision that records one sends the pass's ceiling.
+ */
+const SAFEST_PASS_CEILING: LeadPassCeiling = {
+ runtimeMode: "approval-required",
+ interactionMode: "plan",
+};
+
/** What the pass rules read from the thread a lead chat passes a message to. */
export interface LeadPassTarget {
readonly id: ThreadId;
@@ -687,11 +747,11 @@ export const childRequestStateOn = {
state: OrchestrationChildRequestState,
options?: { readonly keepsPassBlock?: boolean | undefined },
): OrchestrationChildRequestState => {
- const liftsBlock = state.startsBlockedByPass === true && options?.keepsPassBlock !== true;
+ const liftsBlock = state.passCeiling !== undefined && options?.keepsPassBlock !== true;
if (state.startsSinceUser === 0 && state.sendsSinceUser === 0 && !liftsBlock) {
return state;
}
- const { startsBlockedByPass: _block, ...rest } = state;
+ const { passCeiling: _block, ...rest } = state;
return {
...(liftsBlock ? rest : state),
startsSinceUser: 0,
@@ -704,13 +764,19 @@ export const childRequestStateOn = {
pass: {
readonly kind: "sent" | "refused" | "started";
readonly note?: ChildRequestNote | undefined;
+ readonly ceiling?: LeadPassCeiling | undefined;
},
): OrchestrationChildRequestState => {
switch (pass.kind) {
case "sent":
return { ...state, sendsSinceUser: state.sendsSinceUser + 1 };
- case "started":
- return state.startsBlockedByPass === true ? state : { ...state, startsBlockedByPass: true };
+ case "started": {
+ const passCeiling = narrowerModeCeiling(
+ state.passCeiling,
+ pass.ceiling ?? SAFEST_PASS_CEILING,
+ );
+ return passCeiling === state.passCeiling ? state : { ...state, passCeiling };
+ }
case "refused": {
const note = pass.note;
return note === undefined ||
From c30e6b841d3ceae2a000cd96eda1a0423098367e Mon Sep 17 00:00:00 2001
From: Badcuban <108198679+badcuban@users.noreply.github.com>
Date: Tue, 17 Nov 2026 12:28:20 -0500
Subject: [PATCH 07/11] fix: a lead chat's pass is checked against its ceiling
again right before it runs
The user can raise a thread's access after the decider let a queued pass
through but before the turn reaches the agent. The provider layer now reads
the ceiling from the stored message and refuses the turn when the thread or
its live runtime is above it, as it already does for outside agents. This
covers sent, queued, retried and resent passes.
A new agent's history (the hand-off context seed) also leaves out messages
still waiting in the queue: no agent was sent them yet. A message taken
back or refused at that last check still reaches history; recording
delivery on the message is left open.
---
.../Layers/ProviderCommandReactor.test.ts | 71 +++++++++++++++++++
.../Layers/ProviderCommandReactor.ts | 47 +++++++++++-
.../ThreadContextSeedBuilder.test.ts | 21 ++++++
.../contextSeed/ThreadContextSeedBuilder.ts | 8 +++
docs/design/lead-chat.md | 9 ++-
5 files changed, 154 insertions(+), 2 deletions(-)
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
index af64a4f41..a6ab2c17c 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
@@ -3781,6 +3781,77 @@ describe("ProviderCommandReactor", () => {
});
expect(harness.sendTurn).not.toHaveBeenCalled();
});
+
+ it("doesn't send a lead chat's pass the user raised above its ceiling after it was accepted", async () => {
+ const threadId = ThreadId.make("passed-to-thread");
+ let hold: Deferred.Deferred | null = null;
+ const harness = await createHarness({
+ beforeThreadRead: (id) =>
+ id === threadId && hold !== null ? Deferred.await(hold) : Effect.void,
+ });
+ await Effect.runPromise(
+ harness.engine.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("cmd-create-passed-to"),
+ threadId,
+ projectId: asProjectId("project-1"),
+ title: "Fix the flaky test",
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ branch: null,
+ worktreePath: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ }),
+ );
+ hold = Effect.runSync(Deferred.make());
+ await Effect.runPromise(
+ harness.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make("cmd-pass-turn"),
+ threadId,
+ message: {
+ messageId: asMessageId("pass-message"),
+ role: "user",
+ text: "Run the migration",
+ attachments: [],
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ fromThread: {
+ threadId: ThreadId.make("lead-thread"),
+ requestId: ChildRequestId.make("pass-request"),
+ kind: "request",
+ ceiling: {
+ runtimeMode: "approval-required",
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ },
+ },
+ createdAt: "2026-01-01T00:00:01.000Z",
+ }),
+ );
+ await Effect.runPromise(
+ harness.engine.dispatch({
+ type: "thread.runtime-mode.set",
+ commandId: CommandId.make("cmd-raise-passed-to"),
+ threadId,
+ runtimeMode: "full-access",
+ createdAt: "2026-01-01T00:00:02.000Z",
+ }),
+ );
+ Effect.runSync(Deferred.succeed(hold, undefined));
+ hold = null;
+
+ const failure = async () =>
+ (await harness.readModel()).threads
+ .find((entry) => entry.id === threadId)
+ ?.activities.find((activity) => activity.kind === "provider.turn.start.failed");
+ await waitFor(async () => (await failure()) !== undefined);
+ expect(await failure()).toMatchObject({
+ payload: { detail: expect.stringContaining("more access than the lead chat") },
+ });
+ expect(harness.sendTurn).not.toHaveBeenCalled();
+ });
});
it("picks up the room tools at the next turn, never in the middle of one", async () => {
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
index fb0646c8f..9e117e525 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
@@ -33,6 +33,7 @@ import {
type OutsideAgentConnectionId,
type OutsideAgentRef,
type OutsideTurnOrigin,
+ type LeadPassCeiling,
type RuntimeMode,
ThreadAccessRaiseDeferredActivityKind,
type ThreadAccessRaiseDeferredPayload,
@@ -51,7 +52,7 @@ import {
import { renderThreadContextSeed, withContextSeedPreamble } from "@threadlines/shared/contextSeed";
import { LEAD_WITHOUT_TOOLS_TEXT, leadRoleText } from "@threadlines/shared/projectLead";
import { agentInvitesMode, agentThreadsMode } from "@threadlines/shared/serverSettings";
-import { notesFor, remoteChildOf } from "@threadlines/shared/childThreads";
+import { notesFor, remoteChildOf, withinModeCeiling } from "@threadlines/shared/childThreads";
import { settingsChangeNotesFor } from "@threadlines/shared/settingsChangeState";
import { isAgentOrigin } from "@threadlines/shared/roomAgentRequests";
import { exceedsRuntimeMode, saferRuntimeMode } from "@threadlines/shared/runtimeMode";
@@ -222,6 +223,10 @@ export interface ForkTurnBoundary {
readonly lastTurnId?: TurnId;
}
+/** Why a lead chat's pass did not go to the agent: the thread's access went above its ceiling. */
+const PASS_ABOVE_CEILING_DETAIL =
+ "This message the lead chat passed on wasn't sent: this thread has more access than the lead chat now. Send it yourself to run it.";
+
/** One ensure call's launch mark: its generation and instance, once marked. */
interface SessionLaunch {
generation: number | null;
@@ -252,6 +257,13 @@ interface EnsureSessionOptions {
* on the same read of the thread the session starts from.
*/
readonly outsideCeiling?: OutsideTurnOrigin;
+ /**
+ * The turn is a lead chat's pass (docs/design/lead-chat.md, "Access"): it
+ * runs only while the thread is within the pass's ceiling, checked on the
+ * same read of the thread the session starts from, since the user may have
+ * raised its access after the decider let the pass through.
+ */
+ readonly passCeiling?: LeadPassCeiling;
/**
* A turn that isn't from outside: an agent outside text reached
* (OrchestrationOutsideWork) starts fresh for it, a new runtime with a
@@ -1334,6 +1346,14 @@ const make = Effect.gen(function* () {
detail: `This message from ${outsideCeiling.name} wasn't sent: the thread's access was raised above what it may use.`,
});
}
+ const passCeiling = options?.passCeiling;
+ if (passCeiling !== undefined && !withinModeCeiling(thread, passCeiling)) {
+ return yield* new ProviderAdapterRequestError({
+ provider: providerErrorLabel(undefined),
+ method: "thread.turn.start",
+ detail: PASS_ABOVE_CEILING_DETAIL,
+ });
+ }
const sessionKey = participantSessionKey(threadId, participantId);
const shedsOutsideWork =
options?.shedOutsideWork === true &&
@@ -2348,6 +2368,11 @@ const make = Effect.gen(function* () {
}
const sessionKey = participantSessionKey(input.threadId, input.participantId);
+ // Read from the stored message, which keeps it for good: a retry or a
+ // resend of a pass carries no origin on its turn.
+ const passCeiling =
+ thread.messages.find((message) => message.id === input.messageId)?.fromThread?.ceiling ??
+ input.fromThread?.ceiling;
const ensured = yield* ensureSessionForThread(input.threadId, input.createdAt, {
participantId: input.participantId,
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
@@ -2355,6 +2380,7 @@ const make = Effect.gen(function* () {
preservePendingTurnStartup: true,
...(forkFrom !== undefined ? { forkFrom } : {}),
...(input.fromOutside !== undefined ? { outsideCeiling: input.fromOutside } : {}),
+ ...(passCeiling !== undefined ? { passCeiling } : {}),
...(input.sentByPerson === true && input.fromOutside === undefined
? { shedOutsideWork: true }
: {}),
@@ -2380,6 +2406,25 @@ const make = Effect.gen(function* () {
detail: `This message from ${input.fromOutside.name} wasn't sent: the agent here still runs with more access than it may use.`,
});
}
+ // A pass goes only to a runtime within its ceiling, in the mode it runs.
+ if (
+ passCeiling !== undefined &&
+ ((activeSession !== undefined &&
+ exceedsRuntimeMode(activeSession.runtimeMode, passCeiling.runtimeMode)) ||
+ !withinModeCeiling(
+ {
+ runtimeMode: thread.runtimeMode,
+ interactionMode: input.interactionMode ?? thread.interactionMode,
+ },
+ passCeiling,
+ ))
+ ) {
+ return yield* new ProviderAdapterRequestError({
+ provider: providerErrorLabel(activeSession?.provider),
+ method: "thread.turn.start",
+ detail: PASS_ABOVE_CEILING_DETAIL,
+ });
+ }
// In a room, what the other agents said and changed since this agent's
// conversation was last caught up. Built now, from the thread as it stands
// when the turn is sent; the cursor is only kept for the conversation it
diff --git a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts
index efcb2081c..d0f3e37fe 100644
--- a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts
+++ b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts
@@ -196,6 +196,27 @@ describe("ThreadContextSeedBuilder", () => {
expect(value.entries.map((entry) => entry.text)).toEqual(["previous context"]);
});
+ it("leaves out messages still waiting in the queue: no agent was sent them yet", async () => {
+ const thread = {
+ ...fakeThread(
+ [
+ { id: "sent", role: "user", text: "ran earlier", createdAt: "2026-01-01T00:00:00Z" },
+ {
+ id: "queued-pass",
+ role: "user",
+ text: "passed on, waiting",
+ createdAt: "2026-01-01T00:00:01Z",
+ },
+ { id: "current", role: "user", text: "switch now", createdAt: "2026-01-01T00:00:03Z" },
+ ],
+ [],
+ ),
+ queuedFollowUps: [{ messageId: "queued-pass" }],
+ } as unknown as OrchestrationThread;
+ const seed = await build({ thread, excludeMessageId: "current" });
+ expect(Option.getOrThrow(seed).entries.map((entry) => entry.text)).toEqual(["ran earlier"]);
+ });
+
it("returns a workspace-only seed when the thread detail read fails", async () => {
const seed = await build({
thread: null,
diff --git a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts
index 00e01db5f..58d790a9b 100644
--- a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts
+++ b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts
@@ -115,6 +115,8 @@ function buildEntries(input: {
readonly createdAt: string;
}>;
readonly excludeMessageId?: string | undefined;
+ /** Messages still waiting in the queue: no agent was sent them yet. */
+ readonly queuedMessageIds?: ReadonlySet | undefined;
}): ReadonlyArray {
const items: Array<{ readonly createdAt: string; readonly entry: ThreadContextSeedEntry }> = [];
@@ -122,6 +124,11 @@ function buildEntries(input: {
if (message.id !== undefined && message.id === input.excludeMessageId) {
continue;
}
+ // An agent's or another thread's message is written into the chat when it
+ // is queued, before it runs: one still waiting was sent to no agent yet.
+ if (message.id !== undefined && input.queuedMessageIds?.has(message.id) === true) {
+ continue;
+ }
const attached = (message.attachments ?? []).map((attachment) => attachment.name);
const text = [
message.text.trim(),
@@ -191,6 +198,7 @@ export const makeThreadContextSeedBuilder = (deps: {
messages: thread.messages,
activities: thread.activities,
excludeMessageId: input.excludeMessageId,
+ queuedMessageIds: new Set((thread.queuedFollowUps ?? []).map((queued) => queued.messageId)),
});
if (entries.length === 0 && pointer === undefined) {
diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md
index 427ec1c9b..3ba23c890 100644
--- a/docs/design/lead-chat.md
+++ b/docs/design/lead-chat.md
@@ -217,7 +217,14 @@ coordinate it.
without passing through either, decider.ts ~3350). If the target then has more
access than the ceiling (`withinModeCeiling`), the message does not run: one line
in the target ("Not run: this thread has more access than the lead chat"), and a
- note to the lead on its next turn. A retry by the user is refused the same way,
+ note to the lead on its next turn. The provider layer checks the ceiling once more
+ right before the turn goes to the agent (the user may raise access after the
+ decision), against the thread and the live runtime, as it does for outside agents;
+ a pass refused there fails its turn with a line saying so. A pass still waiting in
+ the queue is not part of the history a new agent is given. Open: a pass taken
+ back, or refused at that last check, stays in the chat and can still reach a later
+ agent's history (hand-off seed, room catch-up), since nothing records that it
+ never ran. 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
From fdb3039c488864c6c1d7abe299f1a5957d550c27 Mon Sep 17 00:00:00 2001
From: Badcuban <108198679+badcuban@users.noreply.github.com>
Date: Tue, 17 Nov 2026 13:06:56 -0500
Subject: [PATCH 08/11] fix: a lead chat's pass that never ran is marked not
sent and stays out of every agent's history
A pass taken back at the queue, taken off it by the user, or refused at
the provider layer's last ceiling check stayed in the chat as if sent. A
later agent (after a provider switch, a fork, or joining a room) could
then read it as history while running with more access than the lead.
Such a pass is now OrchestrationMessage.notSent: the shared unqueue fold
marks a pass taken back, and the reactor's last-check refusal dispatches
thread.lead-pass.not-run, which marks it, writes the line in the thread
and the lead's note. One shared rule, reachedAgent (not notSent, not
still queued), filters the hand-off seed, a fork's context and the room
catch-up note. thread_read and room_history keep the message, labelled
notSent. A notSent message is never retried or resent. On screen the
pass says Not sent.
---
apps/server/src/mcp/roomHistory.ts | 3 +
.../server/src/mcp/threadToolHandlers.test.ts | 23 +++++-
.../Layers/ProjectionPipeline.ts | 20 +++++-
.../Layers/ProviderCommandReactor.test.ts | 6 ++
.../Layers/ProviderCommandReactor.ts | 36 +++++++---
apps/server/src/orchestration/Normalizer.ts | 10 +--
.../orchestration/decider.projectLead.test.ts | 71 +++++++++++++++++++
apps/server/src/orchestration/decider.ts | 71 +++++++++++++++++--
apps/server/src/orchestration/projector.ts | 23 ++++--
.../src/orchestration/roomCatchUp.test.ts | 34 +++++++++
apps/server/src/orchestration/roomCatchUp.ts | 8 ++-
.../ThreadContextSeedBuilder.test.ts | 29 +++++---
.../contextSeed/ThreadContextSeedBuilder.ts | 16 +++--
apps/server/src/threads/threadOperations.ts | 1 +
.../src/components/chat/MessagesTimeline.tsx | 11 ++-
apps/web/src/store.ts | 16 ++++-
apps/web/src/types.ts | 2 +-
docs/design/lead-chat.md | 14 ++--
packages/contracts/src/orchestration.ts | 31 +++++++-
packages/contracts/src/peerRpc.ts | 2 +
packages/shared/src/childThreads.ts | 5 +-
packages/shared/src/messageAuthor.ts | 20 ++++++
packages/shared/src/roomAgentRequests.ts | 33 ++++++---
23 files changed, 417 insertions(+), 68 deletions(-)
diff --git a/apps/server/src/mcp/roomHistory.ts b/apps/server/src/mcp/roomHistory.ts
index 3e77ccadf..24dd2b09a 100644
--- a/apps/server/src/mcp/roomHistory.ts
+++ b/apps/server/src/mcp/roomHistory.ts
@@ -41,6 +41,8 @@ export interface RoomHistoryEntry {
readonly text: string;
readonly clipped?: boolean;
readonly streaming?: boolean;
+ /** It never reached the agent (OrchestrationMessage.notSent): shown, never acted on. */
+ readonly notSent?: boolean;
readonly attachments?: ReadonlyArray;
}
@@ -75,6 +77,7 @@ function labelMessage(
...(message.requestKind !== undefined ? { requestKind: message.requestKind } : {}),
...(onTheSide ? { onTheSide: true } : {}),
...(message.streaming ? { streaming: true } : {}),
+ ...(message.notSent === true ? { notSent: true } : {}),
...(message.attachments !== undefined && message.attachments.length > 0
? {
attachments: message.attachments.map((attachment) => ({
diff --git a/apps/server/src/mcp/threadToolHandlers.test.ts b/apps/server/src/mcp/threadToolHandlers.test.ts
index d928a9777..34685c635 100644
--- a/apps/server/src/mcp/threadToolHandlers.test.ts
+++ b/apps/server/src/mcp/threadToolHandlers.test.ts
@@ -992,6 +992,18 @@ describe("thread_read", () => {
}),
message({ eventSequence: 2, text: "Also look at the index." }),
message({ eventSequence: 3, role: "assistant", text: "It is safe." }),
+ // A lead chat's pass that never ran: shown, labelled.
+ message({
+ eventSequence: 4,
+ text: "Run the migration.",
+ notSent: true,
+ fromThread: {
+ threadId: PARENT,
+ requestId: "request-2" as never,
+ kind: "request",
+ ceiling: { runtimeMode: "approval-required", interactionMode: "default" },
+ },
+ }),
],
});
const tools = yield* makeTools({ others: [child] });
@@ -1001,15 +1013,22 @@ describe("thread_read", () => {
["thread_request", `Request from thread "Parent" (${PARENT})`],
["user", "User"],
["agent", "GPT-6 Astra"],
+ ["thread_request", `Request from thread "Parent" (${PARENT})`],
+ ]);
+ expect(result.messages.map((entry) => entry.notSent ?? false)).toEqual([
+ false,
+ false,
+ false,
+ true,
]);
expect(result.thread).toMatchObject({ threadId: CHILD, startedBy: "you", attached: true });
- expect(result.next).toBe(3);
+ expect(result.next).toBe(4);
const later = yield* tools.handlers.thread_read(mainCaller(), {
threadId: CHILD,
after: 2,
});
- expect(later.messages.map((entry) => entry.sequence)).toEqual([3]);
+ expect(later.messages.map((entry) => entry.sequence)).toEqual([3, 4]);
}),
);
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
index ad7aff4c5..90691043b 100644
--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
@@ -1523,16 +1523,34 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
{ ...message.value, id: message.value.messageId },
event.payload,
);
- if (marked.requestOutcome !== message.value.requestOutcome) {
+ if (
+ marked.requestOutcome !== message.value.requestOutcome ||
+ marked.notSent !== message.value.notSent
+ ) {
yield* projectionThreadMessageRepository.upsert({
...message.value,
requestOutcome: marked.requestOutcome,
+ ...(marked.notSent === true ? { notSent: true as const } : {}),
});
}
}
return;
}
+ // A lead chat's pass refused right before it reached the agent.
+ case "thread.lead-pass-recorded": {
+ if (event.payload.kind !== "not-run") {
+ return;
+ }
+ const message = yield* projectionThreadMessageRepository.getByMessageId({
+ messageId: event.payload.messageId,
+ });
+ if (Option.isSome(message) && message.value.notSent !== true) {
+ yield* projectionThreadMessageRepository.upsert({ ...message.value, notSent: true });
+ }
+ return;
+ }
+
// A continue the user's own message overtook never reached the agent.
case "thread.continue-at-reset-skipped": {
const message = yield* projectionThreadMessageRepository.getByMessageId({
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
index a6ab2c17c..00b16a0aa 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
@@ -3851,6 +3851,12 @@ describe("ProviderCommandReactor", () => {
payload: { detail: expect.stringContaining("more access than the lead chat") },
});
expect(harness.sendTurn).not.toHaveBeenCalled();
+ // It never reached the agent, so no history will carry it.
+ const passMessage = async () =>
+ (await harness.readModel()).threads
+ .find((entry) => entry.id === threadId)
+ ?.messages.find((entry) => entry.id === asMessageId("pass-message"));
+ await waitFor(async () => (await passMessage())?.notSent === true);
});
});
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
index 9e117e525..f396bfdb5 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
@@ -3120,13 +3120,33 @@ const make = Effect.gen(function* () {
});
}).pipe(Effect.ignoreCause({ log: true }));
+ // A lead chat's pass refused at the last check never reached the agent:
+ // the decider marks it so no history carries it, and the lead hears.
+ const markPassNotRun = (detail: string) =>
+ detail.includes(PASS_ABOVE_CEILING_DETAIL)
+ ? Effect.gen(function* () {
+ yield* orchestrationEngine.dispatch({
+ type: "thread.lead-pass.not-run",
+ commandId: serverCommandId("lead-pass-not-run"),
+ threadId: event.payload.threadId,
+ messageId: event.payload.messageId,
+ createdAt: yield* nowIso,
+ });
+ }).pipe(Effect.ignoreCause({ log: true }))
+ : Effect.void;
+
+ // What else a turn that could not start ends: its hand-off, its pass.
+ const afterFailedStart = (cause: Cause.Cause) =>
+ Cause.hasInterruptsOnly(cause)
+ ? Effect.void
+ : Effect.andThen(
+ failHandOffForFailedStart(formatFailureDetail(cause)),
+ markPassNotRun(formatFailureDetail(cause)),
+ );
+
const recoverTurnStartFailure = (cause: Cause.Cause) =>
handleTurnStartFailure(cause).pipe(
- Effect.andThen(
- Cause.hasInterruptsOnly(cause)
- ? Effect.void
- : failHandOffForFailedStart(formatFailureDetail(cause)),
- ),
+ Effect.andThen(afterFailedStart(cause)),
Effect.catchCause((recoveryCause) =>
Effect.logWarning("provider command reactor failed to recover turn start failure", {
eventType: event.type,
@@ -3360,11 +3380,7 @@ const make = Effect.gen(function* () {
Effect.map(Option.some),
Effect.catchCause((cause) =>
handleTurnStartFailure(cause).pipe(
- Effect.andThen(
- Cause.hasInterruptsOnly(cause)
- ? Effect.void
- : failHandOffForFailedStart(formatFailureDetail(cause)),
- ),
+ Effect.andThen(afterFailedStart(cause)),
Effect.as(Option.none()),
),
),
diff --git a/apps/server/src/orchestration/Normalizer.ts b/apps/server/src/orchestration/Normalizer.ts
index 22cebb3a8..a02716a21 100644
--- a/apps/server/src/orchestration/Normalizer.ts
+++ b/apps/server/src/orchestration/Normalizer.ts
@@ -21,7 +21,7 @@ import {
withContextSeedPreamble,
} from "@threadlines/shared/contextSeed";
import { agentInvitesMode, agentThreadsMode } from "@threadlines/shared/serverSettings";
-import { transcriptAuthor } from "@threadlines/shared/messageAuthor";
+import { reachedAgent, transcriptAuthor } from "@threadlines/shared/messageAuthor";
import { formatForkSourceExcerpt, truncate } from "@threadlines/shared/String";
import { createAttachmentId, resolveAttachmentPath } from "../attachmentStore.ts";
@@ -276,10 +276,10 @@ export const normalizeDispatchCommand = (command: ClientOrchestrationCommand) =>
// context-seed fallback so the provider never sees both the old and the
// edited instruction. Assistant/system anchors still carry the selected
// message as background before the new continuation instruction.
- const sourceMessages = sourceThread.messages.slice(
- 0,
- replacesUserPrompt ? selectedIndex : selectedIndex + 1,
- );
+ // Only what an agent was given: a pass that never ran stays out.
+ const sourceMessages = sourceThread.messages
+ .slice(0, replacesUserPrompt ? selectedIndex : selectedIndex + 1)
+ .filter((message) => reachedAgent(message, sourceThread));
const entries = [
...sourceMessages.map((message) => ({
kind: "message" as const,
diff --git a/apps/server/src/orchestration/decider.projectLead.test.ts b/apps/server/src/orchestration/decider.projectLead.test.ts
index 63d6a02c5..b07506f1f 100644
--- a/apps/server/src/orchestration/decider.projectLead.test.ts
+++ b/apps/server/src/orchestration/decider.projectLead.test.ts
@@ -397,6 +397,77 @@ describe("lead chat passes", () => {
true,
);
expect(threadIn(sent.model, LEAD).childRequests.pendingNotes[0]?.text).toContain("did not run");
+ expect(target.messages.find((entry) => entry.id === PASS_MESSAGE)?.notSent).toBe(true);
+ });
+
+ it("marks a pass the user took off the queue as never sent", async () => {
+ const passed = (await run(await leadAndHandMade(), pass())).model;
+ const unqueued = await run(passed, {
+ type: "thread.follow-up.unqueue",
+ commandId: CommandId.make("unqueue-pass"),
+ threadId: OTHER,
+ messageId: PASS_MESSAGE,
+ createdAt: now,
+ });
+ const message = threadIn(unqueued.model, OTHER).messages.find((m) => m.id === PASS_MESSAGE);
+ expect(message?.notSent).toBe(true);
+ });
+
+ it("marks a pass refused right before it reached the agent, and never runs it again", async () => {
+ const ran = (
+ await run(
+ await run(await leadAndHandMade(), pass()).then((r) => r.model),
+ sendQueued(PASS_MESSAGE),
+ )
+ ).model;
+ // The provider layer's last check refused it: the thread's access went up.
+ const refused = await run(ran, {
+ type: "thread.lead-pass.not-run",
+ commandId: CommandId.make("not-run"),
+ threadId: OTHER,
+ messageId: PASS_MESSAGE,
+ createdAt: now,
+ });
+ const target = threadIn(refused.model, OTHER);
+ expect(target.messages.find((entry) => entry.id === PASS_MESSAGE)?.notSent).toBe(true);
+ expect(target.activities.some((entry) => entry.kind === LEAD_PASS_NOT_RUN_ACTIVITY_KIND)).toBe(
+ true,
+ );
+ expect(threadIn(refused.model, LEAD).childRequests.pendingNotes[0]?.text).toContain(
+ "did not run",
+ );
+ // Said once: a second report changes nothing.
+ expect(
+ (
+ await run(refused.model, {
+ type: "thread.lead-pass.not-run",
+ commandId: CommandId.make("not-run-again"),
+ threadId: OTHER,
+ messageId: PASS_MESSAGE,
+ createdAt: now,
+ })
+ ).events,
+ ).toEqual([]);
+ // Back within the ceiling, a retry still doesn't send it.
+ const failed = {
+ ...refused.model,
+ threads: refused.model.threads.map((entry) =>
+ entry.id === OTHER
+ ? {
+ ...entry,
+ session: session(OTHER, { status: "error", activeTurnId: null, lastError: "boom" }),
+ }
+ : entry,
+ ),
+ };
+ expect(
+ await refusal(failed, {
+ type: "thread.turn.retry",
+ commandId: CommandId.make("retry-not-sent"),
+ threadId: OTHER,
+ createdAt: now,
+ }),
+ ).toContain("was never sent. Send it yourself to run it");
});
it("refuses to retry a pass above its ceiling: the user sends it themselves", async () => {
diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts
index 04c79fd58..a0dd16720 100644
--- a/apps/server/src/orchestration/decider.ts
+++ b/apps/server/src/orchestration/decider.ts
@@ -336,8 +336,11 @@ const personWrote = (command: {
/**
* A pass whose ceiling is under the thread's access when its turn would
- * start (docs/design/lead-chat.md, "Access"): taken off the queue, one line
- * in the thread, and a note for the lead's next turn when it is still there.
+ * start (docs/design/lead-chat.md, "Access"): it never runs and its message
+ * is `notSent`, one line in the thread, and a note for the lead's next turn
+ * when it is still there. `from` is where it was refused: taken off the
+ * queue (the unqueue marks it), or after the queue let it go, right before
+ * it reached the agent (`thread.lead-pass.not-run`).
*/
function passCeilingCancelEvents(
readModel: OrchestrationReadModel,
@@ -349,6 +352,7 @@ function passCeilingCancelEvents(
refusal: string,
base: () => Omit,
createdAt: string,
+ from: "queue" | "start" = "queue",
): PlannedOrchestrationEvent[] {
const origin = queued.fromThread;
const lead =
@@ -356,11 +360,28 @@ function passCeilingCancelEvents(
? undefined
: readModel.threads.find((entry) => entry.id === origin.threadId);
return [
- {
- ...base(),
- type: "thread.follow-up-unqueued",
- payload: { threadId: thread.id, messageId: queued.messageId, reason: "cancelled", createdAt },
- },
+ from === "queue"
+ ? {
+ ...base(),
+ type: "thread.follow-up-unqueued",
+ payload: {
+ threadId: thread.id,
+ messageId: queued.messageId,
+ reason: "cancelled",
+ createdAt,
+ },
+ }
+ : {
+ ...base(),
+ type: "thread.lead-pass-recorded",
+ payload: {
+ threadId: thread.id,
+ kind: "not-run",
+ messageId: queued.messageId,
+ targetThreadId: thread.id,
+ createdAt,
+ },
+ },
{
...base(),
type: "thread.activity-appended",
@@ -2362,6 +2383,31 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
);
}
+ // Refused right before it reached the agent (the provider reactor's last
+ // check): marked, said once, and the lead hears on its next turn.
+ case "thread.lead-pass.not-run": {
+ const target = yield* requireThread({ readModel, command, threadId: command.threadId });
+ const message = target.messages.find((entry) => entry.id === command.messageId);
+ if (message === undefined || message.fromThread?.ceiling === undefined || message.notSent) {
+ return [];
+ }
+ return passCeilingCancelEvents(
+ readModel,
+ target,
+ { messageId: message.id, fromThread: message.fromThread },
+ "Not run: this thread has more access than the lead chat.",
+ () =>
+ withEventBase({
+ aggregateKind: "thread",
+ aggregateId: target.id,
+ occurredAt: command.createdAt,
+ commandId: command.commandId,
+ }),
+ command.createdAt,
+ "start",
+ );
+ }
+
case "thread.child.start":
case "thread.child-request.respond":
case "thread.child.send":
@@ -3524,6 +3570,17 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
detail: `This message came from ${lastUserMessage.fromOutside.name}, outside Threadlines. Ask it to send it again, or write it yourself.`,
});
}
+ // A message that never reached the agent stays out of its history for
+ // good (OrchestrationMessage.notSent), so it never runs from here.
+ if (lastUserMessage.notSent === true) {
+ return yield* new OrchestrationCommandInvariantError({
+ commandType: command.type,
+ detail:
+ lastUserMessage.fromThread?.ceiling !== undefined
+ ? "This message the lead chat passed on was never sent. Send it yourself to run it."
+ : "This message was never sent. Write it again to send it.",
+ });
+ }
// A lead chat's pass runs again only within the access it was passed
// with; above it, the user sends it themselves.
const retryPassRefusal = passCeilingRefusal(lastUserMessage, targetThread);
diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index f885ed587..5fa878468 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -1004,11 +1004,26 @@ export function projectEvent(
event.type,
"payload",
).pipe(
- Effect.map((payload) =>
- updateChildRequests(nextBase, payload.threadId, (state) =>
+ Effect.map((payload) => {
+ const next = updateChildRequests(nextBase, payload.threadId, (state) =>
childRequestStateOn.leadPass(state, payload),
- ),
- ),
+ );
+ // Refused right before it reached the agent: the message never ran.
+ if (payload.kind !== "not-run") return next;
+ const thread = next.threads.find((entry) => entry.id === payload.threadId);
+ return thread === undefined
+ ? next
+ : {
+ ...next,
+ threads: updateThread(next.threads, payload.threadId, {
+ messages: thread.messages.map((message) =>
+ message.id === payload.messageId
+ ? { ...message, notSent: true as const }
+ : message,
+ ),
+ }),
+ };
+ }),
);
case "thread.remote-child-updated":
diff --git a/apps/server/src/orchestration/roomCatchUp.test.ts b/apps/server/src/orchestration/roomCatchUp.test.ts
index c30dc97c5..4ac0d498e 100644
--- a/apps/server/src/orchestration/roomCatchUp.test.ts
+++ b/apps/server/src/orchestration/roomCatchUp.test.ts
@@ -1,9 +1,11 @@
import {
CheckpointRef,
+ ChildRequestId,
MessageId,
ProviderInstanceId,
RoomAgentRequestId,
SideTurnId,
+ ThreadId,
ThreadParticipantId,
TurnId,
type OrchestrationMessage,
@@ -209,6 +211,38 @@ describe("buildRoomCatchUp", () => {
expect(note).toContain(`message ${ROOM_JOIN_MESSAGE_COUNT + 2}`);
});
+ it("leaves a lead chat's pass that never ran out of a joining agent's note", () => {
+ const ceiling = { runtimeMode: "approval-required", interactionMode: "default" } as const;
+ const pass = (id: string, text: string, extra: Partial = {}) =>
+ message(id, "user", text, null, {
+ fromThread: {
+ threadId: ThreadId.make("lead"),
+ requestId: ChildRequestId.make(`request-${id}`),
+ kind: "request",
+ ceiling,
+ },
+ ...extra,
+ });
+ const note = buildRoomCatchUp({
+ thread: thread(
+ [
+ pass("ran", "passed on and done"),
+ pass("refused", "passed on, refused at its ceiling", { notSent: true }),
+ pass("waiting", "passed on, still waiting"),
+ message("now", "user", "astra, take a look", astraId),
+ ],
+ { queuedFollowUps: [{ messageId: "waiting" }] },
+ ),
+ participantId: astraId,
+ messageId: MessageId.make("now"),
+ ...main,
+ })?.note;
+
+ expect(note).toContain("passed on and done");
+ expect(note).not.toContain("refused at its ceiling");
+ expect(note).not.toContain("still waiting");
+ });
+
it("delivers a side exchange that landed before the agent's own reply", () => {
const sideTurnId = SideTurnId.make("0d9e8f7a-6b5c-4d3e-8f1a-2b3c4d5e6f70");
const messages = [
diff --git a/apps/server/src/orchestration/roomCatchUp.ts b/apps/server/src/orchestration/roomCatchUp.ts
index f23768b13..855429a2b 100644
--- a/apps/server/src/orchestration/roomCatchUp.ts
+++ b/apps/server/src/orchestration/roomCatchUp.ts
@@ -29,7 +29,7 @@ import type {
import { isRoomThread } from "@threadlines/shared/threadParticipants";
-import { messageAuthor } from "@threadlines/shared/messageAuthor";
+import { messageAuthor, reachedAgent } from "@threadlines/shared/messageAuthor";
import { handOffReplyText } from "./agentRequestDecisions.ts";
/** Messages an agent joining late gets verbatim. */
@@ -45,6 +45,8 @@ export interface RoomCatchUpInput {
readonly agentRole?: string | undefined;
readonly participants: ReadonlyArray;
readonly messages: ReadonlyArray;
+ /** What still waits to be sent: kept out of the note (`reachedAgent`). */
+ readonly queuedFollowUps?: ReadonlyArray<{ readonly messageId: string }> | undefined;
readonly checkpoints: ReadonlyArray;
};
/** The agent the turn is for. Null: the thread's own agent. */
@@ -209,7 +211,9 @@ export function buildRoomCatchUp(input: RoomCatchUpInput): RoomCatchUp | undefin
(message) =>
message.id !== input.messageId &&
(message.role === "user" || message.role === "assistant") &&
- message.text.trim().length > 0,
+ message.text.trim().length > 0 &&
+ // Only what an agent was given: a pass that never ran stays out.
+ reachedAgent(message, thread),
);
const ownerOf = (message: OrchestrationMessage) => message.participantId ?? null;
// A reply arrives as the message below the note. The words it was taken
diff --git a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts
index d0f3e37fe..2b3e2adb1 100644
--- a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts
+++ b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.test.ts
@@ -196,25 +196,38 @@ describe("ThreadContextSeedBuilder", () => {
expect(value.entries.map((entry) => entry.text)).toEqual(["previous context"]);
});
- it("leaves out messages still waiting in the queue: no agent was sent them yet", async () => {
+ it("holds only messages an agent was given: never a queued or not-sent pass", async () => {
const thread = {
...fakeThread(
[
- { id: "sent", role: "user", text: "ran earlier", createdAt: "2026-01-01T00:00:00Z" },
+ { id: "ran", role: "user", text: "passed on, ran", createdAt: "2026-01-01T00:00:00Z" },
+ // A room hand-off that ran, later cancelled with its agent: it was given.
{
- id: "queued-pass",
+ id: "hand-off",
role: "user",
- text: "passed on, waiting",
+ text: "hand-off that ran",
+ requestOutcome: "cancelled",
createdAt: "2026-01-01T00:00:01Z",
- },
- { id: "current", role: "user", text: "switch now", createdAt: "2026-01-01T00:00:03Z" },
+ } as FakeMessage,
+ { id: "queued", role: "user", text: "still waiting", createdAt: "2026-01-01T00:00:02Z" },
+ {
+ id: "refused",
+ role: "user",
+ text: "refused at its ceiling",
+ notSent: true,
+ createdAt: "2026-01-01T00:00:03Z",
+ } as FakeMessage,
+ { id: "current", role: "user", text: "switch now", createdAt: "2026-01-01T00:00:04Z" },
],
[],
),
- queuedFollowUps: [{ messageId: "queued-pass" }],
+ queuedFollowUps: [{ messageId: "queued" }],
} as unknown as OrchestrationThread;
const seed = await build({ thread, excludeMessageId: "current" });
- expect(Option.getOrThrow(seed).entries.map((entry) => entry.text)).toEqual(["ran earlier"]);
+ expect(Option.getOrThrow(seed).entries.map((entry) => entry.text)).toEqual([
+ "passed on, ran",
+ "hand-off that ran",
+ ]);
});
it("returns a workspace-only seed when the thread detail read fails", async () => {
diff --git a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts
index 58d790a9b..57e2f6762 100644
--- a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts
+++ b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts
@@ -28,7 +28,7 @@ import {
type SeedBudget,
splitSeedEntriesByBudget,
} from "@threadlines/shared/contextSeed";
-import { transcriptAuthor } from "@threadlines/shared/messageAuthor";
+import { reachedAgent, transcriptAuthor } from "@threadlines/shared/messageAuthor";
import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";
@@ -107,6 +107,7 @@ function buildEntries(input: {
readonly text: string;
readonly attachments?: ReadonlyArray<{ readonly name: string }> | undefined;
readonly fromOutside?: OrchestrationMessage["fromOutside"];
+ readonly notSent?: true | undefined;
readonly createdAt: string;
}>;
readonly activities: ReadonlyArray<{
@@ -115,8 +116,11 @@ function buildEntries(input: {
readonly createdAt: string;
}>;
readonly excludeMessageId?: string | undefined;
- /** Messages still waiting in the queue: no agent was sent them yet. */
- readonly queuedMessageIds?: ReadonlySet | undefined;
+ /** Whether an agent was given the message (`reachedAgent`): history holds only those. */
+ readonly reachedAgent: (message: {
+ readonly id: string;
+ readonly notSent?: true | undefined;
+ }) => boolean;
}): ReadonlyArray {
const items: Array<{ readonly createdAt: string; readonly entry: ThreadContextSeedEntry }> = [];
@@ -124,9 +128,7 @@ function buildEntries(input: {
if (message.id !== undefined && message.id === input.excludeMessageId) {
continue;
}
- // An agent's or another thread's message is written into the chat when it
- // is queued, before it runs: one still waiting was sent to no agent yet.
- if (message.id !== undefined && input.queuedMessageIds?.has(message.id) === true) {
+ if (message.id !== undefined && !input.reachedAgent({ ...message, id: message.id })) {
continue;
}
const attached = (message.attachments ?? []).map((attachment) => attachment.name);
@@ -198,7 +200,7 @@ export const makeThreadContextSeedBuilder = (deps: {
messages: thread.messages,
activities: thread.activities,
excludeMessageId: input.excludeMessageId,
- queuedMessageIds: new Set((thread.queuedFollowUps ?? []).map((queued) => queued.messageId)),
+ reachedAgent: (message) => reachedAgent(message, thread),
});
if (entries.length === 0 && pointer === undefined) {
diff --git a/apps/server/src/threads/threadOperations.ts b/apps/server/src/threads/threadOperations.ts
index 84e6ec42c..5babd5883 100644
--- a/apps/server/src/threads/threadOperations.ts
+++ b/apps/server/src/threads/threadOperations.ts
@@ -474,6 +474,7 @@ export function readThreadPage(
origin,
...text,
...(message.streaming ? { streaming: true } : {}),
+ ...(message.notSent === true ? { notSent: true } : {}),
};
};
const wanted = input.messageId?.trim();
diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx
index 6e022940b..5cf36a590 100644
--- a/apps/web/src/components/chat/MessagesTimeline.tsx
+++ b/apps/web/src/components/chat/MessagesTimeline.tsx
@@ -3234,7 +3234,16 @@ function ThreadMessageTimelineRow({
}
/>
- {message.requestOutcome === "cancelled" ? (
+ {message.notSent === true ? (
+ // A lead chat's pass that never reached the agent; the line in the
+ // thread below says why.
+
+ Not sent
+
+ ) : message.requestOutcome === "cancelled" ? (
+ case "thread.lead-pass-recorded": {
+ const next = updateChildRequestState(state, event.payload.threadId, (current) =>
childRequestStateOn.leadPass(current, event.payload),
);
+ // Refused right before it reached the agent: the message never ran.
+ return event.payload.kind !== "not-run"
+ ? next
+ : updateThreadState(next, event.payload.threadId, (thread) => ({
+ ...thread,
+ messages: thread.messages.map((message) =>
+ message.id === event.payload.messageId
+ ? { ...message, notSent: true as const }
+ : message,
+ ),
+ }));
+ }
// Agents' settings changes (docs/design/agent-settings-changes.md),
// folded through the reducer the server's projector uses.
diff --git a/apps/web/src/types.ts b/apps/web/src/types.ts
index 15406015b..de2d953a7 100644
--- a/apps/web/src/types.ts
+++ b/apps/web/src/types.ts
@@ -140,7 +140,7 @@ export interface ChatMessage {
sentFrom?: MessageSentFrom | undefined;
/** See OrchestrationMessage.trigger: why Threadlines sent it for the user. */
trigger?: MessageTrigger | undefined;
- /** See OrchestrationMessage.notSent: the user wrote first, so it never went. */
+ /** See OrchestrationMessage.notSent: it never reached the agent (a continue the user overtook, a pass refused). */
notSent?: true | undefined;
/**
* See OrchestrationMessage.imported: brought over when the thread moved
diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md
index 3ba23c890..2044e1818 100644
--- a/docs/design/lead-chat.md
+++ b/docs/design/lead-chat.md
@@ -220,11 +220,15 @@ coordinate it.
note to the lead on its next turn. The provider layer checks the ceiling once more
right before the turn goes to the agent (the user may raise access after the
decision), against the thread and the live runtime, as it does for outside agents;
- a pass refused there fails its turn with a line saying so. A pass still waiting in
- the queue is not part of the history a new agent is given. Open: a pass taken
- back, or refused at that last check, stays in the chat and can still reach a later
- agent's history (hand-off seed, room catch-up), since nothing records that it
- never ran. A retry by the user is refused the same way,
+ a pass refused there fails its turn with a line saying so. A pass that never
+ reached the agent is `notSent` (OrchestrationMessage.notSent): taken back at the
+ queue, taken off it by
+ the user, or refused at that last check (`thread.lead-pass.not-run`, which also
+ writes the line and the lead's note). No history an agent is given includes a
+ `notSent` or still-queued message (`reachedAgent`: the hand-off seed, a fork's
+ context, a room's catch-up note); `thread_read` and `room_history` keep it,
+ labelled. It is never retried or resent ("Send it yourself to run it."), and it
+ says "Not sent" on screen. A retry by the user is refused the same way,
with "Send it yourself to run it." The user's thread's access is never changed.
- **No fan-out.** Once a pass starts its turn in a thread, that thread cannot call
`thread_start` until the user writes there ("This thread is working on something
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index d90d9c7c9..deb292c3e 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -1174,8 +1174,11 @@ export const OrchestrationMessage = Schema.Struct({
/** See MessageTrigger. Written with the message and kept. */
trigger: Schema.optional(MessageTrigger),
/**
- * A message Threadlines wrote for the user (`trigger`) that never reached
- * the agent: the user wrote before it went, and theirs went instead.
+ * A message that never reached the agent, kept in the chat: a continue
+ * Threadlines wrote for the user (`trigger`) that the user's own message
+ * overtook, or a lead chat's pass that was taken back or refused at its
+ * ceiling. Once set, kept. No history an agent is given includes it
+ * (`reachedAgent`), and it is never retried.
*/
notSent: Schema.optional(Schema.Literal(true)),
/**
@@ -4928,6 +4931,20 @@ const ThreadLeadPassCommand = Schema.Struct({
createdAt: IsoDateTime,
});
+/**
+ * A lead chat's pass was refused right before it went to the agent: the
+ * thread's access was raised above its ceiling after the decider let it
+ * through (docs/design/lead-chat.md, "Access"). Server only, from the
+ * provider reactor. `threadId` is the thread it was passed to.
+ */
+const ThreadLeadPassNotRunCommand = Schema.Struct({
+ type: Schema.Literal("thread.lead-pass.not-run"),
+ commandId: CommandId,
+ threadId: ThreadId,
+ messageId: MessageId,
+ createdAt: IsoDateTime,
+});
+
/** Child threads: a request moved on (set up, its turn started, background wait). */
const ThreadChildRequestUpdateCommand = Schema.Struct({
type: Schema.Literal("thread.child-request.update"),
@@ -5335,6 +5352,7 @@ const InternalOrchestrationCommand = Schema.Union([
ThreadChildStartCommand,
ThreadChildSendCommand,
ThreadLeadPassCommand,
+ ThreadLeadPassNotRunCommand,
ThreadChildRequestUpdateCommand,
ThreadChildRequestSettleCommand,
ThreadChildNotesDeliveredCommand,
@@ -5912,7 +5930,14 @@ export const ThreadChildRequestsResetPayload = Schema.Struct({
*/
export const ThreadLeadPassRecordedPayload = Schema.Struct({
threadId: ThreadId,
- kind: Schema.Literals(["sent", "refused", "started"]),
+ /**
+ * `sent`, `refused` (with the lead's `note`): on the lead. `started`: the
+ * pass started its turn in the target. `not-run`: on the target, the pass
+ * was refused right before it went to the agent, so its message is
+ * `notSent`. (One taken off the queue is marked by that, see
+ * withUnqueuedAgentMessage.)
+ */
+ kind: Schema.Literals(["sent", "refused", "started", "not-run"]),
/** The pass's message, in the thread it was passed to. */
messageId: MessageId,
targetThreadId: ThreadId,
diff --git a/packages/contracts/src/peerRpc.ts b/packages/contracts/src/peerRpc.ts
index cee087905..098f377cb 100644
--- a/packages/contracts/src/peerRpc.ts
+++ b/packages/contracts/src/peerRpc.ts
@@ -108,6 +108,8 @@ export const AgentThreadReadResult = Schema.Struct({
/** Read by `messageId`: pass as `offset` to read on. Absent: `text` reaches the end. */
nextOffset: Schema.optional(Schema.Number),
streaming: Schema.optional(Schema.Boolean),
+ /** It never reached that thread's agent (OrchestrationMessage.notSent): shown, never acted on. */
+ notSent: Schema.optional(Schema.Boolean),
}),
),
/** Pass as `after` later for only newer messages; null when there are none. */
diff --git a/packages/shared/src/childThreads.ts b/packages/shared/src/childThreads.ts
index 97b5b2dc7..c657845c8 100644
--- a/packages/shared/src/childThreads.ts
+++ b/packages/shared/src/childThreads.ts
@@ -762,7 +762,7 @@ export const childRequestStateOn = {
leadPass: (
state: OrchestrationChildRequestState,
pass: {
- readonly kind: "sent" | "refused" | "started";
+ readonly kind: "sent" | "refused" | "started" | "not-run";
readonly note?: ChildRequestNote | undefined;
readonly ceiling?: LeadPassCeiling | undefined;
},
@@ -770,6 +770,9 @@ export const childRequestStateOn = {
switch (pass.kind) {
case "sent":
return { ...state, sendsSinceUser: state.sendsSinceUser + 1 };
+ // Its mark is on the message, not on the thread's requests.
+ case "not-run":
+ return state;
case "started": {
const passCeiling = narrowerModeCeiling(
state.passCeiling,
diff --git a/packages/shared/src/messageAuthor.ts b/packages/shared/src/messageAuthor.ts
index c2ff72333..5bdaca8d2 100644
--- a/packages/shared/src/messageAuthor.ts
+++ b/packages/shared/src/messageAuthor.ts
@@ -52,6 +52,26 @@ export function transcriptAuthor(
: undefined;
}
+/**
+ * Whether an agent was given this message, so history may include it: not
+ * `notSent` (never reached the agent), and not still waiting in the thread's
+ * queue (an agent's message is written into the chat when it is queued).
+ * Every history handed to an agent filters through this (context seeds, a
+ * fork's context, a room's catch-up note); explicit reads (`thread_read`,
+ * `room_history`) keep the message and label it instead.
+ */
+export function reachedAgent(
+ message: { readonly id: string; readonly notSent?: true | undefined },
+ thread: {
+ readonly queuedFollowUps?: ReadonlyArray<{ readonly messageId: string }> | undefined;
+ },
+): boolean {
+ return (
+ message.notSent !== true &&
+ !(thread.queuedFollowUps ?? []).some((queued) => queued.messageId === message.id)
+ );
+}
+
/** The message's author line and origin. */
export function messageAuthor(
message: Pick<
diff --git a/packages/shared/src/roomAgentRequests.ts b/packages/shared/src/roomAgentRequests.ts
index e68cdddf8..faf2b3c8e 100644
--- a/packages/shared/src/roomAgentRequests.ts
+++ b/packages/shared/src/roomAgentRequests.ts
@@ -317,26 +317,41 @@ export const isAgentOrigin = (entry: {
/**
* A message an agent queued (a reply, or a child thread's report or request)
* that was taken back before it was sent: it stays in the chat, marked
- * cancelled, and never started a turn. The projections and the web store all
- * apply it through this.
+ * cancelled, and never started a turn. A lead chat's pass (`fromThread.ceiling`)
+ * taken back is also `notSent`, which keeps it out of every history an agent
+ * is given (`reachedAgent`). The projections and the web store all apply it
+ * through this.
*/
export const withUnqueuedAgentMessage = <
Message extends {
readonly id: string;
readonly fromAgent?: unknown;
- readonly fromThread?: unknown;
+ readonly fromThread?: { readonly ceiling?: unknown } | undefined;
+ readonly fromOutside?: unknown;
readonly requestOutcome?: RoomAgentRequestOutcome | undefined;
+ readonly notSent?: true | undefined;
},
>(
message: Message,
unqueued: { readonly messageId: string; readonly reason: "sent" | "cancelled" },
-): Message =>
- unqueued.reason === "cancelled" &&
- message.id === unqueued.messageId &&
- isAgentOrigin(message) &&
- message.requestOutcome === undefined
- ? { ...message, requestOutcome: "cancelled" }
+): Message => {
+ if (
+ unqueued.reason !== "cancelled" ||
+ message.id !== unqueued.messageId ||
+ !isAgentOrigin(message)
+ ) {
+ return message;
+ }
+ const outcome = message.requestOutcome === undefined;
+ const notSent = message.fromThread?.ceiling !== undefined && message.notSent !== true;
+ return outcome || notSent
+ ? {
+ ...message,
+ ...(outcome ? { requestOutcome: "cancelled" as const } : {}),
+ ...(notSent ? { notSent: true as const } : {}),
+ }
: message;
+};
/**
* Whether the user wrote a message. In a room, an agent can write a user-role
From 850286698f6a9a7af0be67c37276b2c04b57f156 Mon Sep 17 00:00:00 2001
From: Badcuban <108198679+badcuban@users.noreply.github.com>
Date: Tue, 17 Nov 2026 13:21:42 -0500
Subject: [PATCH 09/11] fix: a pass stopped while prepared, or moved to another
computer, stays not sent
Three gaps in the not-sent mark:
- A Stop that lands while a released pass's turn is prepared dropped the
turn without marking it. The reactor now sends thread.lead-pass.not-run
with reason stopped, so the line and the lead's note say so.
- A retry accepted just before the mark landed could still run the pass.
The reactor refuses a pass marked not sent when its turn is prepared.
- A move to another computer dropped the mark: thread.message-sent had no
field for it, and the linked-computer import didn't copy it. The payload
now carries notSent, folded by the projector, the SQLite pipeline and
the web store.
---
apps/server/src/links/LinkMoves.ts | 2 +
.../Layers/ProjectionPipeline.ts | 1 +
.../Layers/ProviderCommandReactor.test.ts | 73 +++++++++++++++++++
.../Layers/ProviderCommandReactor.ts | 49 +++++++++----
.../orchestration/decider.projectLead.test.ts | 29 ++++++++
.../orchestration/decider.threadMoves.test.ts | 19 ++++-
apps/server/src/orchestration/decider.ts | 11 ++-
apps/server/src/orchestration/projector.ts | 5 +-
apps/web/src/store.ts | 1 +
docs/design/lead-chat.md | 7 +-
packages/contracts/src/orchestration.ts | 12 ++-
11 files changed, 180 insertions(+), 29 deletions(-)
diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts
index f1898db41..038757d43 100644
--- a/apps/server/src/links/LinkMoves.ts
+++ b/apps/server/src/links/LinkMoves.ts
@@ -1550,6 +1550,8 @@ const make = Effect.gen(function* () {
...(message.completesTurn !== undefined ? { completesTurn: message.completesTurn } : {}),
...(message.agentModels !== undefined ? { agentModels: message.agentModels } : {}),
...(message.sentFrom !== undefined ? { sentFrom: message.sentFrom } : {}),
+ // Never reached the agent there: no history here may carry it either.
+ ...(message.notSent === true ? { notSent: true as const } : {}),
createdAt: message.createdAt,
}));
const activities = row.manifest.thread.activities.map((activity) => ({
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
index 90691043b..95b558aac 100644
--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
@@ -1666,6 +1666,7 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
...(event.payload.composer !== undefined ? { composer: event.payload.composer } : {}),
...(event.payload.sentFrom !== undefined ? { sentFrom: event.payload.sentFrom } : {}),
...(event.payload.trigger !== undefined ? { trigger: event.payload.trigger } : {}),
+ ...(event.payload.notSent === true ? { notSent: true as const } : {}),
isStreaming: event.payload.streaming,
createdAt: previousMessage?.createdAt ?? event.payload.createdAt,
updatedAt: event.payload.updatedAt,
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
index 00b16a0aa..7dd51caad 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts
@@ -3858,6 +3858,79 @@ describe("ProviderCommandReactor", () => {
?.messages.find((entry) => entry.id === asMessageId("pass-message"));
await waitFor(async () => (await passMessage())?.notSent === true);
});
+
+ it("doesn't send a lead chat's pass marked never sent while its turn was prepared", async () => {
+ const threadId = ThreadId.make("marked-thread");
+ let hold: Deferred.Deferred | null = null;
+ const harness = await createHarness({
+ beforeThreadRead: (id) =>
+ id === threadId && hold !== null ? Deferred.await(hold) : Effect.void,
+ });
+ await Effect.runPromise(
+ harness.engine.dispatch({
+ type: "thread.create",
+ commandId: CommandId.make("cmd-create-marked"),
+ threadId,
+ projectId: asProjectId("project-1"),
+ title: "Fix the flaky test",
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ branch: null,
+ worktreePath: null,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ }),
+ );
+ hold = Effect.runSync(Deferred.make());
+ await Effect.runPromise(
+ harness.engine.dispatch({
+ type: "thread.turn.start",
+ commandId: CommandId.make("cmd-marked-pass-turn"),
+ threadId,
+ message: {
+ messageId: asMessageId("pass-message"),
+ role: "user",
+ text: "Run the migration",
+ attachments: [],
+ },
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ runtimeMode: "approval-required",
+ fromThread: {
+ threadId: ThreadId.make("lead-thread"),
+ requestId: ChildRequestId.make("pass-request"),
+ kind: "request",
+ ceiling: {
+ runtimeMode: "approval-required",
+ interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE,
+ },
+ },
+ createdAt: "2026-01-01T00:00:01.000Z",
+ }),
+ );
+ // A retry accepted just before the mark landed: the mark lands first here.
+ await Effect.runPromise(
+ harness.engine.dispatch({
+ type: "thread.lead-pass.not-run",
+ commandId: CommandId.make("cmd-mark-not-run"),
+ threadId,
+ messageId: asMessageId("pass-message"),
+ reason: "ceiling",
+ createdAt: "2026-01-01T00:00:02.000Z",
+ }),
+ );
+ Effect.runSync(Deferred.succeed(hold, undefined));
+ hold = null;
+
+ const failure = async () =>
+ (await harness.readModel()).threads
+ .find((entry) => entry.id === threadId)
+ ?.activities.find((activity) => activity.kind === "provider.turn.start.failed");
+ await waitFor(async () => (await failure()) !== undefined);
+ expect(await failure()).toMatchObject({
+ payload: { detail: expect.stringContaining("was never sent") },
+ });
+ expect(harness.sendTurn).not.toHaveBeenCalled();
+ });
});
it("picks up the room tools at the next turn, never in the middle of one", async () => {
diff --git a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
index f396bfdb5..c86f783ef 100644
--- a/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
+++ b/apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
@@ -223,6 +223,10 @@ export interface ForkTurnBoundary {
readonly lastTurnId?: TurnId;
}
+/** Why a pass marked never sent did not go when a retry asked for it. */
+const PASS_NOT_SENT_DETAIL =
+ "This message the lead chat passed on was never sent. Send it yourself to run it.";
+
/** Why a lead chat's pass did not go to the agent: the thread's access went above its ceiling. */
const PASS_ABOVE_CEILING_DETAIL =
"This message the lead chat passed on wasn't sent: this thread has more access than the lead chat now. Send it yourself to run it.";
@@ -2370,9 +2374,17 @@ const make = Effect.gen(function* () {
const sessionKey = participantSessionKey(input.threadId, input.participantId);
// Read from the stored message, which keeps it for good: a retry or a
// resend of a pass carries no origin on its turn.
- const passCeiling =
- thread.messages.find((message) => message.id === input.messageId)?.fromThread?.ceiling ??
- input.fromThread?.ceiling;
+ const storedMessage = thread.messages.find((message) => message.id === input.messageId);
+ const passCeiling = storedMessage?.fromThread?.ceiling ?? input.fromThread?.ceiling;
+ // Marked as never sent while this turn was prepared (a retry the user
+ // made just before the mark landed): it stays unsent.
+ if (passCeiling !== undefined && storedMessage?.notSent === true) {
+ return yield* new ProviderAdapterRequestError({
+ provider: providerErrorLabel(undefined),
+ method: "thread.turn.start",
+ detail: PASS_NOT_SENT_DETAIL,
+ });
+ }
const ensured = yield* ensureSessionForThread(input.threadId, input.createdAt, {
participantId: input.participantId,
...(input.modelSelection !== undefined ? { modelSelection: input.modelSelection } : {}),
@@ -3122,18 +3134,17 @@ const make = Effect.gen(function* () {
// A lead chat's pass refused at the last check never reached the agent:
// the decider marks it so no history carries it, and the lead hears.
- const markPassNotRun = (detail: string) =>
- detail.includes(PASS_ABOVE_CEILING_DETAIL)
- ? Effect.gen(function* () {
- yield* orchestrationEngine.dispatch({
- type: "thread.lead-pass.not-run",
- commandId: serverCommandId("lead-pass-not-run"),
- threadId: event.payload.threadId,
- messageId: event.payload.messageId,
- createdAt: yield* nowIso,
- });
- }).pipe(Effect.ignoreCause({ log: true }))
- : Effect.void;
+ const markPassNotRun = (reason: "ceiling" | "stopped") =>
+ Effect.gen(function* () {
+ yield* orchestrationEngine.dispatch({
+ type: "thread.lead-pass.not-run",
+ commandId: serverCommandId("lead-pass-not-run"),
+ threadId: event.payload.threadId,
+ messageId: event.payload.messageId,
+ reason,
+ createdAt: yield* nowIso,
+ });
+ }).pipe(Effect.ignoreCause({ log: true }));
// What else a turn that could not start ends: its hand-off, its pass.
const afterFailedStart = (cause: Cause.Cause) =>
@@ -3141,7 +3152,9 @@ const make = Effect.gen(function* () {
? Effect.void
: Effect.andThen(
failHandOffForFailedStart(formatFailureDetail(cause)),
- markPassNotRun(formatFailureDetail(cause)),
+ formatFailureDetail(cause).includes(PASS_ABOVE_CEILING_DETAIL)
+ ? markPassNotRun("ceiling")
+ : Effect.void,
);
const recoverTurnStartFailure = (cause: Cause.Cause) =>
@@ -3184,6 +3197,10 @@ const make = Effect.gen(function* () {
messageId: event.payload.messageId,
});
yield* dropStart("Stopped before the turn started.");
+ // A lead chat's pass never ran: marked, so no later history carries it.
+ if (message.fromThread?.ceiling !== undefined) {
+ yield* markPassNotRun("stopped");
+ }
return true;
});
diff --git a/apps/server/src/orchestration/decider.projectLead.test.ts b/apps/server/src/orchestration/decider.projectLead.test.ts
index b07506f1f..7b4f11adf 100644
--- a/apps/server/src/orchestration/decider.projectLead.test.ts
+++ b/apps/server/src/orchestration/decider.projectLead.test.ts
@@ -413,6 +413,33 @@ describe("lead chat passes", () => {
expect(message?.notSent).toBe(true);
});
+ it("marks a pass Stop dropped before it started, and says so to the lead", async () => {
+ const ran = (
+ await run(
+ await run(await leadAndHandMade(), pass()).then((r) => r.model),
+ sendQueued(PASS_MESSAGE),
+ )
+ ).model;
+ const stopped = (
+ await run(ran, {
+ type: "thread.lead-pass.not-run",
+ commandId: CommandId.make("not-run-stopped"),
+ threadId: OTHER,
+ messageId: PASS_MESSAGE,
+ reason: "stopped",
+ createdAt: now,
+ })
+ ).model;
+ const target = threadIn(stopped, OTHER);
+ expect(target.messages.find((entry) => entry.id === PASS_MESSAGE)?.notSent).toBe(true);
+ expect(
+ target.activities.find((entry) => entry.kind === LEAD_PASS_NOT_RUN_ACTIVITY_KIND)?.summary,
+ ).toBe("Not run: this thread was stopped before it started.");
+ expect(threadIn(stopped, LEAD).childRequests.pendingNotes[0]?.text).toContain(
+ "the user stopped that thread",
+ );
+ });
+
it("marks a pass refused right before it reached the agent, and never runs it again", async () => {
const ran = (
await run(
@@ -426,6 +453,7 @@ describe("lead chat passes", () => {
commandId: CommandId.make("not-run"),
threadId: OTHER,
messageId: PASS_MESSAGE,
+ reason: "ceiling",
createdAt: now,
});
const target = threadIn(refused.model, OTHER);
@@ -444,6 +472,7 @@ describe("lead chat passes", () => {
commandId: CommandId.make("not-run-again"),
threadId: OTHER,
messageId: PASS_MESSAGE,
+ reason: "stopped",
createdAt: now,
})
).events,
diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts
index ffdf99dc0..daadc7aef 100644
--- a/apps/server/src/orchestration/decider.threadMoves.test.ts
+++ b/apps/server/src/orchestration/decider.threadMoves.test.ts
@@ -306,6 +306,15 @@ describe("moving a thread to a linked computer", () => {
turnId: TurnId.make("moved-turn-1"),
createdAt: now,
},
+ // Never reached the agent there: it stays unsent here.
+ {
+ messageId: MessageId.make("moved-message-3"),
+ role: "user",
+ text: "Run the migration.",
+ turnId: null,
+ notSent: true,
+ createdAt: now,
+ },
],
activities: [
{
@@ -325,9 +334,12 @@ describe("moving a thread to a linked computer", () => {
const arrived = threadOf(after, ARRIVED);
expect(arrived.movedFrom).toMatchObject({ label: "Windows PC", threadId: THREAD });
expect(arrived.historySeedOwed).toBe(true);
- expect(arrived.messages.map((message) => [message.text, message.imported])).toEqual([
- ["Why does it flake?", true],
- ["A timer races the click.", true],
+ expect(
+ arrived.messages.map((message) => [message.text, message.imported, message.notSent ?? false]),
+ ).toEqual([
+ ["Why does it flake?", true, false],
+ ["A timer races the click.", true, false],
+ ["Run the migration.", true, true],
]);
// Tool steps carry no turn of this computer's, so every revert keeps them.
expect(arrived.activities.map((activity) => [activity.kind, activity.turnId])).toEqual([
@@ -356,6 +368,7 @@ describe("moving a thread to a linked computer", () => {
expect(threadOf(undone, ARRIVED).messages.map((message) => message.text)).toEqual([
"Why does it flake?",
"A timer races the click.",
+ "Run the migration.",
"Run the tests",
]);
// An undo that keeps it owes nothing.
diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.ts
index a0dd16720..14e03ab7c 100644
--- a/apps/server/src/orchestration/decider.ts
+++ b/apps/server/src/orchestration/decider.ts
@@ -353,6 +353,8 @@ function passCeilingCancelEvents(
base: () => Omit,
createdAt: string,
from: "queue" | "start" = "queue",
+ /** Why, in the lead's note: the access went up (default), or the user stopped it. */
+ stopped = false,
): PlannedOrchestrationEvent[] {
const origin = queued.fromThread;
const lead =
@@ -413,7 +415,9 @@ function passCeilingCancelEvents(
note: {
requestId: origin.requestId,
recipient: { participantId: origin.passedBy ?? null },
- text: `The message you passed to "${thread.title}" (thread ${thread.id}) did not run: that thread has more access than this lead chat now. Tell the user, who can send it there.`,
+ text: stopped
+ ? `The message you passed to "${thread.title}" (thread ${thread.id}) did not run: the user stopped that thread before it started. Tell the user, who can send it there.`
+ : `The message you passed to "${thread.title}" (thread ${thread.id}) did not run: that thread has more access than this lead chat now. Tell the user, who can send it there.`,
createdAt,
},
createdAt,
@@ -2395,7 +2399,9 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
readModel,
target,
{ messageId: message.id, fromThread: message.fromThread },
- "Not run: this thread has more access than the lead chat.",
+ command.reason === "stopped"
+ ? "Not run: this thread was stopped before it started."
+ : "Not run: this thread has more access than the lead chat.",
() =>
withEventBase({
aggregateKind: "thread",
@@ -2405,6 +2411,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"
}),
command.createdAt,
"start",
+ command.reason === "stopped",
);
}
diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index 5fa878468..5302248cc 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -1381,6 +1381,7 @@ export function projectEvent(
...(payload.composer !== undefined ? { composer: payload.composer } : {}),
...(payload.sentFrom !== undefined ? { sentFrom: payload.sentFrom } : {}),
...(payload.trigger !== undefined ? { trigger: payload.trigger } : {}),
+ ...(payload.notSent === true ? { notSent: true as const } : {}),
turnId: payload.turnId,
streaming: payload.streaming,
createdAt: payload.createdAt,
@@ -1419,7 +1420,9 @@ export function projectEvent(
...(entry.trigger === undefined && message.trigger !== undefined
? { trigger: message.trigger }
: {}),
- ...(entry.notSent === true ? { notSent: true as const } : {}),
+ ...(entry.notSent === true || message.notSent === true
+ ? { notSent: true as const }
+ : {}),
}
: entry,
)
diff --git a/apps/web/src/store.ts b/apps/web/src/store.ts
index 6572abdbc..ac09c1505 100644
--- a/apps/web/src/store.ts
+++ b/apps/web/src/store.ts
@@ -3102,6 +3102,7 @@ function applyEnvironmentOrchestrationEvent(
...(event.payload.sentFrom !== undefined ? { sentFrom: event.payload.sentFrom } : {}),
...(event.payload.trigger !== undefined ? { trigger: event.payload.trigger } : {}),
...(event.payload.imported ? { imported: true } : {}),
+ ...(event.payload.notSent === true ? { notSent: true as const } : {}),
turnId: event.payload.turnId,
streaming: event.payload.streaming,
createdAt: event.payload.createdAt,
diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md
index 2044e1818..8456c5d3b 100644
--- a/docs/design/lead-chat.md
+++ b/docs/design/lead-chat.md
@@ -222,9 +222,10 @@ coordinate it.
decision), against the thread and the live runtime, as it does for outside agents;
a pass refused there fails its turn with a line saying so. A pass that never
reached the agent is `notSent` (OrchestrationMessage.notSent): taken back at the
- queue, taken off it by
- the user, or refused at that last check (`thread.lead-pass.not-run`, which also
- writes the line and the lead's note). No history an agent is given includes a
+ queue, taken off it by the user, or dropped after the queue let it go
+ (`thread.lead-pass.not-run`: refused at that last check, or stopped while its turn
+ was prepared; it also writes the line and the lead's note). The mark moves with
+ the thread to another computer. No history an agent is given includes a
`notSent` or still-queued message (`reachedAgent`: the hand-off seed, a fork's
context, a room's catch-up note); `thread_read` and `room_history` keep it,
labelled. It is never retried or resent ("Send it yourself to run it."), and it
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index deb292c3e..2b3fbf5b7 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -4932,16 +4932,18 @@ const ThreadLeadPassCommand = Schema.Struct({
});
/**
- * A lead chat's pass was refused right before it went to the agent: the
- * thread's access was raised above its ceiling after the decider let it
- * through (docs/design/lead-chat.md, "Access"). Server only, from the
- * provider reactor. `threadId` is the thread it was passed to.
+ * A lead chat's pass never went to the agent after the queue let it go: the
+ * thread's access was raised above its ceiling, or Stop landed, while its
+ * turn was prepared (docs/design/lead-chat.md, "Access"). Server only, from
+ * the provider reactor. `threadId` is the thread it was passed to.
*/
const ThreadLeadPassNotRunCommand = Schema.Struct({
type: Schema.Literal("thread.lead-pass.not-run"),
commandId: CommandId,
threadId: ThreadId,
messageId: MessageId,
+ /** `ceiling`: its access went above the pass's. `stopped`: Stop landed while it was prepared. */
+ reason: Schema.Literals(["ceiling", "stopped"]),
createdAt: IsoDateTime,
});
@@ -6042,6 +6044,8 @@ export const ThreadMessageSentPayload = Schema.Struct({
streaming: Schema.Boolean,
/** See OrchestrationMessage.imported. */
imported: Schema.optional(Schema.Literal(true)),
+ /** See OrchestrationMessage.notSent: an imported message that never reached the agent there. */
+ notSent: Schema.optional(Schema.Literal(true)),
/** Missing means legacy behavior for events written before assistant
* segments carried an explicit turn-settlement decision. */
completesTurn: Schema.optional(Schema.Boolean),
From 0f5007da99ef0d9fc4dbe179916aef835a5be45a Mon Sep 17 00:00:00 2001
From: Badcuban <108198679+badcuban@users.noreply.github.com>
Date: Tue, 17 Nov 2026 13:38:45 -0500
Subject: [PATCH 10/11] fix: an agent's message still queued when its thread
moves arrives as never sent
Only the user's own queued messages move with a thread. An agent's message
still waiting in the queue (a lead chat's pass) is already written into the
chat, so the export sent it as ordinary history and the other computer's
agent could be given it. The export now marks it notSent, which keeps it
out of every history there.
---
apps/server/src/moves/ThreadMoves.test.ts | 32 ++++++++++++++++++++++-
apps/server/src/moves/moveExport.ts | 6 ++++-
2 files changed, 36 insertions(+), 2 deletions(-)
diff --git a/apps/server/src/moves/ThreadMoves.test.ts b/apps/server/src/moves/ThreadMoves.test.ts
index 29f3f13b0..069993917 100644
--- a/apps/server/src/moves/ThreadMoves.test.ts
+++ b/apps/server/src/moves/ThreadMoves.test.ts
@@ -24,7 +24,12 @@ import {
previewManyThread,
targetPreviewOf,
} from "./ThreadMoves.ts";
-import { MOVE_MAX_BYTES, moveThreadStateOf, nativeSessionFits } from "./moveExport.ts";
+import {
+ exportThreadHistory,
+ MOVE_MAX_BYTES,
+ moveThreadStateOf,
+ nativeSessionFits,
+} from "./moveExport.ts";
import { carryBringsWords, threadMoveCarry } from "../orchestration/threadMoveCarry.ts";
import { NATIVE_SESSION_MAX_BYTES, type NativeSessionExport } from "../provider/nativeSession.ts";
@@ -451,3 +456,28 @@ describe("what a thread carries, as the dialog says it (Part 3e)", () => {
]);
});
});
+
+describe("exportThreadHistory", () => {
+ it("sends an agent's message still waiting in the queue as never sent", () => {
+ const message = (id: string, text: string) => ({
+ id: MessageId.make(id),
+ role: "user" as const,
+ text,
+ turnId: null,
+ streaming: false,
+ createdAt: "2026-01-01T00:00:00.000Z",
+ updatedAt: "2026-01-01T00:00:00.000Z",
+ });
+ const thread = {
+ messages: [message("ran", "Fix it."), message("waiting", "Run the migration.")],
+ activities: [],
+ queuedFollowUps: [{ messageId: MessageId.make("waiting") }],
+ } as unknown as OrchestrationThread;
+ expect(
+ exportThreadHistory(thread).messages.map((entry) => [entry.text, entry.notSent ?? false]),
+ ).toEqual([
+ ["Fix it.", false],
+ ["Run the migration.", true],
+ ]);
+ });
+});
diff --git a/apps/server/src/moves/moveExport.ts b/apps/server/src/moves/moveExport.ts
index 976e6db58..be71dd15c 100644
--- a/apps/server/src/moves/moveExport.ts
+++ b/apps/server/src/moves/moveExport.ts
@@ -283,6 +283,10 @@ export function exportThreadHistory(thread: OrchestrationThread): {
readonly messages: ReadonlyArray;
readonly activities: ReadonlyArray;
} {
+ // An agent's message still waiting in the queue is written into the chat
+ // but never ran here, and only the user's own queued messages move: it
+ // arrives as never sent (reachedAgent), so no history there carries it.
+ const queuedIds = new Set((thread.queuedFollowUps ?? []).map((queued) => queued.messageId));
const messages = thread.messages
.filter(
(message) =>
@@ -304,7 +308,7 @@ export function exportThreadHistory(thread: OrchestrationThread): {
...(message.fromOutside !== undefined ? { fromOutside: message.fromOutside } : {}),
...(message.sentFrom !== undefined ? { sentFrom: message.sentFrom } : {}),
...(message.trigger !== undefined ? { trigger: message.trigger } : {}),
- ...(message.notSent === true ? { notSent: true as const } : {}),
+ ...(message.notSent === true || queuedIds.has(message.id) ? { notSent: true as const } : {}),
createdAt: message.createdAt,
}));
const activities = thread.activities
From f64279e5d588f59c813f5be1d0c2785a65811327 Mon Sep 17 00:00:00 2001
From: Badcuban <108198679+badcuban@users.noreply.github.com>
Date: Tue, 17 Nov 2026 13:59:05 -0500
Subject: [PATCH 11/11] fix: history handed to an agent never calls another
agent's message the user's
A context seed after a provider switch, and a fork's context, named only an
outside agent's message. A lead chat's pass, a parent's request, a child's
report and a room agent's message all read as "User", so a new agent could
take them for the user's instructions. They are now named as another
agent's, as thread_read and room_history already did.
---
.../contextSeed/ThreadContextSeedBuilder.ts | 2 ++
docs/design/lead-chat.md | 5 +++-
packages/shared/src/contextSeed.test.ts | 23 +++++++++++++++
packages/shared/src/messageAuthor.ts | 29 +++++++++++++------
4 files changed, 49 insertions(+), 10 deletions(-)
diff --git a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts
index 57e2f6762..d3b56df05 100644
--- a/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts
+++ b/apps/server/src/provider/contextSeed/ThreadContextSeedBuilder.ts
@@ -107,6 +107,8 @@ function buildEntries(input: {
readonly text: string;
readonly attachments?: ReadonlyArray<{ readonly name: string }> | undefined;
readonly fromOutside?: OrchestrationMessage["fromOutside"];
+ readonly fromThread?: OrchestrationMessage["fromThread"];
+ readonly fromAgent?: OrchestrationMessage["fromAgent"];
readonly notSent?: true | undefined;
readonly createdAt: string;
}>;
diff --git a/docs/design/lead-chat.md b/docs/design/lead-chat.md
index 8456c5d3b..254489aac 100644
--- a/docs/design/lead-chat.md
+++ b/docs/design/lead-chat.md
@@ -228,7 +228,10 @@ coordinate it.
the thread to another computer. No history an agent is given includes a
`notSent` or still-queued message (`reachedAgent`: the hand-off seed, a fork's
context, a room's catch-up note); `thread_read` and `room_history` keep it,
- labelled. It is never retried or resent ("Send it yourself to run it."), and it
+ labelled. A pass that did run is never called the user's in that history: the
+ hand-off seed and a fork's context name a message another agent wrote as that
+ agent's (`transcriptAuthor`), as `thread_read` and `room_history` already did.
+ It is never retried or resent ("Send it yourself to run it."), and it
says "Not sent" on screen. A retry by the user is refused the same way,
with "Send it yourself to run it." The user's thread's access is never changed.
- **No fan-out.** Once a pass starts its turn in a thread, that thread cannot call
diff --git a/packages/shared/src/contextSeed.test.ts b/packages/shared/src/contextSeed.test.ts
index 7b5a82c04..590e6441d 100644
--- a/packages/shared/src/contextSeed.test.ts
+++ b/packages/shared/src/contextSeed.test.ts
@@ -1,6 +1,8 @@
import {
+ ChildRequestId,
OutsideAgentConnectionId,
ProviderDriverKind,
+ ThreadId,
type ThreadContextSeedEntry,
} from "@threadlines/contracts";
import { describe, expect, it } from "vite-plus/test";
@@ -88,6 +90,27 @@ describe("renderSeedEntries with authors", () => {
expect(rendered).toContain("**Claude Code (outside agent):** Fix it");
expect(rendered).toContain("**User:** Thanks");
});
+
+ it("never calls another agent's message the user's", () => {
+ const fromThread = {
+ threadId: ThreadId.make("thread-lead"),
+ requestId: ChildRequestId.make("request-1"),
+ };
+ expect(transcriptAuthor({ role: "user", fromThread: { ...fromThread, kind: "request" } })).toBe(
+ "Agent in another thread (request)",
+ );
+ expect(transcriptAuthor({ role: "user", fromThread: { ...fromThread, kind: "report" } })).toBe(
+ "Agent in another thread (report)",
+ );
+ expect(transcriptAuthor({ role: "user", fromAgent: { participantId: null } })).toBe(
+ "Another agent in this thread",
+ );
+ // The user's own words, and an agent's reply, keep their role's name.
+ expect(transcriptAuthor({ role: "user" })).toBeUndefined();
+ expect(
+ transcriptAuthor({ role: "assistant", fromThread: { ...fromThread, kind: "report" } }),
+ ).toBeUndefined();
+ });
});
describe("renderThreadContextSeed", () => {
diff --git a/packages/shared/src/messageAuthor.ts b/packages/shared/src/messageAuthor.ts
index 5bdaca8d2..0049d2e28 100644
--- a/packages/shared/src/messageAuthor.ts
+++ b/packages/shared/src/messageAuthor.ts
@@ -41,15 +41,27 @@ export const outsideAgentAuthor = (agent: { readonly name: string }): string =>
/**
* The name a transcript handed to an agent gives a message instead of its
- * role's ("User"), or undefined to keep the role's: an outside agent's
- * message carries the agent's name.
+ * role's ("User"), or undefined to keep the role's. A user-role message some
+ * agent wrote is never called the user's: an outside agent's carries its
+ * name, another thread's agent's says so (a parent's request, a lead chat's
+ * pass, a child's report), and so does one from another agent in the thread.
+ * A transcript has no names to look up, so the last two are general.
*/
export function transcriptAuthor(
- message: Pick,
+ message: Pick,
): string | undefined {
- return message.role === "user" && message.fromOutside !== undefined
- ? outsideAgentAuthor(message.fromOutside)
- : undefined;
+ if (message.role !== "user") {
+ return undefined;
+ }
+ if (message.fromOutside !== undefined) {
+ return outsideAgentAuthor(message.fromOutside);
+ }
+ if (message.fromThread !== undefined) {
+ return message.fromThread.kind === "request"
+ ? "Agent in another thread (request)"
+ : "Agent in another thread (report)";
+ }
+ return message.fromAgent !== undefined ? "Another agent in this thread" : undefined;
}
/**
@@ -83,9 +95,8 @@ export function messageAuthor(
if (message.role !== "user") {
return { author: names.agentName(message.participantId), origin: "agent" };
}
- const outside = transcriptAuthor(message);
- if (outside !== undefined) {
- return { author: outside, origin: "user" };
+ if (message.fromOutside !== undefined) {
+ return { author: outsideAgentAuthor(message.fromOutside), origin: "user" };
}
if (message.fromThread !== undefined) {
return message.fromThread.kind === "request"