feat(server): hand a thread off to a linked environment #16751
Closedjuliusmarmingewants to merge 1 commit into
t3code/peer/handoff-git fromt3code/peer/handoffopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
juliusmarminge added labelsmacroscope-review
- @@ -0,0 +150,21 @@150+ );151+ // The project's own identity reads blank while its cache is cold.152+ const key =153+ here === undefined154+ ? undefined155+ : (yield* repositoryIdentities.resolve(here.workspaceRoot))?.canonicalKey;156+ if (key === undefined) {157+ return yield* failure(158+ "target_required",159+ "This thread's project has no repository to match there. Pick the project there.",160+ );161+ }162+ const listed = yield* forwarding.call(163+ scope,164+ ProjectToolkit.tools.t3_project_list,165+ environmentId,166+ {167+ limit: 100,168+ },169+ );170+ const matches = listed.projects.filter(@@ -1251,3 +1270,5 @@12511270 if (12521271 projection.thread.archivedAt !== null ||12531272 projection.thread.deletedAt !== null ||1273+ // A thread waiting to move, moving or moved starts nothing more here.1274+ (projection.thread.handoff !== undefined && projection.thread.handoff.state !== "failed") ||@@ -0,0 +454,21 @@454+ /** A pending move whose turn ended departs; one a restart cut short is settled. */455+ const settle = (threadId: ThreadId) =>456+ Effect.gen(function* () {457+ const records = yield* threads.getThreadRecords(threadId, ["runs", "messages"], {458+ messageRoles: ["user"],459+ });460+ const handoff = records.thread.handoff;461+ if (handoff === undefined) return;462+ if (handoff.state === "pending") {463+ const live = records.runs.some(464+ (run) =>465+ run.status === "running" ||466+ run.status === "starting" ||467+ run.status === "waiting" ||468+ run.status === "preparing",469+ );470+ if (live) return;471+ // Someone wrote during the turn the agent asked in, steered into it or472+ // queued after it: new instructions win. That is the user, or an agent473+ // the user works through, such as an orchestrator.474+ const asked = records.runs.at(-1)?.requestedAt;@@ -0,0 +49,21 @@49+ "The bundle must be a pending upload from t3_attachment_prepare_upload.",50+ );51+ }52+ const bundlePath = resolveAttachmentPathById({53+ attachmentsDir: config.attachmentsDir,54+ attachmentId: input.bundle.attachmentId,55+ });56+ if (bundlePath === null) {57+ return yield* failure("The bundle upload was not found. Upload it again.");58+ }59+ const worktreesSetting = yield* settings.getSettings.pipe(60+ Effect.map((current) => current.worktreesDirectory),61+ Effect.orElseSucceed(() => ""),62+ );63+ const parent = resolveWorktreesDirectory(worktreesSetting, config.worktreesDir, path);64+ if (parent === null) {65+ return yield* failure(66+ "This environment's worktree location is not usable. Fix it in Settings → Storage.",67+ );68+ }69+ const name = (input.bundle.branch ?? `handoff-${input.handoffId}`).replace(/\//g, "-");@@ -10514,3 +10590,5 @@1051410590 threadId: command.threadId,1051510591 });1051610592 }10593+ // A thread moving away, or gone, takes no new turns here.10594+ if (thread.handoff?.state === "departing" || thread.handoff?.state === "departed") {@@ -0,0 +107,21 @@107+ thread: {108+ threadId: thread.id,109+ providerSessionId: `handoff:${thread.id}`,110+ providerInstanceId: thread.providerInstanceId as never,111+ },112+ client: undefined,113+ capabilities: new Set(["orchestration"]),114+ issuedAt: 0,115+ });116+117+ const setHandoff = (118+ threadId: ThreadId,119+ expected: HandoffState | null,120+ handoff: OrchestrationV2ThreadHandoff | null,121+ step: string,122+ ) =>123+ threads124+ .dispatch({125+ type: "thread.handoff.update",126+ commandId: CommandId.make(127+ `command:handoff:${threadId}:${handoff?.handoffId ?? "clear"}:${step}`,@@ -0,0 +425,21 @@425+ run.status === "queued" ||426+ run.status === "preparing",427+ );428+ const base = {429+ handoffId,430+ environmentId: input.environmentId,431+ label: link.label,432+ ...(input.continuationPrompt === undefined433+ ? {}434+ : { continuationPrompt: input.continuationPrompt }),435+ };436+ if (busy) {437+ if (input.whenTurnEnds !== true) {438+ return yield* failure(439+ "invalid_request",440+ "The thread is running a turn. Stop it, or let it move when the turn ends.",441+ );442+ }443+ const pending: OrchestrationV2ThreadHandoff = { state: "pending", ...base };444+ yield* setHandoff(input.threadId, current, pending, "pending");445+ return pending;@@ -0,0 +76,21 @@76+ handoffId: input.handoffId,77+ bundlePath,78+ branch: input.bundle.branch,79+ tip: input.bundle.tip,80+ snapshot: input.bundle.snapshot,81+ })82+ .pipe(83+ Effect.mapError(84+ (error) =>85+ new OrchestratorMcpFailure({86+ code: error.reason === "git_failed" ? "orchestration_error" : "invalid_request",87+ message: error.message,88+ }),89+ ),90+ Effect.ensuring(deletePendingAttachment(input.bundle.attachmentId).pipe(Effect.ignore)),91+ );92+ const processes = yield* VcsProcess.VcsProcess;93+ return {94+ worktreePath,95+ branch: applied.branch,96+ undo: processes@@ -0,0 +408,21 @@408+ );409+ if (link === undefined) {410+ return yield* failure("invalid_request", "That environment is not linked.");411+ }412+ // Fails now, while the asking agent can still say so, rather than after its turn.413+ yield* remoteProject(414+ scopeFor(thread),415+ input.environmentId,416+ thread.projectId,417+ input.projectId,418+ );419+ const handoffId = (yield* crypto.randomUUIDv4.pipe(Effect.orDie)).replaceAll("-", "");420+ const busy = records.runs.some(421+ (run) =>422+ run.status === "running" ||423+ run.status === "starting" ||424+ run.status === "waiting" ||425+ run.status === "queued" ||426+ run.status === "preparing",427+ );428+ const base = {@@ -0,0 +305,21 @@305+ projectId,306+ title: thread.title,307+ modelSelection: thread.modelSelection,308+ runtimeMode: thread.runtimeMode,309+ interactionMode: thread.interactionMode,310+ messages: yield* conversation(threadId),311+ continuationPrompt: handoff.continuationPrompt ?? DEFAULT_CONTINUATION,312+ ...(packed === undefined || attachmentId === undefined313+ ? {}314+ : {315+ bundle: {316+ attachmentId,317+ branch: packed.branch,318+ tip: packed.tip,319+ snapshot: packed.snapshot,320+ },321+ }),322+ },323+ );324+ }).pipe(Effect.scoped, Effect.result);325+ if (result._tag === "Failure") {@@ -152,3 +164,4 @@152164 .pipe(Effect.orElseSucceed(() => null));153165 let created = false;154166 if (existing === null) {167+ const workspace = input.workspace === undefined ? undefined : yield* input.workspace;
- @@ -10514,3 +10590,12 @@1051410590 threadId: command.threadId,1051510591 });1051610592 }10593+ // A thread moving away, or gone, takes no new turns here.10594+ if (thread.handoff?.state === "departing" || thread.handoff?.state === "departed") {10595+ return yield* new OrchestratorThreadMovedError({10596+ commandId: command.commandId,10597+ threadId: command.threadId,10598+ label: thread.handoff.label,10599+ state: thread.handoff.state,10600+ });10601+ }@@ -0,0 +84,21 @@84+ (error) =>85+ new OrchestratorMcpFailure({86+ code: error.reason === "git_failed" ? "orchestration_error" : "invalid_request",87+ message: error.message,88+ }),89+ ),90+ Effect.ensuring(deletePendingAttachment(input.bundle.attachmentId).pipe(Effect.ignore)),91+ );92+ const processes = yield* VcsProcess.VcsProcess;93+ return {94+ worktreePath,95+ branch: applied.branch,96+ undo: processes97+ .run({98+ operation: "HandoffImport.undo",99+ command: "git",100+ cwd: input.repoRoot,101+ args: ["worktree", "remove", "--force", worktreePath],102+ })103+ .pipe(Effect.ignore),104+ } satisfies ImportedWorkspace;@@ -0,0 +319,21 @@319+ snapshot: packed.snapshot,320+ },321+ }),322+ },323+ );324+ }).pipe(Effect.scoped, Effect.result);325+ if (result._tag === "Failure") {326+ yield* setHandoff(327+ threadId,328+ "departing",329+ {330+ state: "failed",331+ handoffId: handoff.handoffId,332+ environmentId: handoff.environmentId,333+ label: handoff.label,334+ lastError: result.failure.message,335+ },336+ "failed",337+ ).pipe(Effect.ignore);338+ return yield* Effect.fail(result.failure);339+ }@@ -0,0 +425,21 @@425+ run.status === "queued" ||426+ run.status === "preparing",427+ );428+ const base = {429+ handoffId,430+ environmentId: input.environmentId,431+ label: link.label,432+ ...(input.continuationPrompt === undefined433+ ? {}434+ : { continuationPrompt: input.continuationPrompt }),435+ };436+ if (busy) {437+ if (input.whenTurnEnds !== true) {438+ return yield* failure(439+ "invalid_request",440+ "The thread is running a turn. Stop it, or let it move when the turn ends.",441+ );442+ }443+ const pending: OrchestrationV2ThreadHandoff = { state: "pending", ...base };444+ yield* setHandoff(input.threadId, current, pending, "pending");445+ return pending;@@ -0,0 +461,21 @@461+ if (handoff === undefined) return;462+ if (handoff.state === "pending") {463+ const live = records.runs.some(464+ (run) =>465+ run.status === "running" ||466+ run.status === "starting" ||467+ run.status === "waiting" ||468+ run.status === "preparing",469+ );470+ if (live) return;471+ // Someone wrote during the turn the agent asked in, steered into it or472+ // queued after it: new instructions win. That is the user, or an agent473+ // the user works through, such as an orchestrator.474+ const asked = records.runs.at(-1)?.requestedAt;475+ const writtenSince = records.messages.some(476+ (message) => asked !== undefined && DateTime.isGreaterThan(message.createdAt, asked),477+ );478+ if (writtenSince || records.runs.some((run) => run.status === "queued")) {479+ yield* setHandoff(threadId, "pending", null, "cancel-by-user");480+ return;481+ }@@ -0,0 +494,21 @@494+ const shells = yield* projections.getShellSnapshot().pipe(495+ Effect.map((snapshot) => snapshot.threads),496+ Effect.orElseSucceed(() => []),497+ );498+ yield* Effect.forEach(499+ shells.filter(500+ (shell) => shell.handoff?.state === "pending" || shell.handoff?.state === "departing",501+ ),502+ (shell) => settle(shell.id),503+ { discard: true },504+ );505+ yield* threads.streamStoredEvents.pipe(506+ Stream.filter(507+ (stored) =>508+ stored.event.type === "run.updated" &&509+ ["completed", "failed", "cancelled", "interrupted", "rolled_back"].includes(510+ stored.event.payload.status,511+ ),512+ ),513+ Stream.runForEach((stored) => settle(stored.event.threadId)),514+ );
- @@ -736,0 +751,21 @@751+ success: Schema.Struct({752+ options: Schema.Array(753+ Schema.Struct({754+ environmentId: EnvironmentId,755+ label: Schema.String,756+ projectId: Schema.NullOr(ProjectId),757+ reason: Schema.NullOr(Schema.String),758+ }),759+ ),760+ }),761+ error: Schema.Union([762+ Schema.TaggedStruct("ThreadHandoffError", ThreadHandoffError.fields),763+ EnvironmentAuthorizationError,764+ ]),765+});766+767+const WsThreadHandoffStartRpc = Rpc.make(WS_METHODS.threadHandoffStart, {768+ payload: Schema.Struct({769+ threadId: ThreadId,770+ environmentId: EnvironmentId,771+ projectId: Schema.optional(ProjectId),
- @@ -226,4 +235,20 @@235+ });226236 if (input.worktreePath !== undefined)227237 yield* assertProjectWorktree(project.workspaceRoot, input.worktreePath);228238 const imports = yield* ThreadImportService.ThreadImportService;229- return yield* imports.importThread({ ...input, runtimeMode, interactionMode, linkOrigin });239+ const bundle = input.bundle;240+ const context = yield* Effect.context<241+ | ServerConfig.ServerConfig242+ | Settings.ServerSettingsService243+ | VcsProcess.VcsProcess244+ | FileSystem.FileSystem245+ | Path.Path246+ >();247+ const workspace =248+ bundle === undefined249+ ? undefined250+ : HandoffImport.applyBundle({251+ repoRoot: project.workspaceRoot,252+ handoffId: input.source.handoffId,253+ bundle,254+ }).pipe(Effect.provideContext(context));
- @@ -6722,0 +6746,21 @@6746+ function* (6747+ command: Extract<OrchestrationV2InternalCommand, { readonly type: "thread.handoff.update" }>,6748+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,6749+ ) {6750+ const projection = yield* projectionStore6751+ .getThreadRecords(command.threadId, ["runs"])6752+ .pipe(6753+ Effect.mapError(6754+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),6755+ ),6756+ );6757+ const thread = projection.thread;6758+ const reject = (cause: string) =>6759+ new OrchestratorDispatchError({6760+ commandId: command.commandId,6761+ commandType: command.type,6762+ cause,6763+ });6764+ if (thread.deletedAt !== null) return yield* reject(`Thread ${thread.id} is deleted.`);6765+ const current = thread.handoff?.state ?? null;6766+ if (current !== command.expected) {
tanstack-source added labelsfeature
juliusmarminge closed this
Sign in to join this conversation.
Thread transfer impact#
✅ Thread transfer remains within every enforced ceiling.
Baseline: unavailable · PR result:
8a5e546· Source CI: failureScenario and decoded snapshot size
10 historical turns, 5 command tools per turn, 878.9 KiB retained MCP result per historical turn, and a 1.05 MiB retained result in the measured turn.
Updated in place by a trusted workflow. PR artifacts are strictly validated and never executed.