@devries-cameron20 / t3code-1 / commits / 58e60bf5e8
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

feat: turn a No project thread into a project (#26767)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 29, 2026 at 02:27 UTC 58e60bf5e808fc226d9b769d66d1ea9fec014d23
27 files changed +879 -22
apps/mobile/src/features/threads/thread-list-v2-items.tsx
+20 -1
@@ -62,6 +62,8 @@ import { useThreadPr } from "../../state/use-thread-pr";
62 import { useSwipeRowDormant } from "../home/swipe-row-activation";
63 import { ThreadSwipeable } from "../home/thread-swipe-actions";
64 import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
65 +import { canTurnThreadIntoProject, turnThreadIntoProject } from "./turnThreadIntoProject";
66 +import { threadCanArchive } from "../home/threadArchive";
67 import {
68 THREAD_LIST_V2_SETTLED_PAGE_COUNT,
69 resolveThreadListV2SnoozeGateExpiryMs,
@@ -837,6 +839,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
839 : [],
840 [props.autoSettleOptOutSupported, thread.autoSettleDisabledAt],
841 );
842 + const canTurnIntoProject = canTurnThreadIntoProject(thread);
843 const titleMenuItems = useMemo<MenuAction[]>(
844 () => [
845 { id: "rename", title: "Rename", image: "square.and.pencil" },
@@ -844,8 +847,23 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
847 supported: props.titleRegenerationSupported,
848 isRegenerating: thread.titleRegeneration != null,
849 }),
850 + ...(canTurnIntoProject
851 + ? [
852 + {
853 + id: "turn-into-project",
854 + title: "Turn into project",
855 + image: "folder.badge.plus",
856 + attributes: { disabled: !threadCanArchive(thread.runtime) },
857 + } satisfies MenuAction,
858 + ]
859 + : []),
860 + ],
861 + [
862 + canTurnIntoProject,
863 + props.titleRegenerationSupported,
864 + thread.runtime,
865 + thread.titleRegeneration,
866 ],
848 - [props.titleRegenerationSupported, thread.titleRegeneration],
867 );
868 const snoozableCardMenuActions = useMemo<MenuAction[]>(
869 () => [
@@ -923,6 +941,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
941 if (nativeEvent.event === "archive") handleArchive();
942 if (nativeEvent.event === "rename") handleRename();
943 if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
944 + if (nativeEvent.event === "turn-into-project") void turnThreadIntoProject(thread);
945 if (nativeEvent.event === "copy-thread") {
946 const target = threadChipCopyTarget(
947 { environmentId: thread.environmentId, threadId: thread.id },
apps/mobile/src/features/threads/turnThreadIntoProject.ts new
+47
@@ -0,0 +1,47 @@
1 +import {
2 + isAtomCommandInterrupted,
3 + runAtomCommand,
4 + squashAtomCommandFailure,
5 +} from "@t3tools/client-runtime/state/runtime";
6 +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
7 +import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
8 +import * as Haptics from "expo-haptics";
9 +
10 +import * as Dialog from "../../components/ui/Dialog";
11 +import { appAtomRegistry } from "../../state/atom-registry";
12 +import { environmentProjects, projectEnvironment } from "../../state/projects";
13 +import { environmentServerConfigsAtom } from "../../state/server";
14 +import { readEnvironmentScope } from "../../state/session";
15 +
16 +/** A No project thread that already has its own folder, on a server that can promote it. */
17 +export function canTurnThreadIntoProject(thread: EnvironmentThreadShell): boolean {
18 + if (thread.worktreePath === null) return false;
19 + const config = appAtomRegistry.get(environmentServerConfigsAtom).get(thread.environmentId);
20 + if (config?.environment.capabilities.threadProjectFromScratch !== true) return false;
21 + const project = appAtomRegistry.get(
22 + environmentProjects.projectAtom({
23 + environmentId: thread.environmentId,
24 + projectId: thread.projectId,
25 + }),
26 + );
27 + return project?.isScratch === true;
28 +}
29 +
30 +export async function turnThreadIntoProject(thread: EnvironmentThreadShell): Promise<void> {
31 + const title = "Could not turn thread into a project";
32 + if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) {
33 + Dialog.alert(title, "This connection cannot change threads.");
34 + return;
35 + }
36 + void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
37 + const result = await runAtomCommand(
38 + appAtomRegistry,
39 + projectEnvironment.createFromThread,
40 + { environmentId: thread.environmentId, input: { threadId: thread.id } },
41 + { reportFailure: false },
42 + );
43 + if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
44 + const error = squashAtomCommandFailure(result);
45 + Dialog.alert(title, error instanceof Error ? error.message : "Try again.");
46 + }
47 +}
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -246,6 +246,7 @@ export const make = Effect.gen(function* () {
246 threadPinReorder: true,
247 threadActiveReorder: true,
248 threadAutoSettleOptOut: true,
249 + threadProjectFromScratch: true,
250 threadTitleRegeneration: true,
251 commandOutputStreaming: true,
252 threadVisitedTracking: true,
apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+1
@@ -182,6 +182,7 @@ const layerUnusedScheduledTaskStub = Layer.succeed(
182 setEnabled: () => Effect.die("ScheduledTaskService.setEnabled is unused in this test"),
183 delete: () => Effect.die("ScheduledTaskService.delete is unused in this test"),
184 deleteForThread: () => Effect.die("unused in this test"),
185 + moveThreadTasks: () => Effect.die("unused in this test"),
186 runNow: () => Effect.die("ScheduledTaskService.runNow is unused in this test"),
187 rotateWebhookToken: () => Effect.die("unused in this test"),
188 listWebhookDeliveries: () => Effect.die("unused in this test"),
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -150,6 +150,7 @@ const RPC_AGGREGATES = {
150 [WS_METHODS.projectsWriteFile]: "workspace",
151 [WS_METHODS.projectsEnsureScratch]: "orchestration",
152 [WS_METHODS.projectsCreateNew]: "orchestration",
153 + [WS_METHODS.projectsCreateFromThread]: "orchestration",
154 [WS_METHODS.shellOpenInEditor]: "workspace",
155 [WS_METHODS.filesystemBrowse]: "workspace",
156 [WS_METHODS.filesystemGetMetadata]: "workspace",
apps/server/src/orchestration-v2/Orchestrator.ts
+71
@@ -455,6 +455,23 @@ function wakeWorkStartedAt(
455
456 const threadPullRequestLinksEqual = Schema.toEquivalence(Schema.NullOr(ThreadLinkedPullRequest));
457
458 +/** Unfinished runs (including queued) or open requests block moving a thread to another project. */
459 +export function threadHasUnfinishedWork(records: {
460 + readonly runs: ReadonlyArray<{ readonly status: string }>;
461 + readonly runtimeRequests: ReadonlyArray<{ readonly status: string }>;
462 +}): boolean {
463 + return (
464 + records.runs.some(
465 + (run) =>
466 + run.status !== "completed" &&
467 + run.status !== "failed" &&
468 + run.status !== "cancelled" &&
469 + run.status !== "interrupted" &&
470 + run.status !== "rolled_back",
471 + ) || records.runtimeRequests.some((request) => request.status === "pending")
472 + );
473 +}
474 +
475 function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
476 switch (command.type) {
477 case "thread.create":
@@ -486,6 +503,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
503 case "thread.pull-request-watch.sync":
504 case "thread.pull-request.sync":
505 case "thread.title.regeneration.complete":
506 + case "thread.project.adopt-folder":
507 case "thread.runtime-mode.set":
508 case "thread.interaction-mode.set":
509 case "thread.model-selection.set":
@@ -3983,6 +4001,56 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
4001 },
4002 );
4003
4004 + const dispatchThreadProjectAdoptFolder = Effect.fn(
4005 + "orchestrationV2.dispatch.threadProjectAdoptFolder",
4006 + )(function* (
4007 + command: Extract<
4008 + OrchestrationV2ServerCommand,
4009 + { readonly type: "thread.project.adopt-folder" }
4010 + >,
4011 + events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
4012 + ) {
4013 + const reject = (cause: string) =>
4014 + new OrchestratorDispatchError({
4015 + commandId: command.commandId,
4016 + commandType: command.type,
4017 + cause: `Thread ${command.threadId} ${cause}`,
4018 + });
4019 + const projection = yield* projectionStore
4020 + .getThreadRecords(command.threadId, ["runs", "runtimeRequests"], { turnItemTypes: [] })
4021 + .pipe(
4022 + Effect.mapError(
4023 + (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
4024 + ),
4025 + );
4026 + const thread = projection.thread;
4027 + if (thread.deletedAt !== null) return yield* reject("is deleted.");
4028 + if (threadHasUnfinishedWork(projection)) {
4029 + return yield* reject("still has work in progress. Finish or stop it first.");
4030 + }
4031 + const current = yield* projects.get(thread.projectId).pipe(mapDispatchError(command));
4032 + const target = yield* projects.get(command.projectId).pipe(mapDispatchError(command));
4033 + if (Option.isNone(target) || target.value.deletedAt !== null) {
4034 + return yield* reject(`cannot move to missing project ${command.projectId}.`);
4035 + }
4036 + // The thread always lands in the project root, so the move must not change its cwd.
4037 + const cwd = thread.worktreePath ?? Option.getOrUndefined(current)?.workspaceRoot;
4038 + if (cwd !== target.value.workspaceRoot) {
4039 + return yield* reject(`does not work in ${target.value.workspaceRoot}.`);
4040 + }
4041 + const now = yield* DateTime.now;
4042 + yield* emit(
4043 + events,
4044 + command,
4045 + )({
4046 + type: "thread.metadata-updated",
4047 + threadId: command.threadId,
4048 + providerInstanceId: thread.providerInstanceId,
4049 + occurredAt: now,
4050 + payload: { ...thread, projectId: command.projectId, worktreePath: null, updatedAt: now },
4051 + });
4052 + });
4053 +
4054 const refuseAboveDispatchModeLimit = Effect.fn("orchestrationV2.dispatch.refuseAboveModeLimit")(
4055 function* (
4056 command: OrchestrationV2ServerCommand,
@@ -12487,6 +12555,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
12555 case "provider-session.detach":
12556 yield* dispatchProviderSessionDetach(command, events, effects);
12557 break;
12558 + case "thread.project.adopt-folder":
12559 + yield* dispatchThreadProjectAdoptFolder(command, events);
12560 + break;
12561 case "message.dispatch": {
12562 // Providers own native subagent conversations; messages cannot target them, and adapters ask questions on the parent.
12563 const thread = yield* projectionStore
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+276
@@ -37,6 +37,7 @@ import * as DateTime from "effect/DateTime";
37 import * as Deferred from "effect/Deferred";
38 import * as Fiber from "effect/Fiber";
39 import * as Layer from "effect/Layer";
40 +import * as Option from "effect/Option";
41 import * as Path from "effect/Path";
42 import * as Queue from "effect/Queue";
43 import * as Stream from "effect/Stream";
@@ -76,6 +77,7 @@ import { shellStreamItemFromThreadShell } from "./ShellStream.ts";
77 import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
78 import * as ThreadManagementService from "./ThreadManagementService.ts";
79 import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
80 +import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts";
81 import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
82 import * as Scheduler from "../scheduling/Scheduler.ts";
83 import * as SecretRequests from "../secrets/SecretRequests.ts";
@@ -5805,6 +5807,198 @@ it.layer(layerTest)("snooze queued runs", (it) => {
5807 );
5808 });
5809
5810 +const SCRATCH_ROOT = "/tmp/runtime-layer-promotion-scratch";
5811 +const SCRATCH_PROJECT_ID = ProjectId.make("runtime-layer-promotion-scratch");
5812 +const layerScratchPromotionTest = ScratchThreadPromotion.layer.pipe(
5813 + Layer.provide(
5814 + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
5815 + scratchRoot: Effect.succeedSome(SCRATCH_ROOT),
5816 + isScratchProject: (projectId) => Effect.succeed(projectId === SCRATCH_PROJECT_ID),
5817 + namedProjectsRoot: "/projects",
5818 + }),
5819 + ),
5820 + Layer.provide(NodeServices.layer),
5821 + Layer.provideMerge(layerProjectDeletionTest),
5822 +);
5823 +
5824 +it.layer(layerScratchPromotionTest)("turning a No project thread into a project", (it) => {
5825 + const setup = Effect.fn(function* (name: string) {
5826 + const projects = yield* ProjectService.ProjectService;
5827 + const orchestrator = yield* Orchestrator.OrchestratorV2;
5828 + const folder = `${SCRATCH_ROOT}/2026-01-01-${name}`;
5829 + if (Option.isNone(yield* projects.getById(SCRATCH_PROJECT_ID))) {
5830 + yield* projects.create({
5831 + commandId: CommandId.make("promotion-scratch-create"),
5832 + projectId: SCRATCH_PROJECT_ID,
5833 + title: "No project",
5834 + workspaceRoot: SCRATCH_ROOT,
5835 + });
5836 + }
5837 + const createThread = (suffix: string, worktreePath: string) =>
5838 + orchestrator
5839 + .dispatch({
5840 + type: "thread.create",
5841 + createdBy: "user",
5842 + creationSource: "web",
5843 + commandId: CommandId.make(`promotion-${name}-${suffix}-create`),
5844 + threadId: ThreadId.make(`promotion-${name}-${suffix}`),
5845 + projectId: SCRATCH_PROJECT_ID,
5846 + title: `${name} ${suffix}`,
5847 + modelSelection,
5848 + runtimeMode: "full-access",
5849 + interactionMode: "default",
5850 + branch: null,
5851 + worktreePath,
5852 + })
5853 + .pipe(Effect.as(ThreadId.make(`promotion-${name}-${suffix}`)));
5854 + return { folder, createThread };
5855 + });
5856 + const shellOf = (threadId: ThreadId) =>
5857 + Orchestrator.OrchestratorV2.pipe(
5858 + Effect.flatMap((orchestrator) => orchestrator.getThreadShell(threadId)),
5859 + );
5860 +
5861 + it.effect("moves every thread in the folder and its bound tasks into one project", () =>
5862 + Effect.gen(function* () {
5863 + const promotion = yield* ScratchThreadPromotion.ScratchThreadPromotion;
5864 + const projects = yield* ProjectService.ProjectService;
5865 + const orchestrator = yield* Orchestrator.OrchestratorV2;
5866 + const tasks = yield* ScheduledTaskService.ScheduledTaskService;
5867 + const { folder, createThread } = yield* setup("moves");
5868 + const threadId = yield* createThread("main", folder);
5869 + const siblingId = yield* createThread("sibling", folder);
5870 + const otherId = yield* createThread("other", `${SCRATCH_ROOT}/2026-01-01-elsewhere`);
5871 + yield* orchestrator.dispatch({
5872 + type: "thread.archive",
5873 + commandId: CommandId.make("promotion-moves-sibling-archive"),
5874 + threadId: siblingId,
5875 + });
5876 + const { task } = yield* tasks.upsert({
5877 + id: ScheduledTaskId.make("promotion-moves-bound"),
5878 + title: "Bound",
5879 + prompt: "Check in",
5880 + enabled: true,
5881 + schedule: { type: "interval", everyMs: 60_000 },
5882 + projectId: SCRATCH_PROJECT_ID,
5883 + threadId: siblingId,
5884 + workspaceStrategy: { type: "root" },
5885 + modelSelection,
5886 + runtimeMode: "full-access",
5887 + interactionMode: "default",
5888 + createdBy: "user",
5889 + creationSource: "web",
5890 + });
5891 +
5892 + const { projectId } = yield* promotion.promote({ threadId });
5893 +
5894 + const project = yield* projects.getById(projectId);
5895 + assert.equal(Option.getOrUndefined(project)?.workspaceRoot, folder);
5896 + assert.equal(Option.getOrUndefined(project)?.title, "moves main");
5897 + for (const id of [threadId, siblingId]) {
5898 + const shell = yield* shellOf(id);
5899 + assert.equal(shell?.projectId, projectId);
5900 + assert.isNull(shell?.worktreePath);
5901 + }
5902 + assert.equal((yield* shellOf(otherId))?.projectId, SCRATCH_PROJECT_ID);
5903 + const saved = (yield* tasks.list()).tasks.find((candidate) => candidate.id === task.id);
5904 + assert.equal(saved?.projectId, projectId);
5905 + assert.deepEqual(yield* promotion.promote({ threadId }), { projectId });
5906 + }),
5907 + );
5908 +
5909 + it.effect("changes nothing while a thread in the folder is busy", () =>
5910 + Effect.gen(function* () {
5911 + const promotion = yield* ScratchThreadPromotion.ScratchThreadPromotion;
5912 + const projects = yield* ProjectService.ProjectService;
5913 + const orchestrator = yield* Orchestrator.OrchestratorV2;
5914 + const { folder, createThread } = yield* setup("busy");
5915 + const threadId = yield* createThread("idle", folder);
5916 + const busyId = yield* createThread("delegate", folder);
5917 + yield* orchestrator.dispatch({
5918 + type: "message.dispatch",
5919 + createdBy: "user",
5920 + creationSource: "web",
5921 + commandId: CommandId.make("promotion-busy-message"),
5922 + threadId: busyId,
5923 + messageId: MessageId.make("promotion-busy-message"),
5924 + text: "Keep this run active.",
5925 + attachments: [],
5926 + modelSelection,
5927 + dispatchMode: { type: "start_immediately" },
5928 + });
5929 +
5930 + const error = yield* promotion.promote({ threadId }).pipe(Effect.flip);
5931 +
5932 + assert.equal(error.message, '"busy delegate" is still working. Finish or stop it first.');
5933 + assert.isTrue(Option.isNone(yield* projects.getByWorkspaceRoot(folder)));
5934 + assert.equal((yield* shellOf(threadId))?.projectId, SCRATCH_PROJECT_ID);
5935 + }),
5936 + );
5937 +
5938 + it.effect("finishes a partial move from either thread", () =>
5939 + Effect.gen(function* () {
5940 + const promotion = yield* ScratchThreadPromotion.ScratchThreadPromotion;
5941 + const projects = yield* ProjectService.ProjectService;
5942 + const orchestrator = yield* Orchestrator.OrchestratorV2;
5943 + const { folder, createThread } = yield* setup("partial");
5944 + const movedId = yield* createThread("moved", folder);
5945 + const leftId = yield* createThread("left", folder);
5946 + const earlier = yield* projects.create({
5947 + commandId: CommandId.make("promotion-partial-project"),
5948 + projectId: ProjectId.make("promotion-partial-project"),
5949 + title: "Earlier",
5950 + workspaceRoot: folder,
5951 + });
5952 + yield* orchestrator.dispatch({
5953 + type: "thread.project.adopt-folder",
5954 + commandId: CommandId.make("promotion-partial-adopt"),
5955 + threadId: movedId,
5956 + projectId: earlier.id,
5957 + });
5958 +
5959 + assert.deepEqual(yield* promotion.promote({ threadId: movedId }), { projectId: earlier.id });
5960 + assert.equal((yield* shellOf(leftId))?.projectId, earlier.id);
5961 + }),
5962 + );
5963 +
5964 + it.effect("refuses a thread outside No project", () =>
5965 + Effect.gen(function* () {
5966 + const promotion = yield* ScratchThreadPromotion.ScratchThreadPromotion;
5967 + const projects = yield* ProjectService.ProjectService;
5968 + const orchestrator = yield* Orchestrator.OrchestratorV2;
5969 + const projectId = ProjectId.make("promotion-regular-project");
5970 + const threadId = ThreadId.make("promotion-regular-thread");
5971 + yield* projects.create({
5972 + commandId: CommandId.make("promotion-regular-project"),
5973 + projectId,
5974 + title: "Regular",
5975 + workspaceRoot: "/tmp/runtime-layer-promotion-regular",
5976 + });
5977 + yield* orchestrator.dispatch({
5978 + type: "thread.create",
5979 + createdBy: "user",
5980 + creationSource: "web",
5981 + commandId: CommandId.make("promotion-regular-thread-create"),
5982 + threadId,
5983 + projectId,
5984 + title: "Regular",
5985 + modelSelection,
5986 + runtimeMode: "full-access",
5987 + interactionMode: "default",
5988 + branch: null,
5989 + worktreePath: null,
5990 + });
5991 +
5992 + const error = yield* promotion.promote({ threadId }).pipe(Effect.flip);
5993 +
5994 + assert.equal(
5995 + error.message,
5996 + "Only a No project thread with its own folder can become a project.",
5997 + );
5998 + }),
5999 + );
6000 +});
6001 +
6002 it.layer(layerSharedApplicationDataPlaneTest)("snooze projection", (it) => {
6003 it.effect("carries snooze state through the V2 shell projection", () =>
6004 Effect.gen(function* () {
@@ -5900,6 +6094,88 @@ it.layer(layerSharedApplicationDataPlaneTest)("snooze projection", (it) => {
6094 assert.isNull(awakened.thread.snoozedAt);
6095 }),
6096 );
6097 +
6098 + it.effect("moves a thread into a project rooted at its own folder", () =>
6099 + Effect.gen(function* () {
6100 + const projects = yield* ProjectService.ProjectService;
6101 + const orchestrator = yield* Orchestrator.OrchestratorV2;
6102 + const scratchProjectId = ProjectId.make("runtime-layer-adopt-scratch");
6103 + const folderProjectId = ProjectId.make("runtime-layer-adopt-folder");
6104 + const otherProjectId = ProjectId.make("runtime-layer-adopt-other");
6105 + const folder = "/tmp/runtime-layer-adopt-scratch/2026-01-01-notes-a1b2c3d4";
6106 + const createProject = (projectId: ProjectId, workspaceRoot: string) =>
6107 + projects.create({
6108 + commandId: CommandId.make(`${projectId}-create`),
6109 + projectId,
6110 + title: projectId,
6111 + workspaceRoot,
6112 + });
6113 + const createThread = (threadId: ThreadId) =>
6114 + orchestrator.dispatch({
6115 + type: "thread.create",
6116 + createdBy: "user",
6117 + creationSource: "web",
6118 + commandId: CommandId.make(`${threadId}-create`),
6119 + threadId,
6120 + projectId: scratchProjectId,
6121 + title: "Scratch work",
6122 + modelSelection,
6123 + runtimeMode: "full-access",
6124 + interactionMode: "default",
6125 + branch: null,
6126 + worktreePath: folder,
6127 + });
6128 + const adopt = (threadId: ThreadId, projectId: ProjectId, suffix: string) =>
6129 + orchestrator.dispatch({
6130 + type: "thread.project.adopt-folder",
6131 + commandId: CommandId.make(`${threadId}-adopt-${suffix}`),
6132 + threadId,
6133 + projectId,
6134 + });
6135 + yield* createProject(scratchProjectId, "/tmp/runtime-layer-adopt-scratch");
6136 + yield* createProject(folderProjectId, folder);
6137 + yield* createProject(otherProjectId, "/tmp/runtime-layer-adopt-other");
6138 + const idleThreadId = ThreadId.make("runtime-layer-adopt-idle");
6139 + const busyThreadId = ThreadId.make("runtime-layer-adopt-busy");
6140 + yield* createThread(idleThreadId);
6141 + yield* createThread(busyThreadId);
6142 + yield* orchestrator.dispatch({
6143 + type: "message.dispatch",
6144 + createdBy: "user",
6145 + creationSource: "web",
6146 + commandId: CommandId.make("runtime-layer-adopt-busy-message"),
6147 + threadId: busyThreadId,
6148 + messageId: MessageId.make("runtime-layer-adopt-busy-message"),
6149 + text: "Keep this run active.",
6150 + attachments: [],
6151 + modelSelection,
6152 + dispatchMode: { type: "start_immediately" },
6153 + });
6154 +
6155 + const otherFolder = yield* adopt(idleThreadId, otherProjectId, "other").pipe(Effect.flip);
6156 + assert.equal(
6157 + otherFolder.cause,
6158 + `Thread ${idleThreadId} does not work in /tmp/runtime-layer-adopt-other.`,
6159 + );
6160 + const missing = yield* adopt(idleThreadId, ProjectId.make("missing"), "missing").pipe(
6161 + Effect.flip,
6162 + );
6163 + assert.equal(missing.cause, `Thread ${idleThreadId} cannot move to missing project missing.`);
6164 + const busy = yield* adopt(busyThreadId, folderProjectId, "busy").pipe(Effect.flip);
6165 + assert.equal(
6166 + busy.cause,
6167 + `Thread ${busyThreadId} still has work in progress. Finish or stop it first.`,
6168 + );
6169 +
6170 + yield* adopt(idleThreadId, folderProjectId, "folder");
6171 + const shell = yield* orchestrator.getShellSnapshot();
6172 + const moved = shell.threads.find((thread) => thread.id === idleThreadId);
6173 + assert.equal(moved?.projectId, folderProjectId);
6174 + assert.isNull(moved?.worktreePath);
6175 + const stayed = shell.threads.find((thread) => thread.id === busyThreadId);
6176 + assert.equal(stayed?.projectId, scratchProjectId);
6177 + }),
6178 + );
6179 });
6180
6181 it.layer(layerSharedApplicationDataPlaneTest)("visited projection", (it) => {
apps/server/src/orchestration-v2/runtimeLayer.ts
+12
@@ -16,6 +16,7 @@ import * as AgentSessionScanner from "../project/AgentSessionScanner.ts";
16 import * as ProjectService from "../project/ProjectService.ts";
17 import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
18 import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
19 +import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts";
20 import * as CheckpointCaptureService from "./CheckpointCaptureService.ts";
21 import * as CheckpointService from "./CheckpointService.ts";
22 import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
@@ -289,6 +290,16 @@ const layerScheduledTaskProvided = ScheduledTaskService.layer.pipe(
290 ),
291 ),
292 );
293 +const layerScratchThreadPromotionProvided = ScratchThreadPromotion.layer.pipe(
294 + Layer.provide(
295 + Layer.mergeAll(
296 + layerProjectService,
297 + layerManagedProjectFoldersProvided,
298 + layerThreadManagementProvided,
299 + layerScheduledTaskProvided,
300 + ),
301 + ),
302 +);
303 const layerProviderContinuationWorkerProvided = ProviderContinuationService.layer.pipe(
304 Layer.provide(
305 Layer.mergeAll(
@@ -362,6 +373,7 @@ export const layerProduction = Layer.mergeAll(
373 layerManagedProjectFoldersProvided,
374 layerThreadLaunchProvided,
375 layerScheduledTaskProvided,
376 + layerScratchThreadPromotionProvided,
377 layerSecretRequestsProvided,
378 GuestShareService.layer.pipe(
379 Layer.provide(Layer.merge(layerOrchestratorProvided, layerCommandOutputHubProvided)),
apps/server/src/project/ScratchThreadPromotion.ts new
+161
@@ -0,0 +1,161 @@
1 +import {
2 + CommandId,
3 + type OrchestrationV2ThreadShell,
4 + ProjectId,
5 + type ThreadId,
6 +} from "@t3tools/contracts";
7 +import * as Context from "effect/Context";
8 +import * as Crypto from "effect/Crypto";
9 +import * as Effect from "effect/Effect";
10 +import * as Layer from "effect/Layer";
11 +import * as Option from "effect/Option";
12 +import * as Path from "effect/Path";
13 +import * as Schema from "effect/Schema";
14 +
15 +import { threadHasUnfinishedWork } from "../orchestration-v2/Orchestrator.ts";
16 +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
17 +import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
18 +import * as ManagedProjectFolders from "./ManagedProjectFolders.ts";
19 +import * as ProjectService from "./ProjectService.ts";
20 +
21 +export class ScratchThreadPromotionError extends Schema.TaggedError<ScratchThreadPromotionError>()(
22 + "ScratchThreadPromotionError",
23 + {
24 + reason: Schema.String,
25 + cause: Schema.optional(Schema.Defect()),
26 + },
27 +) {
28 + override get message(): string {
29 + return this.reason;
30 + }
31 +}
32 +
33 +export class ScratchThreadPromotion extends Context.Service<
34 + ScratchThreadPromotion,
35 + {
36 + /**
37 + * Turns a No project thread's folder into a project, in place, and moves every
38 + * thread working in that folder into it. Running it again finishes a partial move.
39 + */
40 + readonly promote: (input: {
41 + readonly threadId: ThreadId;
42 + }) => Effect.Effect<{ readonly projectId: ProjectId }, ScratchThreadPromotionError>;
43 + }
44 +>()("t3/project/ScratchThreadPromotion") {}
45 +
46 +const make = Effect.gen(function* () {
47 + const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
48 + const projects = yield* ProjectService.ProjectService;
49 + const threads = yield* ThreadManagementService.ThreadManagementService;
50 + const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
51 + const crypto = yield* Crypto.Crypto;
52 + const path = yield* Path.Path;
53 +
54 + const fail = (reason: string) => (cause: unknown) =>
55 + new ScratchThreadPromotionError({ reason, cause });
56 +
57 + const promote: ScratchThreadPromotion["Service"]["promote"] = Effect.fn(
58 + "ScratchThreadPromotion.promote",
59 + )(function* (input) {
60 + const thread = yield* threads.getThreadShell(input.threadId).pipe(
61 + Effect.mapError(fail("Could not read the thread.")),
62 + Effect.filterOrFail(
63 + (shell) => shell !== null,
64 + () => new ScratchThreadPromotionError({ reason: "Thread not found." }),
65 + ),
66 + );
67 + const project = yield* projects
68 + .getById(thread.projectId)
69 + .pipe(Effect.mapError(fail("Could not read the thread's project.")));
70 + const folder = thread.worktreePath ?? Option.getOrUndefined(project)?.workspaceRoot;
71 + const scratchRoot = Option.getOrUndefined(yield* managedFolders.scratchRoot);
72 + const isScratch = yield* managedFolders.isScratchProject(thread.projectId);
73 + // A thread already rooted at its folder is a partial earlier promotion; finish it.
74 + const alreadyPromoted =
75 + Option.isSome(project) && project.value.workspaceRoot === folder && !isScratch;
76 + if (
77 + folder === undefined ||
78 + scratchRoot === undefined ||
79 + path.dirname(folder) !== scratchRoot ||
80 + !(isScratch || alreadyPromoted)
81 + ) {
82 + return yield* new ScratchThreadPromotionError({
83 + reason: "Only a No project thread with its own folder can become a project.",
84 + });
85 + }
86 +
87 + const snapshot = yield* Effect.flatten(
88 + threads.readShellSnapshot({ worktreePath: folder }),
89 + ).pipe(Effect.mapError(fail("Could not read the threads in this folder.")));
90 + const moveSet = new Map<ThreadId, OrchestrationV2ThreadShell>();
91 + if (isScratch) moveSet.set(thread.id, thread);
92 + for (const candidate of [...snapshot.threads, ...snapshot.archivedThreads]) {
93 + if (yield* managedFolders.isScratchProject(candidate.projectId)) {
94 + moveSet.set(candidate.id, candidate);
95 + }
96 + }
97 +
98 + for (const candidate of moveSet.values()) {
99 + const records = yield* threads
100 + .getThreadRecords(candidate.id, ["runs", "runtimeRequests"], { turnItemTypes: [] })
101 + .pipe(Effect.mapError(fail(`Could not read "${candidate.title}".`)));
102 + if (threadHasUnfinishedWork(records)) {
103 + return yield* new ScratchThreadPromotionError({
104 + reason: `"${candidate.title}" is still working. Finish or stop it first.`,
105 + });
106 + }
107 + }
108 +
109 + return yield* Effect.uninterruptible(
110 + Effect.gen(function* () {
111 + const projectId = yield* createProject(thread.title, folder);
112 + yield* scheduledTasks
113 + .moveThreadTasks({ threadIds: [...moveSet.keys()], projectId })
114 + .pipe(Effect.mapError(fail("Could not move the thread's scheduled tasks.")));
115 + for (const candidate of moveSet.values()) {
116 + const commandId = CommandId.make(`scratch-promotion:${yield* randomId}`);
117 + yield* threads
118 + .dispatch({
119 + type: "thread.project.adopt-folder",
120 + commandId,
121 + threadId: candidate.id,
122 + projectId,
123 + })
124 + .pipe(Effect.mapError(fail(`Could not move "${candidate.title}". Try again.`)));
125 + }
126 + return { projectId };
127 + }),
128 + );
129 + });
130 +
131 + const randomId = crypto
132 + .randomUUIDv4()
133 + .pipe(Effect.mapError(fail("Could not create an id for the project.")));
134 +
135 + // bootstrap returns the project that already owns the folder, so retries reuse it.
136 + const createProject = Effect.fn("ScratchThreadPromotion.createProject")(function* (
137 + title: string,
138 + workspaceRoot: string,
139 + ) {
140 + const id = yield* randomId;
141 + return yield* projects
142 + .bootstrap({
143 + commandId: CommandId.make(`scratch-promotion-project:${id}`),
144 + projectId: ProjectId.make(id),
145 + title,
146 + workspaceRoot,
147 + })
148 + .pipe(
149 + Effect.map(({ project }) => project.id),
150 + // bootstrap reads before locking; racing creates return the winner in a conflict.
151 + Effect.catchTags({
152 + ProjectConflictError: (conflict) => Effect.succeed(conflict.conflictingProjectId),
153 + }),
154 + Effect.mapError(fail("Could not create the project.")),
155 + );
156 + });
157 +
158 + return ScratchThreadPromotion.of({ promote });
159 +});
160 +
161 +export const layer = Layer.effect(ScratchThreadPromotion, make);
apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
+74
@@ -402,3 +402,77 @@ it.effect("thread cleanup notifies subscribers and a finishing run cannot recrea
402 }).pipe(Effect.provide(layer));
403 }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
404 );
405 +
406 +it.effect("a bound run follows its thread when promotion moves it mid-send", () =>
407 + Effect.gen(function* () {
408 + const scratch = ProjectId.make("project:scratch");
409 + const promoted = ProjectId.make("project:promoted");
410 + const sends = yield* Ref.make<Array<{ projectId: ProjectId; commandId: string }>>([]);
411 + // Rebind lands first, then the promotion commits between the shell read and the retry.
412 + const shellProjects = yield* Ref.make([scratch, promoted]);
413 + const layer = ScheduledTaskService.layer.pipe(
414 + Layer.provide(
415 + Layer.mergeAll(
416 + Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
417 + Layer.mock(ThreadManagementService.ThreadManagementService)({
418 + sendToThread: (input) =>
419 + Ref.updateAndGet(sends, (all) => [
420 + ...all,
421 + { projectId: input.projectId, commandId: input.commandId },
422 + ]).pipe(
423 + Effect.flatMap((all) =>
424 + all.length < 3
425 + ? Effect.fail(
426 + new ThreadManagementService.ThreadManagementThreadNotFoundError({
427 + projectId: input.projectId,
428 + threadId: input.threadId,
429 + }),
430 + )
431 + : Effect.succeed({} as never),
432 + ),
433 + ),
434 + getThreadShell: () =>
435 + Ref.modify(shellProjects, ([next, ...rest]) => [
436 + { projectId: next ?? promoted } as never,
437 + rest,
438 + ]),
439 + }),
440 + Layer.mock(SecretRequests.SecretRequests)({}),
441 + Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
442 + namedProjectsRoot: "/projects",
443 + isScratchProject: () => Effect.succeed(false),
444 + }),
445 + NodeCrypto.layer,
446 + Scheduler.layer,
447 + ),
448 + ),
449 + );
450 + yield* Effect.gen(function* () {
451 + const service = yield* ScheduledTaskService.ScheduledTaskService;
452 + const threadId = ThreadId.make("thread:promoted-during-run");
453 + const { task } = yield* service.upsert({
454 + id: ScheduledTaskId.make("task:promoted-during-run"),
455 + title: "Check in",
456 + prompt: "Check progress",
457 + enabled: true,
458 + schedule: { type: "interval", everyMs: 60_000 },
459 + projectId: promoted,
460 + threadId,
461 + workspaceStrategy: { type: "root" },
462 + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
463 + runtimeMode: "full-access",
464 + interactionMode: "default",
465 + });
466 +
467 + const result = yield* service.runNow({ id: task.id });
468 +
469 + assert.equal(result.threadId, threadId);
470 + const attempts = yield* Ref.get(sends);
471 + assert.deepEqual(
472 + attempts.map((attempt) => attempt.projectId),
473 + [promoted, scratch, promoted],
474 + );
475 + assert.equal(new Set(attempts.map((attempt) => attempt.commandId)).size, 1);
476 + }).pipe(Effect.provide(layer));
477 + }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
478 +);
apps/server/src/scheduledTasks/ScheduledTaskService.ts
+62 -14
@@ -2,6 +2,7 @@ import {
2 CommandId,
3 MessageId,
4 PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
5 + type ProjectId,
6 ScheduledTask,
7 ScheduledTaskError,
8 ScheduledTaskId,
@@ -240,6 +241,11 @@ export class ScheduledTaskService extends Context.Service<
241 ) => Effect.Effect<ScheduledTaskDeleteResult, ScheduledTaskError>;
242 /** Deletes only tasks that still target this thread, including their webhook deliveries. */
243 readonly deleteForThread: (threadId: ThreadId) => Effect.Effect<void, ScheduledTaskError>;
244 + /** Points tasks bound to these threads at the project the threads moved to. */
245 + readonly moveThreadTasks: (input: {
246 + readonly threadIds: ReadonlyArray<ThreadId>;
247 + readonly projectId: ProjectId;
248 + }) => Effect.Effect<void, ScheduledTaskError>;
249 /** The dispatched thread, or null if dispatch failed; leaves the task's binding unchanged. */
250 readonly runNow: (
251 input: ScheduledTaskRunNowInput,
@@ -808,6 +814,42 @@ export const layer = Layer.effect(
814 // A webhook prompt was rendered from the row when the request arrived.
815 const prompt = webhook?.prompt ?? active.prompt;
816
817 + // A bound thread can move to another project (No project to a project) while
818 + // this fires. Follow it; one move needs at most two retries. Same ids replay safely.
819 + const sendBound = (
820 + threadId: ThreadId,
821 + projectId: ProjectId,
822 + retries: number,
823 + ): ReturnType<typeof threadManagement.sendToThread> =>
824 + threadManagement
825 + .sendToThread({
826 + projectId,
827 + commandId,
828 + threadId,
829 + messageId,
830 + scheduledTaskId: active.id,
831 + text: prompt,
832 + attachments: [],
833 + mode: "queue",
834 + createdBy: active.createdBy,
835 + creationSource: active.creationSource,
836 + })
837 + .pipe(
838 + Effect.catchTags({
839 + ThreadManagementThreadNotFoundError: (error) =>
840 + retries === 0
841 + ? Effect.fail(error)
842 + : threadManagement.getThreadShell(threadId).pipe(
843 + Effect.orElseSucceed(() => null),
844 + Effect.flatMap((shell) =>
845 + shell === null || shell.projectId === projectId
846 + ? Effect.fail(error)
847 + : sendBound(threadId, shell.projectId, retries - 1),
848 + ),
849 + ),
850 + }),
851 + );
852 +
853 // Capture defects and interrupts too so dispatch failures still reach markCompleted.
854 const result =
855 active.threadId === null
@@ -835,20 +877,9 @@ export const layer = Layer.effect(
877 : yield* Effect.exit(
878 // The stored selection only seeds fresh threads. A bound run
879 // follows the thread's current provider, so it passes none.
838 - threadManagement
839 - .sendToThread({
840 - projectId: active.projectId,
841 - commandId,
842 - threadId: ThreadId.make(active.threadId),
843 - messageId,
844 - scheduledTaskId: active.id,
845 - text: prompt,
846 - attachments: [],
847 - mode: "queue",
848 - createdBy: active.createdBy,
849 - creationSource: active.creationSource,
850 - })
851 - .pipe(Effect.as(ThreadId.make(active.threadId))),
880 + sendBound(ThreadId.make(active.threadId), active.projectId, 2).pipe(
881 + Effect.as(ThreadId.make(active.threadId)),
882 + ),
883 );
884
885 const runSucceeded = result._tag === "Success";
@@ -1262,6 +1293,22 @@ export const layer = Layer.effect(
1293 if (removed.length > 0) yield* notifyChanged;
1294 });
1295
1296 + const moveThreadTasks: ScheduledTaskService["Service"]["moveThreadTasks"] = Effect.fn(
1297 + "ScheduledTaskService.moveThreadTasks",
1298 + )(function* (input) {
1299 + if (input.threadIds.length === 0) return;
1300 + const moved = yield* sql<{ task_id: ScheduledTaskId }>`
1301 + UPDATE scheduled_tasks SET project_id = ${input.projectId}
1302 + WHERE project_id != ${input.projectId} AND thread_id IN ${sql.in(input.threadIds)}
1303 + RETURNING task_id
1304 + `.pipe(
1305 + Effect.mapError((cause) =>
1306 + taskError("Could not move the thread's schedule tasks.", { cause }),
1307 + ),
1308 + );
1309 + if (moved.length > 0) yield* notifyChanged;
1310 + });
1311 +
1312 const runNow: ScheduledTaskService["Service"]["runNow"] = Effect.fn(
1313 "ScheduledTaskService.runNow",
1314 )(function* (input: ScheduledTaskRunNowInput) {
@@ -2138,6 +2185,7 @@ export const layer = Layer.effect(
2185 setEnabled,
2186 delete: deleteTask,
2187 deleteForThread,
2188 + moveThreadTasks,
2189 runNow,
2190 rotateWebhookToken,
2191 listWebhookDeliveries,
apps/server/src/ws.test.ts
+3
@@ -49,6 +49,7 @@ import * as EnvironmentTheme from "./environmentTheme.ts";
49 import * as GitWorkflowService from "./git/GitWorkflowService.ts";
50 import * as HostResources from "./resourceTelemetry/HostResources.ts";
51 import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts";
52 +import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts";
53 import * as McpAppRequests from "./mcpApps/McpAppRequests.ts";
54 import * as ModelManifest from "./provider/ModelManifest.ts";
55 import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
@@ -593,6 +594,7 @@ it.effect(
594 scratchRoot: Effect.succeedNone,
595 namedProjectsRoot: process.cwd(),
596 }),
597 + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
598 Layer.mock(ServerEnvironment.ServerEnvironment)({
599 getDescriptor: Effect.succeed({
600 environmentId: EnvironmentId.make("config-test"),
@@ -769,6 +771,7 @@ it.effect("on-demand clients get provider config without workspace snapshots", (
771 scratchRoot: Effect.succeedNone,
772 namedProjectsRoot: process.cwd(),
773 }),
774 + Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
775 Layer.mock(ServerEnvironment.ServerEnvironment)({
776 getDescriptor: Effect.succeed({
777 environmentId: EnvironmentId.make("config-test"),
apps/server/src/ws.ts
+10
@@ -214,6 +214,7 @@ import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts
214 import * as ProjectService from "./project/ProjectService.ts";
215 import { threadWorkspaceRoot } from "./project/threadWorkspaceRoot.ts";
216 import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts";
217 +import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts";
218 import { projectMutationOperation } from "./project/ProjectMutation.ts";
219 import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts";
220 import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
@@ -1238,6 +1239,7 @@ export const layerWsRpc = (
1239 const projectStore = yield* ProjectStore.ProjectStoreV2;
1240 const projectService = yield* ProjectService.ProjectService;
1241 const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
1242 + const scratchThreadPromotion = yield* ScratchThreadPromotion.ScratchThreadPromotion;
1243 const eventLoopMonitor = yield* EventLoopMonitor.EventLoopMonitor;
1244 const threadSearch = yield* ThreadSearch.ThreadSearch;
1245
@@ -2716,6 +2718,14 @@ export const layerWsRpc = (
2718 (cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }),
2719 ),
2720 ),
2721 + [WS_METHODS.projectsCreateFromThread]: (input) =>
2722 + scratchThreadPromotion
2723 + .promote(input)
2724 + .pipe(
2725 + Effect.mapError(
2726 + (cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }),
2727 + ),
2728 + ),
2729 [WS_METHODS.projectCloneCancel]: (input) =>
2730 projectCloneTracker.cancel(input.projectId).pipe(Effect.map((applied) => ({ applied }))),
2731 [WS_METHODS.projectCloneRetry]: (input) =>
apps/web/src/components/Sidebar.tsx
+27 -1
@@ -115,7 +115,11 @@ import {
115 getThreadKeysToDeselectAfterDelete,
116 useThreadSelectionStore,
117 } from "../threadSelectionStore";
118 -import { useAcknowledgeThreadWoke, useThreadActions } from "../hooks/useThreadActions";
118 +import {
119 + canTurnThreadIntoProject,
120 + useAcknowledgeThreadWoke,
121 + useThreadActions,
122 +} from "../hooks/useThreadActions";
123 import { useHandleNewThread } from "../hooks/useHandleNewThread";
124 import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups";
125 import { useTerminalFocus } from "../hooks/useTerminalFocus";
@@ -897,6 +901,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
901 unpinThread,
902 confirmAndUnpinThread,
903 setThreadAutoSettle,
904 + turnThreadIntoProject,
905 reorderPinnedThread,
906 reorderActiveThread,
907 markThreadUnread,
@@ -2558,6 +2563,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2563 canShareWithGuest: appAtomRegistry.get(
2564 canShareWithGuestAtom(threadRef.environmentId),
2565 ),
2566 + canTurnIntoProject: canTurnThreadIntoProject(threadRef),
2567 supports: {
2568 settlement: configLoaded,
2569 autoSettleOptOut: supportsAutoSettleOptOut,
@@ -2638,6 +2644,26 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
2644 case "unpin":
2645 attemptUnpin(threadRef);
2646 return;
2647 + case "turn-into-project": {
2648 + const result = await turnThreadIntoProject(threadRef);
2649 + if (result._tag === "Success") {
2650 + toastManager.add({
2651 + type: "success",
2652 + title: "Project created",
2653 + description: thread.title,
2654 + });
2655 + } else if (!isAtomCommandInterrupted(result)) {
2656 + const error = squashAtomCommandFailure(result);
2657 + toastManager.add(
2658 + stackedThreadToast({
2659 + type: "error",
2660 + title: "Could not turn thread into a project",
2661 + description: error instanceof Error ? error.message : "An error occurred.",
2662 + }),
2663 + );
2664 + }
2665 + return;
2666 + }
2667 case "auto-settle:enabled":
2668 case "auto-settle:disabled": {
2669 const result = await setThreadAutoSettle(
apps/web/src/components/threadActionMenu.logic.test.ts
+8 -5
@@ -65,10 +65,13 @@ describe("buildThreadActionMenuItems", () => {
65 },
66 );
67
68 - it("disables archive while the thread is running", () => {
69 - const archiveItem = buildThreadActionMenuItems({ ...baseState, isRunning: true }).find(
70 - (item) => item.id === "archive",
71 - );
72 - expect(archiveItem?.disabled).toBe(true);
68 + it("disables archive and turning into a project while the thread is running", () => {
69 + const items = buildThreadActionMenuItems({
70 + ...baseState,
71 + isRunning: true,
72 + canTurnIntoProject: true,
73 + });
74 + expect(items.find((item) => item.id === "archive")?.disabled).toBe(true);
75 + expect(items.find((item) => item.id === "turn-into-project")?.disabled).toBe(true);
76 });
77 });
apps/web/src/components/threadActionMenu.logic.ts
+13
@@ -4,6 +4,7 @@ import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"
4 export type ThreadActionMenuId =
5 | "new-thread-on-branch"
6 | "filter-by-project"
7 + | "turn-into-project"
8 | "project-settings"
9 | "pin"
10 | "unpin"
@@ -90,6 +91,8 @@ export interface ThreadActionMenuState {
91 readonly snoozePresets: ReadonlyArray<SnoozePreset>;
92 /** Guest links need their own grant, so the caller checks it instead of `canOperate`. */
93 readonly canShareWithGuest?: boolean;
94 + /** A No project thread with its own folder, on a server that can promote it. */
95 + readonly canTurnIntoProject?: boolean;
96 }
97
98 /** Local navigation, read markers, and copying remain available to read-only clients. */
@@ -183,6 +186,16 @@ export function buildThreadActionMenuItems(
186 },
187 ]
188 : []),
189 + ...(state.canTurnIntoProject
190 + ? [
191 + {
192 + id: "turn-into-project" as const,
193 + label: "Turn into project",
194 + icon: "folder-plus",
195 + disabled: state.isRunning,
196 + },
197 + ]
198 + : []),
199 ...(state.supports.autoSettleOptOut
200 ? [
201 {
apps/web/src/contextMenuFallback.ts
+10
@@ -124,6 +124,16 @@ const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<stri
124 { tag: "line", attrs: { x1: "19", x2: "19", y1: "8", y2: "14" } },
125 { tag: "line", attrs: { x1: "22", x2: "16", y1: "11", y2: "11" } },
126 ],
127 + "folder-plus": [
128 + { tag: "path", attrs: { d: "M12 10v6" } },
129 + { tag: "path", attrs: { d: "M9 13h6" } },
130 + {
131 + tag: "path",
132 + attrs: {
133 + d: "M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",
134 + },
135 + },
136 + ],
137 "folder-tree": [
138 {
139 tag: "path",
apps/web/src/hooks/useThreadActionMenu.test.ts
+1
@@ -119,6 +119,7 @@ vi.mock("./useSettings", () => ({
119 }),
120 }));
121 vi.mock("./useThreadActions", () => ({
122 + canTurnThreadIntoProject: () => false,
123 useThreadActions: () =>
124 Object.fromEntries(
125 [
apps/web/src/hooks/useThreadActionMenu.ts
+16 -1
@@ -45,7 +45,7 @@ import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models";
45 import { useCopyToClipboard } from "./useCopyToClipboard";
46 import { useNewThreadHandler } from "./useHandleNewThread";
47 import { useClientSettings } from "./useSettings";
48 -import { useThreadActions } from "./useThreadActions";
48 +import { canTurnThreadIntoProject, useThreadActions } from "./useThreadActions";
49
50 function failureToast(title: string, error: unknown) {
51 toastManager.add(
@@ -84,6 +84,7 @@ export function useThreadActionMenu(input: {
84 archiveThread,
85 deleteThread,
86 markThreadUnread,
87 + turnThreadIntoProject,
88 } = useThreadActions();
89 const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
90 reportFailure: false,
@@ -144,6 +145,7 @@ export function useThreadActionMenu(input: {
145 supports,
146 snoozePresets,
147 canShareWithGuest,
148 + canTurnIntoProject: canTurnThreadIntoProject(threadRef),
149 });
150 const clicked = await settlePromise(() => api.contextMenu.show(items, position));
151 if (clicked._tag === "Failure" || clicked.value === null) return;
@@ -254,6 +256,19 @@ export function useThreadActionMenu(input: {
256 case "share-guest":
257 openGuestShareDialog(threadRef);
258 return;
259 + case "turn-into-project": {
260 + const result = await turnThreadIntoProject(threadRef);
261 + if (result._tag === "Success") {
262 + toastManager.add({
263 + type: "success",
264 + title: "Project created",
265 + description: thread.title,
266 + });
267 + } else if (!isAtomCommandInterrupted(result)) {
268 + failureToast("Could not turn thread into a project", squashAtomCommandFailure(result));
269 + }
270 + return;
271 + }
272 case "copy-path": {
273 const workspacePath = thread.worktreePath ?? projectCwd;
274 if (!workspacePath) {
apps/web/src/hooks/useThreadActions.ts
+23
@@ -29,6 +29,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
29 import { environmentServerConfigsAtom } from "../state/server";
30 import { isScratchProject } from "@t3tools/client-runtime/state/projects";
31 import { orchestrationEnvironment } from "../state/orchestration";
32 +import { projectEnvironment } from "../state/projects";
33 import { threadEnvironment } from "../state/threads";
34 import { vcsEnvironment } from "../state/vcs";
35 import { useNewThreadHandler } from "./useHandleNewThread";
@@ -228,6 +229,20 @@ export function useAcknowledgeThreadWoke() {
229 };
230 }
231
232 +/** A No project thread that already has its own folder, on a server that can promote it. */
233 +export function canTurnThreadIntoProject(threadRef: ScopedThreadRef): boolean {
234 + const thread = readThreadShell(threadRef);
235 + const config = appAtomRegistry.get(environmentServerConfigsAtom).get(threadRef.environmentId);
236 + if (!thread?.worktreePath || config?.environment.capabilities.threadProjectFromScratch !== true) {
237 + return false;
238 + }
239 + const project = readProject({
240 + environmentId: threadRef.environmentId,
241 + projectId: thread.projectId,
242 + });
243 + return project !== null && isScratchProject(project, config.scratchWorkspaceRoot);
244 +}
245 +
246 function threadOperationFailure(target: ScopedThreadRef) {
247 return readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope)
248 ? null
@@ -279,6 +294,9 @@ export function useThreadActions() {
294 reportFailure: false,
295 });
296 const markThreadUnread = useMarkThreadUnread();
297 + const createProjectFromThread = useAtomCommand(projectEnvironment.createFromThread, {
298 + reportFailure: false,
299 + });
300 const stopThreadSession = useOrchestrationCommand(threadEnvironment.stopSession);
301 const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
302 reportFailure: false,
@@ -925,5 +943,10 @@ export function useThreadActions() {
943 reorderActiveThread,
944 markThreadUnread,
945 setThreadAutoSettle,
946 + turnThreadIntoProject: (target: ScopedThreadRef) =>
947 + createProjectFromThread({
948 + environmentId: target.environmentId,
949 + input: { threadId: target.threadId },
950 + }),
951 };
952 }
docs/user/thread-sidebar.md
+6
@@ -37,6 +37,12 @@ folder, so the files the agent wrote stay until you delete them. Branch, worktre
37 these folders are not Git repositories. This is unavailable when the data
38 directory itself sits inside a Git checkout.
39
40 +When the work grows into something real, pick **Turn into project** from the
41 +thread's menu. The thread's folder becomes a project where it is, so nothing
42 +moves and the agent keeps working in the same place. Other threads in that folder
43 +move with it. Rename the project in its settings, and use **Initialize Git** to
44 +get branch and diff controls.
45 +
46 ### Start in the background
47
48 In a desktop browser or the desktop app, press `Cmd+Enter` on macOS or `Ctrl+Enter`
packages/client-runtime/src/state/projectCommands.ts
+6
@@ -201,6 +201,12 @@ export function createProjectEnvironmentAtoms<R, E>(
201 scheduler: projectScheduler,
202 concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
203 }),
204 + createFromThread: createEnvironmentRpcCommand(runtime, {
205 + label: "environment-data:projects:create-from-thread",
206 + tag: WS_METHODS.projectsCreateFromThread,
207 + scheduler: projectScheduler,
208 + concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
209 + }),
210 writeFile: createEnvironmentRpcCommand(runtime, {
211 label: "environment-data:projects:write-file",
212 tag: WS_METHODS.projectsWriteFile,
packages/contracts/src/clientRpcPermissions.ts
+1
@@ -33,6 +33,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
33 [WS_METHODS.pullRequestsSetLabels]: AuthSourceControlWriteScope,
34 // Writing a guide runs a model on this environment's providers, which reading one does not.
35 [WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope,
36 + [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope,
37 [WS_METHODS.sourceControlCloneRepository]: AuthSourceControlWriteScope,
38 [WS_METHODS.sourceControlPublishRepository]: AuthSourceControlWriteScope,
39 // Signing in replaces the server's GitHub credential, as saving a token in Settings does.
packages/contracts/src/environment.ts
+1
@@ -110,6 +110,7 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
110 threadPinReorder: Schema.optionalKey(Schema.Boolean),
111 threadActiveReorder: Schema.optionalKey(Schema.Boolean),
112 threadAutoSettleOptOut: Schema.optionalKey(Schema.Boolean),
113 + threadProjectFromScratch: Schema.optionalKey(Schema.Boolean),
114 threadTitleRegeneration: Schema.optionalKey(Schema.Boolean),
115 threadVisitedTracking: Schema.optionalKey(Schema.Boolean),
116 threadPullRequestLinking: Schema.optionalKey(Schema.Boolean),
packages/contracts/src/orchestrationV2.ts
+7
@@ -3335,6 +3335,13 @@ const OrchestrationV2InternalCommand = Schema.Union([
3335 text: Schema.String,
3336 attachments: Schema.optional(Schema.Array(ChatAttachment)),
3337 }),
3338 + /** Moves a thread to a project rooted at the folder it already works in, so its cwd never changes. */
3339 + Schema.Struct({
3340 + type: Schema.Literal("thread.project.adopt-folder"),
3341 + commandId: CommandId,
3342 + threadId: ThreadId,
3343 + projectId: ProjectId,
3344 + }),
3345 Schema.Struct({
3346 type: Schema.Literal("thread.pull-request-watch.sync"),
3347 commandId: CommandId,
packages/contracts/src/project.ts
+11
@@ -10,6 +10,7 @@ import {
10 NonNegativeInt,
11 PositiveInt,
12 ProjectId,
13 + ThreadId,
14 TrimmedNonEmptyString,
15 TrimmedString,
16 type UnknownUnionMember,
@@ -527,6 +528,16 @@ export const ProjectCreateNewResult = Schema.Struct({
528 });
529 export type ProjectCreateNewResult = typeof ProjectCreateNewResult.Type;
530
531 +export const ProjectCreateFromThreadInput = Schema.Struct({
532 + threadId: ThreadId,
533 +});
534 +export type ProjectCreateFromThreadInput = typeof ProjectCreateFromThreadInput.Type;
535 +
536 +export const ProjectCreateFromThreadResult = Schema.Struct({
537 + projectId: ProjectId,
538 +});
539 +export type ProjectCreateFromThreadResult = typeof ProjectCreateFromThreadResult.Type;
540 +
541 export class ProjectWriteFileError extends Schema.TaggedError<ProjectWriteFileError>()(
542 "ProjectWriteFileError",
543 {
packages/contracts/src/rpc.ts
+10
@@ -230,6 +230,8 @@ import {
230 import {
231 ProjectCreateNewInput,
232 ProjectCreateNewResult,
233 + ProjectCreateFromThreadInput,
234 + ProjectCreateFromThreadResult,
235 ProjectEnsureScratchResult,
236 ProjectListEntriesError,
237 ProjectListEntriesInput,
@@ -405,6 +407,7 @@ export const WS_METHODS = {
407 projectsMutate: "projects.mutate",
408 projectsEnsureScratch: "projects.ensureScratch",
409 projectsCreateNew: "projects.createNew",
410 + projectsCreateFromThread: "projects.createFromThread",
411
412 shellOpenInEditor: "shell.openInEditor",
413
@@ -1313,6 +1316,12 @@ const WsProjectsCreateNewRpc = Rpc.make(WS_METHODS.projectsCreateNew, {
1316 error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]),
1317 });
1318
1319 +const WsProjectsCreateFromThreadRpc = Rpc.make(WS_METHODS.projectsCreateFromThread, {
1320 + payload: ProjectCreateFromThreadInput,
1321 + success: ProjectCreateFromThreadResult,
1322 + error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]),
1323 +});
1324 +
1325 const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {
1326 payload: LaunchEditorInput,
1327 error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]),
@@ -2043,6 +2052,7 @@ export const WsRpcGroup = RpcGroup.make(
2052 WsProjectsSearchEntriesRpc,
2053 WsProjectsEnsureScratchRpc,
2054 WsProjectsCreateNewRpc,
2055 + WsProjectsCreateFromThreadRpc,
2056 WsProjectsWriteFileRpc,
2057 WsProjectsMutateRpc,
2058 WsShellOpenInEditorRpc,