Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/server/src/environment/Layers/ServerEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
20 changes: 18 additions & 2 deletions apps/server/src/guide/topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export const GUIDE_TOPICS: ReadonlyArray<GuideTopic> = [
],
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.

Expand Down Expand Up @@ -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",
Expand Down
17 changes: 16 additions & 1 deletion apps/server/src/mcp/threadToolHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,9 @@ export interface ThreadToolDeps {
) => Effect.Effect<ReadonlyArray<OrchestrationThreadShell>>;
readonly readProject: (
projectId: ProjectId,
) => Effect.Effect<Pick<OrchestrationProjectShell, "kind" | "workspaceRoot"> | undefined>;
) => Effect.Effect<
Pick<OrchestrationProjectShell, "kind" | "workspaceRoot" | "leadThreadId"> | undefined
>;
/** The provider snapshots: who a child could run on. */
readonly providers: Effect.Effect<ReadonlyArray<ServerProvider>>;
/** The user's default for new threads (Settings): the last reasoning a child follows. */
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 3 additions & 0 deletions apps/server/src/orchestration/Layers/ProjectionPipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
11 changes: 11 additions & 0 deletions apps/server/src/orchestration/Layers/ProjectionSnapshotQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
};
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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"
Expand All @@ -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"
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>((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 = (
Expand Down
24 changes: 24 additions & 0 deletions apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -2510,6 +2533,7 @@ const make = Effect.gen(function* () {
resumeContextText,
forkContextText,
roomCatchUp?.note,
leadContext,
childContext.text,
outsideAgentContext(thread, input.messageId),
scheduleContext.text,
Expand Down
14 changes: 12 additions & 2 deletions apps/server/src/orchestration/childThreadDecisions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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.");
Expand All @@ -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.");
Expand Down Expand Up @@ -679,6 +688,7 @@ function decideRemoteChildSend(
command: CommandOf<"thread.child.send">,
baseFor: ChildEventBase,
remoteChild: NonNullable<ReturnType<typeof remoteChildOf>>,
isLead: boolean,
): ChildThreadDecision {
const refusal = childSendRefusal(
parent,
Expand All @@ -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);
Expand Down
Loading
Loading