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
4 changes: 2 additions & 2 deletions apps/server/src/guide/topics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,11 @@ When an agent asks to start several threads, the card has a checkbox per thread,

Only one thread leads a project; making another the lead replaces it. "Stop using as lead chat" turns it back into an ordinary thread, and the threads it started stay with it. Archiving or deleting the lead ends it. A lead can't move to another computer, and each computer keeps its own lead for a project.

The lead's row sits at the top of the sidebar with a crown, says Lead where the project name goes, and never wraps up on its own. The chat shows a Lead chat label beside the title, or, once it has started threads, the family tabs with the lead first.
The lead's row sits at the top of the sidebar with a crown, says Lead where the project name goes, and never wraps up on its own. {place:archived.autoArchive} leaves it alone, as it does a pinned thread. The chat shows a Lead chat label beside the title, or, once it has started threads, the family tabs with the lead first.

The Threads tab in the right sidebar shows the project's threads on every computer you can see, grouped as Needs you, Ready for review, Working, Landing, Idle and Done. Open it from the sidebar's list of panels or its + menu, on any thread of the project. A thread you wrapped up goes under Done (for 7 days, closed until you open it) unless its pull request is still open, which keeps it under Ready for review or Landing. Ready for review says what the pull request waits on, as the Pull requests page does. Click a row to open the thread, or right-click it for the thread's menu. The top line counts what needs you and what's working, with a Lead chat link when you're on another thread.

The lead's agent is told its role at the start of every turn. It may start 10 threads and send 20 messages to them per message you send, instead of 5 and 10. It needs {place:threads.agentThreads} to be on, and an agent that can't use the thread tools says so. General chats, a thread another thread still owns, and threads from another computer or an outside agent can't be the lead.`,
The lead's agent is told its role at the start of every turn, and when you give it a goal. It may start 10 threads and send 20 messages to them per message you send, instead of 5 and 10. It needs {place:threads.agentThreads} to be on, and an agent that can't use the thread tools says so. General chats, a thread another thread still owns, and threads from another computer or an outside agent can't be the lead.`,
},
{
id: "linking-computers",
Expand Down
11 changes: 9 additions & 2 deletions apps/server/src/mcp/threadTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,12 @@ import {
AgentThreadReadResult,
AgentThreadStatusWord,
AgentThreadSummary,
CHILD_THREAD_SEND_LIMIT,
CHILD_THREAD_START_LIMIT,
CHILD_THREADS_PER_CALL,
RuntimeMode,
} from "@threadlines/contracts";
import { LEAD_THREAD_SEND_LIMIT, LEAD_THREAD_START_LIMIT } from "@threadlines/shared/childThreads";
import * as Schema from "effect/Schema";
import { Tool, Toolkit } from "effect/ai";
import { loadedOnDemand } from "./toolLoading.ts";
Expand Down Expand Up @@ -246,7 +250,8 @@ export const ThreadStartTool = loadedOnDemand(
drivesThreads(
Tool.make("thread_start", {
description:
"Start new threads in this project to work in parallel. Each gets its own agent session and its own git worktree off your current commit (in a project without git they share the project folder). Give each a short `title` and a self-contained `prompt`: the new thread sees none of this conversation, only its prompt. `agent` picks a model from thread_agents; leave it out to use your own model and reasoning. Unless the user asked for a model or reasoning, prefer your own model or one already in this room (thread_agents' `room`), here or on another computer: a thread on a room agent's model runs at the reasoning the user set for that agent. `agent.reasoning` sets a level instead. Threads get your current access and interaction modes, never more; `access` asks for less. `runSetup: false` skips the project's setup script, for quick research. `checkout` puts a thread in a checkout that already exists instead of a new worktree, so it sees the files as they are there, uncommitted changes included (a reviewer for work another thread just finished): no worktree or branch is made and the setup script is not run. It shares that folder with the thread it belongs to, so have only one of them work at a time. `computer` starts them on another linked computer (a name or id from thread_agents' `computers`) in its copy of this project: from your branch when you pushed it, otherwise from that computer's default branch, without your unpushed changes. With `reportBack` (default true) each thread's final reply comes back to you as a message when it finishes; with false they run on their own and nothing comes back. Returns as soon as they are recorded and does not wait for them, so don't poll: carry on, or end your turn if you have nothing else to do. At most 5 threads per call and 5 per user message (10 in the project's lead chat).",
"Start new threads in this project to work in parallel. Each gets its own agent session and its own git worktree off your current commit (in a project without git they share the project folder). Give each a short `title` and a self-contained `prompt`: the new thread sees none of this conversation, only its prompt. `agent` picks a model from thread_agents; leave it out to use your own model and reasoning. Unless the user asked for a model or reasoning, prefer your own model or one already in this room (thread_agents' `room`), here or on another computer: a thread on a room agent's model runs at the reasoning the user set for that agent. `agent.reasoning` sets a level instead. Threads get your current access and interaction modes, never more; `access` asks for less. `runSetup: false` skips the project's setup script, for quick research. `checkout` puts a thread in a checkout that already exists instead of a new worktree, so it sees the files as they are there, uncommitted changes included (a reviewer for work another thread just finished): no worktree or branch is made and the setup script is not run. It shares that folder with the thread it belongs to, so have only one of them work at a time. `computer` starts them on another linked computer (a name or id from thread_agents' `computers`) in its copy of this project: from your branch when you pushed it, otherwise from that computer's default branch, without your unpushed changes. With `reportBack` (default true) each thread's final reply comes back to you as a message when it finishes; with false they run on their own and nothing comes back. Returns as soon as they are recorded and does not wait for them, so don't poll: carry on, or end your turn if you have nothing else to do. " +
`At most ${CHILD_THREADS_PER_CALL} threads per call and ${CHILD_THREAD_START_LIMIT} per user message (${LEAD_THREAD_START_LIMIT} in the project's lead chat).`,
parameters: Schema.Struct({
threads: Schema.Array(
Schema.Struct({
Expand Down Expand Up @@ -328,7 +333,9 @@ export const ThreadSendTool = loadedOnDemand(
drivesThreads(
Tool.make("thread_send", {
description:
"Send one of your threads a message: more work, a correction or a question. If it is idle it starts on it now; if it is busy it takes it after its current turn. Its reply comes back to you as a message, like a start. Only threads you started whose replies still come back to you. `checkout` first moves an idle thread into another thread's checkout, keeping its conversation, so it reads your message there (a thread that planned the work looks at what another thread built). The project's lead chat may also pass a message to an open thread in this project that it did not start (not a room, not one another thread owns, not one the user stopped): it works on it there, and nothing comes back. Don't poll; end your turn if you have nothing else to do.",
"Send one of your threads a message: more work, a correction or a question. If it is idle it starts on it now; if it is busy it takes it after its current turn. Its reply comes back to you as a message, like a start. Only threads you started whose replies still come back to you. `checkout` first moves an idle thread into another thread's checkout, keeping its conversation, so it reads your message there (a thread that planned the work looks at what another thread built). The project's lead chat may also pass a message to an open thread in this project that it did not start (not a room, not one another thread owns, not one the user stopped): it works on it there, and nothing comes back. " +
`At most ${CHILD_THREAD_SEND_LIMIT} messages per user message (${LEAD_THREAD_SEND_LIMIT} in the project's lead chat). ` +
"Don't poll; end your turn if you have nothing else to do.",
parameters: Schema.Struct({
threadId: ThreadIdParameter,
message: Schema.String.annotate({ description: "What you want it to do or answer." }),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1178,6 +1178,40 @@ describe("ProviderCommandReactor", () => {
expect(steered.input).not.toContain(role);
});

it("gives a goal set in the lead chat the lead's role, apart from the objective", async () => {
const harness = await createHarness();
const setGoal = (id: string) =>
Effect.runPromise(
harness.engine.dispatch({
type: "thread.goal.set",
commandId: CommandId.make(`cmd-goal-set-${id}`),
threadId: ThreadId.make("thread-1"),
objective: `Goal ${id}`,
createdAt: "2026-01-01T00:00:00.000Z",
}),
);
// Not the lead yet: the goal goes as it is.
await setGoal("before");
await waitFor(() => harness.setThreadGoal.mock.calls.length === 1);
expect(harness.setThreadGoal.mock.calls[0]?.[0].context).toBeUndefined();

await Effect.runPromise(
harness.engine.dispatch({
type: "project.lead.set",
commandId: CommandId.make("cmd-lead-set"),
projectId: asProjectId("project-1"),
threadId: ThreadId.make("thread-1"),
}),
);
await setGoal("after");
await waitFor(() => harness.setThreadGoal.mock.calls.length === 2);
const asLead = harness.setThreadGoal.mock.calls[1]?.[0];
expect(asLead?.objective).toBe("Goal after");
expect(asLead?.context).toContain(
'This thread is the lead chat for the project "Provider Project"',
);
});

it("steers the user's message into a continue that already reached the agent", async () => {
const harness = await createHarness();
const send = (
Expand Down
27 changes: 27 additions & 0 deletions apps/server/src/orchestration/Layers/ProviderCommandReactor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4188,10 +4188,30 @@ const make = Effect.gen(function* () {
)
: Effect.succeed(null),
),
// A goal that starts work in the lead carries the lead's role, as a
// turn there would: the provider runs that work without a turn start
// of ours (docs/design/lead-chat.md, "Role text").
Effect.flatMap((resumed) =>
(event.payload.objective !== undefined || event.payload.status === "active"
? providerService
.listSessions()
.pipe(
Effect.flatMap((sessions) =>
leadChatContext(
thread,
sessions.find((session) => session.threadId === goalHolderSessionKey)
?.roomTools,
),
),
)
: Effect.succeed(undefined)
).pipe(Effect.map((context) => ({ resumed, context }))),
),
Effect.flatMap(({ resumed, context }) =>
providerService.setThreadGoal({
threadId: goalHolderSessionKey,
modelSelection: goalModelSelection,
...(context !== undefined ? { context } : {}),
...(event.payload.objective !== undefined
? { objective: event.payload.objective }
: resumed !== null
Expand Down Expand Up @@ -5950,11 +5970,18 @@ const make = Effect.gen(function* () {
// Unreadable: tried again at the next turn end.
if (Option.isNone(held)) return;
if (held.value === null || held.value.status !== "active") {
// Made the lead here since it arrived: the goal's work hears it.
const leadContext = yield* leadChatContext(
thread,
(yield* providerService.listSessions()).find((session) => session.threadId === holderKey)
?.roomTools,
);
const given = yield* providerService
.setThreadGoal({
threadId: holderKey,
modelSelection: holderModel,
status: "active",
...(leadContext !== undefined ? { context: leadContext } : {}),
// The provider counts from zero again: what is left of the budget.
...(held.value === null
? {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,10 +108,26 @@ function runningSession(threadId: ThreadId): OrchestrationSession {

function makeSnapshotQuery(
threads: readonly OrchestrationThreadShell[],
leadThreadId?: ThreadId,
): ProjectionSnapshotQueryShape {
const shellSnapshot = {
snapshotSequence: 1,
projects: [],
projects:
leadThreadId === undefined
? []
: [
{
id: PROJECT_ID,
kind: "workspace" as const,
title: "Project",
workspaceRoot: "/repo/project",
defaultModelSelection: null,
scripts: [],
leadThreadId,
createdAt: daysAgo(60),
updatedAt: daysAgo(60),
},
],
threads: [...threads],
updatedAt: new Date(NOW_MS).toISOString(),
};
Expand Down Expand Up @@ -157,6 +173,7 @@ describe("ThreadAutoArchiveSweeper", () => {
async function createHarness(input: {
readonly inactiveDays: AutoArchiveInactiveThreadsDays;
readonly threads: readonly OrchestrationThreadShell[];
readonly leadThreadId?: ThreadId;
readonly failingThreadIds?: ReadonlySet<ThreadId>;
readonly settingsShape?: ServerSettingsShape;
/** The children each parent's archive takes along, as the decider would decide. */
Expand Down Expand Up @@ -243,7 +260,12 @@ describe("ThreadAutoArchiveSweeper", () => {
})
: Layer.succeed(ServerSettingsService, input.settingsShape),
),
Layer.provideMerge(Layer.succeed(ProjectionSnapshotQuery, makeSnapshotQuery(input.threads))),
Layer.provideMerge(
Layer.succeed(
ProjectionSnapshotQuery,
makeSnapshotQuery(input.threads, input.leadThreadId),
),
),
Layer.provideMerge(Layer.succeed(OrchestrationEngineService, orchestrationEngine)),
);
runtime = ManagedRuntime.make(layer);
Expand Down Expand Up @@ -318,10 +340,13 @@ describe("ThreadAutoArchiveSweeper", () => {
inactiveDays: 30,
threads: [
thread("pinned", { pinnedAt: daysAgo(40) }),
// The project's lead chat: archiving it would end its role.
thread("lead"),
{ ...running, session: runningSession(running.id) },
thread("approval", { hasPendingApprovals: true }),
thread("recent", { updatedAt: daysAgo(2) }),
],
leadThreadId: ThreadId.make("lead"),
});

expect(await runtime!.runPromise(sweeper.sweepNow())).toBe(0);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,15 @@ const makeThreadAutoArchiveSweeper = (options?: ThreadAutoArchiveSweeperLiveOpti
)
.map((thread) => thread.parentThreadId),
);
const leadThreadIds = new Set(
snapshot.projects.flatMap((project) =>
project.leadThreadId != null ? [project.leadThreadId] : [],
),
);
const candidates = selectAutoArchiveCandidates({
threads: snapshot.threads,
threads: snapshot.threads.map((thread) =>
leadThreadIds.has(thread.id) ? { ...thread, lead: true } : thread,
),
inactiveDays,
nowMs,
isExcluded: (thread) => liveChildParents.has(thread.id),
Expand Down
26 changes: 26 additions & 0 deletions apps/server/src/provider/Layers/ClaudeAdapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12485,6 +12485,32 @@ describe("ClaudeAdapterLive goals", () => {
},
);

it.effect("puts a goal's context ahead of /goal without a turn of its own", () => {
const harness = makeHarness();
return Effect.gen(function* () {
const { adapter } = yield* startGoalSession(harness);
const setting = yield* adapter.setThreadGoal!({
threadId: THREAD_ID,
objective: "Tests pass",
origin: "user",
context: "This thread is the lead chat.",
}).pipe(Effect.forkChild);
const sent = yield* Effect.promise(() =>
readPromptMessages(harness.getLastCreateQueryInput(), 2),
);
assert.deepEqual(sent.map(promptMessageShape), [
{ origin: undefined, shouldQuery: false, text: "This thread is the lead chat." },
{ origin: { kind: "human" }, shouldQuery: undefined, text: "/goal Tests pass" },
]);
harness.query.emit(goalReply("Tests pass", "Goal set: Tests pass"));
const goal = yield* Fiber.join(setting);
assert.equal(goal.objective, "Tests pass");
}).pipe(
Effect.provideService(Random.Random, makeDeterministicRandomService()),
Effect.provide(harness.layer),
);
});

// As Claude Code 2.1.301 answers it: the running turn's result comes first,
// then the clear's own answer and its zero-turn result.
it.effect(
Expand Down
27 changes: 18 additions & 9 deletions apps/server/src/provider/Layers/ClaudeAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6744,23 +6744,27 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const queueGoalCommand = Effect.fn("queueGoalCommand")(function* (
context: ClaudeSessionContext,
command: { readonly kind: "set" | "clear"; readonly args: string },
goalContext?: string,
) {
const reply = yield* Deferred.make<ClaudeGoalCommandOutcome>();
const request: ClaudeGoalCommandRequest = { ...command, sentAtMs: Date.now() };
context.goalCommand = { ...request, reply };
const messages: Array<SDKUserMessage> = [];
// A goal can be the first thing a thread handed over from another agent
// asks for; the handoff's context goes in ahead of it, as it would ahead
// of a message.
// of a message. So does what the goal's work should read first (a lead
// chat's role), unless a turn is running: that turn already heard it.
const seed = context.pendingContextSeedText;
if (
command.kind === "set" &&
seed !== undefined &&
supportsClaudeAppendOnly(context.cliVersion)
) {
const leading =
command.kind === "set" && supportsClaudeAppendOnly(context.cliVersion)
? [seed, context.turnState ? undefined : goalContext]
.filter((part): part is string => part !== undefined && part.trim().length > 0)
.join("\n\n")
: "";
if (leading.length > 0) {
messages.push(
deliverAsWritten(
buildUserMessage({ sdkContent: [{ type: "text", text: seed }], appendOnly: true }),
buildUserMessage({ sdkContent: [{ type: "text", text: leading }], appendOnly: true }),
context.cliVersion,
),
);
Expand Down Expand Up @@ -6788,8 +6792,9 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
const sendGoalCommand = Effect.fn("sendGoalCommand")(function* (
context: ClaudeSessionContext,
command: { readonly kind: "set" | "clear"; readonly args: string },
goalContext?: string,
) {
const { reply, request } = yield* queueGoalCommand(context, command);
const { reply, request } = yield* queueGoalCommand(context, command, goalContext);
yield* ensureGoalWatch(context);
const outcome = yield* Deferred.await(reply).pipe(
Effect.timeoutOption(CLAUDE_GOAL_REPLY_TIMEOUT),
Expand Down Expand Up @@ -6920,7 +6925,11 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* (
threadId: input.threadId,
modelSelection: input.modelSelection,
});
const outcome = yield* sendGoalCommand(context, { kind: "set", args: objective });
const outcome = yield* sendGoalCommand(
context,
{ kind: "set", args: objective },
input.context,
);
if (!outcome.accepted) {
return yield* refuse(outcome.text.length > 0 ? outcome.text : "Claude did not set the goal.");
}
Expand Down
Loading
Loading