Skip to content
TypeScript

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

Theo Browne58e60bf5e808
diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
index 39c5ac82362..5b0c1fd2f52 100644
--- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx
+++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx
@@ -62,6 +62,8 @@ import { useThreadPr } from "../../state/use-thread-pr";
import { useSwipeRowDormant } from "../home/swipe-row-activation";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
+import { canTurnThreadIntoProject, turnThreadIntoProject } from "./turnThreadIntoProject";
+import { threadCanArchive } from "../home/threadArchive";
import {
THREAD_LIST_V2_SETTLED_PAGE_COUNT,
resolveThreadListV2SnoozeGateExpiryMs,
@@ -837,6 +839,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
: [],
[props.autoSettleOptOutSupported, thread.autoSettleDisabledAt],
);
+ const canTurnIntoProject = canTurnThreadIntoProject(thread);
const titleMenuItems = useMemo<MenuAction[]>(
() => [
{ id: "rename", title: "Rename", image: "square.and.pencil" },
@@ -844,8 +847,23 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
+ ...(canTurnIntoProject
+ ? [
+ {
+ id: "turn-into-project",
+ title: "Turn into project",
+ image: "folder.badge.plus",
+ attributes: { disabled: !threadCanArchive(thread.runtime) },
+ } satisfies MenuAction,
+ ]
+ : []),
+ ],
+ [
+ canTurnIntoProject,
+ props.titleRegenerationSupported,
+ thread.runtime,
+ thread.titleRegeneration,
],
- [props.titleRegenerationSupported, thread.titleRegeneration],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
@@ -923,6 +941,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "rename") handleRename();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
+ if (nativeEvent.event === "turn-into-project") void turnThreadIntoProject(thread);
if (nativeEvent.event === "copy-thread") {
const target = threadChipCopyTarget(
{ environmentId: thread.environmentId, threadId: thread.id },
diff --git a/apps/mobile/src/features/threads/turnThreadIntoProject.ts b/apps/mobile/src/features/threads/turnThreadIntoProject.ts
new file mode 100644
index 00000000000..44e6e03fe0d
--- /dev/null
+++ b/apps/mobile/src/features/threads/turnThreadIntoProject.ts
@@ -0,0 +1,47 @@
+import {
+ isAtomCommandInterrupted,
+ runAtomCommand,
+ squashAtomCommandFailure,
+} from "@t3tools/client-runtime/state/runtime";
+import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell";
+import { AuthOrchestrationOperateScope } from "@t3tools/contracts";
+import * as Haptics from "expo-haptics";
+
+import * as Dialog from "../../components/ui/Dialog";
+import { appAtomRegistry } from "../../state/atom-registry";
+import { environmentProjects, projectEnvironment } from "../../state/projects";
+import { environmentServerConfigsAtom } from "../../state/server";
+import { readEnvironmentScope } from "../../state/session";
+
+/** A No project thread that already has its own folder, on a server that can promote it. */
+export function canTurnThreadIntoProject(thread: EnvironmentThreadShell): boolean {
+ if (thread.worktreePath === null) return false;
+ const config = appAtomRegistry.get(environmentServerConfigsAtom).get(thread.environmentId);
+ if (config?.environment.capabilities.threadProjectFromScratch !== true) return false;
+ const project = appAtomRegistry.get(
+ environmentProjects.projectAtom({
+ environmentId: thread.environmentId,
+ projectId: thread.projectId,
+ }),
+ );
+ return project?.isScratch === true;
+}
+
+export async function turnThreadIntoProject(thread: EnvironmentThreadShell): Promise<void> {
+ const title = "Could not turn thread into a project";
+ if (!readEnvironmentScope(thread.environmentId, AuthOrchestrationOperateScope)) {
+ Dialog.alert(title, "This connection cannot change threads.");
+ return;
+ }
+ void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light);
+ const result = await runAtomCommand(
+ appAtomRegistry,
+ projectEnvironment.createFromThread,
+ { environmentId: thread.environmentId, input: { threadId: thread.id } },
+ { reportFailure: false },
+ );
+ if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ Dialog.alert(title, error instanceof Error ? error.message : "Try again.");
+ }
+}
diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts
index 2b9b1f95b07..90ae4519bed 100644
--- a/apps/server/src/environment/ServerEnvironment.ts
+++ b/apps/server/src/environment/ServerEnvironment.ts
@@ -246,6 +246,7 @@ export const make = Effect.gen(function* () {
threadPinReorder: true,
threadActiveReorder: true,
threadAutoSettleOptOut: true,
+ threadProjectFromScratch: true,
threadTitleRegeneration: true,
commandOutputStreaming: true,
threadVisitedTracking: true,
diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
index dba3bf7c08e..ec8c9434bec 100644
--- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
+++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts
@@ -182,6 +182,7 @@ const layerUnusedScheduledTaskStub = Layer.succeed(
setEnabled: () => Effect.die("ScheduledTaskService.setEnabled is unused in this test"),
delete: () => Effect.die("ScheduledTaskService.delete is unused in this test"),
deleteForThread: () => Effect.die("unused in this test"),
+ moveThreadTasks: () => Effect.die("unused in this test"),
runNow: () => Effect.die("ScheduledTaskService.runNow is unused in this test"),
rotateWebhookToken: () => Effect.die("unused in this test"),
listWebhookDeliveries: () => Effect.die("unused in this test"),
diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts
index fcbbde88f4b..259fa92a660 100644
--- a/apps/server/src/observability/RpcInstrumentation.ts
+++ b/apps/server/src/observability/RpcInstrumentation.ts
@@ -150,6 +150,7 @@ const RPC_AGGREGATES = {
[WS_METHODS.projectsWriteFile]: "workspace",
[WS_METHODS.projectsEnsureScratch]: "orchestration",
[WS_METHODS.projectsCreateNew]: "orchestration",
+ [WS_METHODS.projectsCreateFromThread]: "orchestration",
[WS_METHODS.shellOpenInEditor]: "workspace",
[WS_METHODS.filesystemBrowse]: "workspace",
[WS_METHODS.filesystemGetMetadata]: "workspace",
diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts
index 91acb881637..d0edd5dacf8 100644
--- a/apps/server/src/orchestration-v2/Orchestrator.ts
+++ b/apps/server/src/orchestration-v2/Orchestrator.ts
@@ -455,6 +455,23 @@ function wakeWorkStartedAt(
const threadPullRequestLinksEqual = Schema.toEquivalence(Schema.NullOr(ThreadLinkedPullRequest));
+/** Unfinished runs (including queued) or open requests block moving a thread to another project. */
+export function threadHasUnfinishedWork(records: {
+ readonly runs: ReadonlyArray<{ readonly status: string }>;
+ readonly runtimeRequests: ReadonlyArray<{ readonly status: string }>;
+}): boolean {
+ return (
+ records.runs.some(
+ (run) =>
+ run.status !== "completed" &&
+ run.status !== "failed" &&
+ run.status !== "cancelled" &&
+ run.status !== "interrupted" &&
+ run.status !== "rolled_back",
+ ) || records.runtimeRequests.some((request) => request.status === "pending")
+ );
+}
+
function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
switch (command.type) {
case "thread.create":
@@ -486,6 +503,7 @@ function commandThreadId(command: OrchestrationV2ServerCommand): ThreadId {
case "thread.pull-request-watch.sync":
case "thread.pull-request.sync":
case "thread.title.regeneration.complete":
+ case "thread.project.adopt-folder":
case "thread.runtime-mode.set":
case "thread.interaction-mode.set":
case "thread.model-selection.set":
@@ -3983,6 +4001,56 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
},
);
+ const dispatchThreadProjectAdoptFolder = Effect.fn(
+ "orchestrationV2.dispatch.threadProjectAdoptFolder",
+ )(function* (
+ command: Extract<
+ OrchestrationV2ServerCommand,
+ { readonly type: "thread.project.adopt-folder" }
+ >,
+ events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
+ ) {
+ const reject = (cause: string) =>
+ new OrchestratorDispatchError({
+ commandId: command.commandId,
+ commandType: command.type,
+ cause: `Thread ${command.threadId} ${cause}`,
+ });
+ const projection = yield* projectionStore
+ .getThreadRecords(command.threadId, ["runs", "runtimeRequests"], { turnItemTypes: [] })
+ .pipe(
+ Effect.mapError(
+ (cause) => new OrchestratorProjectionError({ threadId: command.threadId, cause }),
+ ),
+ );
+ const thread = projection.thread;
+ if (thread.deletedAt !== null) return yield* reject("is deleted.");
+ if (threadHasUnfinishedWork(projection)) {
+ return yield* reject("still has work in progress. Finish or stop it first.");
+ }
+ const current = yield* projects.get(thread.projectId).pipe(mapDispatchError(command));
+ const target = yield* projects.get(command.projectId).pipe(mapDispatchError(command));
+ if (Option.isNone(target) || target.value.deletedAt !== null) {
+ return yield* reject(`cannot move to missing project ${command.projectId}.`);
+ }
+ // The thread always lands in the project root, so the move must not change its cwd.
+ const cwd = thread.worktreePath ?? Option.getOrUndefined(current)?.workspaceRoot;
+ if (cwd !== target.value.workspaceRoot) {
+ return yield* reject(`does not work in ${target.value.workspaceRoot}.`);
+ }
+ const now = yield* DateTime.now;
+ yield* emit(
+ events,
+ command,
+ )({
+ type: "thread.metadata-updated",
+ threadId: command.threadId,
+ providerInstanceId: thread.providerInstanceId,
+ occurredAt: now,
+ payload: { ...thread, projectId: command.projectId, worktreePath: null, updatedAt: now },
+ });
+ });
+
const refuseAboveDispatchModeLimit = Effect.fn("orchestrationV2.dispatch.refuseAboveModeLimit")(
function* (
command: OrchestrationV2ServerCommand,
@@ -12487,6 +12555,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
case "provider-session.detach":
yield* dispatchProviderSessionDetach(command, events, effects);
break;
+ case "thread.project.adopt-folder":
+ yield* dispatchThreadProjectAdoptFolder(command, events);
+ break;
case "message.dispatch": {
// Providers own native subagent conversations; messages cannot target them, and adapters ask questions on the parent.
const thread = yield* projectionStore
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
index c77837094b2..65c0c040e0d 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts
@@ -37,6 +37,7 @@ import * as DateTime from "effect/DateTime";
import * as Deferred from "effect/Deferred";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as Queue from "effect/Queue";
import * as Stream from "effect/Stream";
@@ -76,6 +77,7 @@ import { shellStreamItemFromThreadShell } from "./ShellStream.ts";
import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
import * as ThreadManagementService from "./ThreadManagementService.ts";
import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
+import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts";
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
import * as Scheduler from "../scheduling/Scheduler.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
@@ -5805,6 +5807,198 @@ it.layer(layerTest)("snooze queued runs", (it) => {
);
});
+const SCRATCH_ROOT = "/tmp/runtime-layer-promotion-scratch";
+const SCRATCH_PROJECT_ID = ProjectId.make("runtime-layer-promotion-scratch");
+const layerScratchPromotionTest = ScratchThreadPromotion.layer.pipe(
+ Layer.provide(
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
+ scratchRoot: Effect.succeedSome(SCRATCH_ROOT),
+ isScratchProject: (projectId) => Effect.succeed(projectId === SCRATCH_PROJECT_ID),
+ namedProjectsRoot: "/projects",
+ }),
+ ),
+ Layer.provide(NodeServices.layer),
+ Layer.provideMerge(layerProjectDeletionTest),
+);
+
+it.layer(layerScratchPromotionTest)("turning a No project thread into a project", (it) => {
+ const setup = Effect.fn(function* (name: string) {
+ const projects = yield* ProjectService.ProjectService;
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const folder = `${SCRATCH_ROOT}/2026-01-01-${name}`;
+ if (Option.isNone(yield* projects.getById(SCRATCH_PROJECT_ID))) {
+ yield* projects.create({
+ commandId: CommandId.make("promotion-scratch-create"),
+ projectId: SCRATCH_PROJECT_ID,
+ title: "No project",
+ workspaceRoot: SCRATCH_ROOT,
+ });
+ }
+ const createThread = (suffix: string, worktreePath: string) =>
+ orchestrator
+ .dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`promotion-${name}-${suffix}-create`),
+ threadId: ThreadId.make(`promotion-${name}-${suffix}`),
+ projectId: SCRATCH_PROJECT_ID,
+ title: `${name} ${suffix}`,
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath,
+ })
+ .pipe(Effect.as(ThreadId.make(`promotion-${name}-${suffix}`)));
+ return { folder, createThread };
+ });
+ const shellOf = (threadId: ThreadId) =>
+ Orchestrator.OrchestratorV2.pipe(
+ Effect.flatMap((orchestrator) => orchestrator.getThreadShell(threadId)),
+ );
+
+ it.effect("moves every thread in the folder and its bound tasks into one project", () =>
+ Effect.gen(function* () {
+ const promotion = yield* ScratchThreadPromotion.ScratchThreadPromotion;
+ const projects = yield* ProjectService.ProjectService;
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const tasks = yield* ScheduledTaskService.ScheduledTaskService;
+ const { folder, createThread } = yield* setup("moves");
+ const threadId = yield* createThread("main", folder);
+ const siblingId = yield* createThread("sibling", folder);
+ const otherId = yield* createThread("other", `${SCRATCH_ROOT}/2026-01-01-elsewhere`);
+ yield* orchestrator.dispatch({
+ type: "thread.archive",
+ commandId: CommandId.make("promotion-moves-sibling-archive"),
+ threadId: siblingId,
+ });
+ const { task } = yield* tasks.upsert({
+ id: ScheduledTaskId.make("promotion-moves-bound"),
+ title: "Bound",
+ prompt: "Check in",
+ enabled: true,
+ schedule: { type: "interval", everyMs: 60_000 },
+ projectId: SCRATCH_PROJECT_ID,
+ threadId: siblingId,
+ workspaceStrategy: { type: "root" },
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ createdBy: "user",
+ creationSource: "web",
+ });
+
+ const { projectId } = yield* promotion.promote({ threadId });
+
+ const project = yield* projects.getById(projectId);
+ assert.equal(Option.getOrUndefined(project)?.workspaceRoot, folder);
+ assert.equal(Option.getOrUndefined(project)?.title, "moves main");
+ for (const id of [threadId, siblingId]) {
+ const shell = yield* shellOf(id);
+ assert.equal(shell?.projectId, projectId);
+ assert.isNull(shell?.worktreePath);
+ }
+ assert.equal((yield* shellOf(otherId))?.projectId, SCRATCH_PROJECT_ID);
+ const saved = (yield* tasks.list()).tasks.find((candidate) => candidate.id === task.id);
+ assert.equal(saved?.projectId, projectId);
+ assert.deepEqual(yield* promotion.promote({ threadId }), { projectId });
+ }),
+ );
+
+ it.effect("changes nothing while a thread in the folder is busy", () =>
+ Effect.gen(function* () {
+ const promotion = yield* ScratchThreadPromotion.ScratchThreadPromotion;
+ const projects = yield* ProjectService.ProjectService;
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const { folder, createThread } = yield* setup("busy");
+ const threadId = yield* createThread("idle", folder);
+ const busyId = yield* createThread("delegate", folder);
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("promotion-busy-message"),
+ threadId: busyId,
+ messageId: MessageId.make("promotion-busy-message"),
+ text: "Keep this run active.",
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: "start_immediately" },
+ });
+
+ const error = yield* promotion.promote({ threadId }).pipe(Effect.flip);
+
+ assert.equal(error.message, '"busy delegate" is still working. Finish or stop it first.');
+ assert.isTrue(Option.isNone(yield* projects.getByWorkspaceRoot(folder)));
+ assert.equal((yield* shellOf(threadId))?.projectId, SCRATCH_PROJECT_ID);
+ }),
+ );
+
+ it.effect("finishes a partial move from either thread", () =>
+ Effect.gen(function* () {
+ const promotion = yield* ScratchThreadPromotion.ScratchThreadPromotion;
+ const projects = yield* ProjectService.ProjectService;
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const { folder, createThread } = yield* setup("partial");
+ const movedId = yield* createThread("moved", folder);
+ const leftId = yield* createThread("left", folder);
+ const earlier = yield* projects.create({
+ commandId: CommandId.make("promotion-partial-project"),
+ projectId: ProjectId.make("promotion-partial-project"),
+ title: "Earlier",
+ workspaceRoot: folder,
+ });
+ yield* orchestrator.dispatch({
+ type: "thread.project.adopt-folder",
+ commandId: CommandId.make("promotion-partial-adopt"),
+ threadId: movedId,
+ projectId: earlier.id,
+ });
+
+ assert.deepEqual(yield* promotion.promote({ threadId: movedId }), { projectId: earlier.id });
+ assert.equal((yield* shellOf(leftId))?.projectId, earlier.id);
+ }),
+ );
+
+ it.effect("refuses a thread outside No project", () =>
+ Effect.gen(function* () {
+ const promotion = yield* ScratchThreadPromotion.ScratchThreadPromotion;
+ const projects = yield* ProjectService.ProjectService;
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const projectId = ProjectId.make("promotion-regular-project");
+ const threadId = ThreadId.make("promotion-regular-thread");
+ yield* projects.create({
+ commandId: CommandId.make("promotion-regular-project"),
+ projectId,
+ title: "Regular",
+ workspaceRoot: "/tmp/runtime-layer-promotion-regular",
+ });
+ yield* orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("promotion-regular-thread-create"),
+ threadId,
+ projectId,
+ title: "Regular",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ });
+
+ const error = yield* promotion.promote({ threadId }).pipe(Effect.flip);
+
+ assert.equal(
+ error.message,
+ "Only a No project thread with its own folder can become a project.",
+ );
+ }),
+ );
+});
+
it.layer(layerSharedApplicationDataPlaneTest)("snooze projection", (it) => {
it.effect("carries snooze state through the V2 shell projection", () =>
Effect.gen(function* () {
@@ -5900,6 +6094,88 @@ it.layer(layerSharedApplicationDataPlaneTest)("snooze projection", (it) => {
assert.isNull(awakened.thread.snoozedAt);
}),
);
+
+ it.effect("moves a thread into a project rooted at its own folder", () =>
+ Effect.gen(function* () {
+ const projects = yield* ProjectService.ProjectService;
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
+ const scratchProjectId = ProjectId.make("runtime-layer-adopt-scratch");
+ const folderProjectId = ProjectId.make("runtime-layer-adopt-folder");
+ const otherProjectId = ProjectId.make("runtime-layer-adopt-other");
+ const folder = "/tmp/runtime-layer-adopt-scratch/2026-01-01-notes-a1b2c3d4";
+ const createProject = (projectId: ProjectId, workspaceRoot: string) =>
+ projects.create({
+ commandId: CommandId.make(`${projectId}-create`),
+ projectId,
+ title: projectId,
+ workspaceRoot,
+ });
+ const createThread = (threadId: ThreadId) =>
+ orchestrator.dispatch({
+ type: "thread.create",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make(`${threadId}-create`),
+ threadId,
+ projectId: scratchProjectId,
+ title: "Scratch work",
+ modelSelection,
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: folder,
+ });
+ const adopt = (threadId: ThreadId, projectId: ProjectId, suffix: string) =>
+ orchestrator.dispatch({
+ type: "thread.project.adopt-folder",
+ commandId: CommandId.make(`${threadId}-adopt-${suffix}`),
+ threadId,
+ projectId,
+ });
+ yield* createProject(scratchProjectId, "/tmp/runtime-layer-adopt-scratch");
+ yield* createProject(folderProjectId, folder);
+ yield* createProject(otherProjectId, "/tmp/runtime-layer-adopt-other");
+ const idleThreadId = ThreadId.make("runtime-layer-adopt-idle");
+ const busyThreadId = ThreadId.make("runtime-layer-adopt-busy");
+ yield* createThread(idleThreadId);
+ yield* createThread(busyThreadId);
+ yield* orchestrator.dispatch({
+ type: "message.dispatch",
+ createdBy: "user",
+ creationSource: "web",
+ commandId: CommandId.make("runtime-layer-adopt-busy-message"),
+ threadId: busyThreadId,
+ messageId: MessageId.make("runtime-layer-adopt-busy-message"),
+ text: "Keep this run active.",
+ attachments: [],
+ modelSelection,
+ dispatchMode: { type: "start_immediately" },
+ });
+
+ const otherFolder = yield* adopt(idleThreadId, otherProjectId, "other").pipe(Effect.flip);
+ assert.equal(
+ otherFolder.cause,
+ `Thread ${idleThreadId} does not work in /tmp/runtime-layer-adopt-other.`,
+ );
+ const missing = yield* adopt(idleThreadId, ProjectId.make("missing"), "missing").pipe(
+ Effect.flip,
+ );
+ assert.equal(missing.cause, `Thread ${idleThreadId} cannot move to missing project missing.`);
+ const busy = yield* adopt(busyThreadId, folderProjectId, "busy").pipe(Effect.flip);
+ assert.equal(
+ busy.cause,
+ `Thread ${busyThreadId} still has work in progress. Finish or stop it first.`,
+ );
+
+ yield* adopt(idleThreadId, folderProjectId, "folder");
+ const shell = yield* orchestrator.getShellSnapshot();
+ const moved = shell.threads.find((thread) => thread.id === idleThreadId);
+ assert.equal(moved?.projectId, folderProjectId);
+ assert.isNull(moved?.worktreePath);
+ const stayed = shell.threads.find((thread) => thread.id === busyThreadId);
+ assert.equal(stayed?.projectId, scratchProjectId);
+ }),
+ );
});
it.layer(layerSharedApplicationDataPlaneTest)("visited projection", (it) => {
diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts
index 6bd33ebd261..1b546275953 100644
--- a/apps/server/src/orchestration-v2/runtimeLayer.ts
+++ b/apps/server/src/orchestration-v2/runtimeLayer.ts
@@ -16,6 +16,7 @@ import * as AgentSessionScanner from "../project/AgentSessionScanner.ts";
import * as ProjectService from "../project/ProjectService.ts";
import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts";
import * as ManagedProjectFolders from "../project/ManagedProjectFolders.ts";
+import * as ScratchThreadPromotion from "../project/ScratchThreadPromotion.ts";
import * as CheckpointCaptureService from "./CheckpointCaptureService.ts";
import * as CheckpointService from "./CheckpointService.ts";
import * as CheckpointRollbackService from "./CheckpointRollbackService.ts";
@@ -289,6 +290,16 @@ const layerScheduledTaskProvided = ScheduledTaskService.layer.pipe(
),
),
);
+const layerScratchThreadPromotionProvided = ScratchThreadPromotion.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ layerProjectService,
+ layerManagedProjectFoldersProvided,
+ layerThreadManagementProvided,
+ layerScheduledTaskProvided,
+ ),
+ ),
+);
const layerProviderContinuationWorkerProvided = ProviderContinuationService.layer.pipe(
Layer.provide(
Layer.mergeAll(
@@ -362,6 +373,7 @@ export const layerProduction = Layer.mergeAll(
layerManagedProjectFoldersProvided,
layerThreadLaunchProvided,
layerScheduledTaskProvided,
+ layerScratchThreadPromotionProvided,
layerSecretRequestsProvided,
GuestShareService.layer.pipe(
Layer.provide(Layer.merge(layerOrchestratorProvided, layerCommandOutputHubProvided)),
diff --git a/apps/server/src/project/ScratchThreadPromotion.ts b/apps/server/src/project/ScratchThreadPromotion.ts
new file mode 100644
index 00000000000..671a480a958
--- /dev/null
+++ b/apps/server/src/project/ScratchThreadPromotion.ts
@@ -0,0 +1,161 @@
+import {
+ CommandId,
+ type OrchestrationV2ThreadShell,
+ ProjectId,
+ type ThreadId,
+} from "@t3tools/contracts";
+import * as Context from "effect/Context";
+import * as Crypto from "effect/Crypto";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Path from "effect/Path";
+import * as Schema from "effect/Schema";
+
+import { threadHasUnfinishedWork } from "../orchestration-v2/Orchestrator.ts";
+import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
+import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
+import * as ManagedProjectFolders from "./ManagedProjectFolders.ts";
+import * as ProjectService from "./ProjectService.ts";
+
+export class ScratchThreadPromotionError extends Schema.TaggedError<ScratchThreadPromotionError>()(
+ "ScratchThreadPromotionError",
+ {
+ reason: Schema.String,
+ cause: Schema.optional(Schema.Defect()),
+ },
+) {
+ override get message(): string {
+ return this.reason;
+ }
+}
+
+export class ScratchThreadPromotion extends Context.Service<
+ ScratchThreadPromotion,
+ {
+ /**
+ * Turns a No project thread's folder into a project, in place, and moves every
+ * thread working in that folder into it. Running it again finishes a partial move.
+ */
+ readonly promote: (input: {
+ readonly threadId: ThreadId;
+ }) => Effect.Effect<{ readonly projectId: ProjectId }, ScratchThreadPromotionError>;
+ }
+>()("t3/project/ScratchThreadPromotion") {}
+
+const make = Effect.gen(function* () {
+ const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
+ const projects = yield* ProjectService.ProjectService;
+ const threads = yield* ThreadManagementService.ThreadManagementService;
+ const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
+ const crypto = yield* Crypto.Crypto;
+ const path = yield* Path.Path;
+
+ const fail = (reason: string) => (cause: unknown) =>
+ new ScratchThreadPromotionError({ reason, cause });
+
+ const promote: ScratchThreadPromotion["Service"]["promote"] = Effect.fn(
+ "ScratchThreadPromotion.promote",
+ )(function* (input) {
+ const thread = yield* threads.getThreadShell(input.threadId).pipe(
+ Effect.mapError(fail("Could not read the thread.")),
+ Effect.filterOrFail(
+ (shell) => shell !== null,
+ () => new ScratchThreadPromotionError({ reason: "Thread not found." }),
+ ),
+ );
+ const project = yield* projects
+ .getById(thread.projectId)
+ .pipe(Effect.mapError(fail("Could not read the thread's project.")));
+ const folder = thread.worktreePath ?? Option.getOrUndefined(project)?.workspaceRoot;
+ const scratchRoot = Option.getOrUndefined(yield* managedFolders.scratchRoot);
+ const isScratch = yield* managedFolders.isScratchProject(thread.projectId);
+ // A thread already rooted at its folder is a partial earlier promotion; finish it.
+ const alreadyPromoted =
+ Option.isSome(project) && project.value.workspaceRoot === folder && !isScratch;
+ if (
+ folder === undefined ||
+ scratchRoot === undefined ||
+ path.dirname(folder) !== scratchRoot ||
+ !(isScratch || alreadyPromoted)
+ ) {
+ return yield* new ScratchThreadPromotionError({
+ reason: "Only a No project thread with its own folder can become a project.",
+ });
+ }
+
+ const snapshot = yield* Effect.flatten(
+ threads.readShellSnapshot({ worktreePath: folder }),
+ ).pipe(Effect.mapError(fail("Could not read the threads in this folder.")));
+ const moveSet = new Map<ThreadId, OrchestrationV2ThreadShell>();
+ if (isScratch) moveSet.set(thread.id, thread);
+ for (const candidate of [...snapshot.threads, ...snapshot.archivedThreads]) {
+ if (yield* managedFolders.isScratchProject(candidate.projectId)) {
+ moveSet.set(candidate.id, candidate);
+ }
+ }
+
+ for (const candidate of moveSet.values()) {
+ const records = yield* threads
+ .getThreadRecords(candidate.id, ["runs", "runtimeRequests"], { turnItemTypes: [] })
+ .pipe(Effect.mapError(fail(`Could not read "${candidate.title}".`)));
+ if (threadHasUnfinishedWork(records)) {
+ return yield* new ScratchThreadPromotionError({
+ reason: `"${candidate.title}" is still working. Finish or stop it first.`,
+ });
+ }
+ }
+
+ return yield* Effect.uninterruptible(
+ Effect.gen(function* () {
+ const projectId = yield* createProject(thread.title, folder);
+ yield* scheduledTasks
+ .moveThreadTasks({ threadIds: [...moveSet.keys()], projectId })
+ .pipe(Effect.mapError(fail("Could not move the thread's scheduled tasks.")));
+ for (const candidate of moveSet.values()) {
+ const commandId = CommandId.make(`scratch-promotion:${yield* randomId}`);
+ yield* threads
+ .dispatch({
+ type: "thread.project.adopt-folder",
+ commandId,
+ threadId: candidate.id,
+ projectId,
+ })
+ .pipe(Effect.mapError(fail(`Could not move "${candidate.title}". Try again.`)));
+ }
+ return { projectId };
+ }),
+ );
+ });
+
+ const randomId = crypto
+ .randomUUIDv4()
+ .pipe(Effect.mapError(fail("Could not create an id for the project.")));
+
+ // bootstrap returns the project that already owns the folder, so retries reuse it.
+ const createProject = Effect.fn("ScratchThreadPromotion.createProject")(function* (
+ title: string,
+ workspaceRoot: string,
+ ) {
+ const id = yield* randomId;
+ return yield* projects
+ .bootstrap({
+ commandId: CommandId.make(`scratch-promotion-project:${id}`),
+ projectId: ProjectId.make(id),
+ title,
+ workspaceRoot,
+ })
+ .pipe(
+ Effect.map(({ project }) => project.id),
+ // bootstrap reads before locking; racing creates return the winner in a conflict.
+ Effect.catchTags({
+ ProjectConflictError: (conflict) => Effect.succeed(conflict.conflictingProjectId),
+ }),
+ Effect.mapError(fail("Could not create the project.")),
+ );
+ });
+
+ return ScratchThreadPromotion.of({ promote });
+});
+
+export const layer = Layer.effect(ScratchThreadPromotion, make);
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
index c1dcdd22abb..82d16597275 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.test.ts
@@ -402,3 +402,77 @@ it.effect("thread cleanup notifies subscribers and a finishing run cannot recrea
}).pipe(Effect.provide(layer));
}).pipe(Effect.provide(SqlitePersistence.layerMemory)),
);
+
+it.effect("a bound run follows its thread when promotion moves it mid-send", () =>
+ Effect.gen(function* () {
+ const scratch = ProjectId.make("project:scratch");
+ const promoted = ProjectId.make("project:promoted");
+ const sends = yield* Ref.make<Array<{ projectId: ProjectId; commandId: string }>>([]);
+ // Rebind lands first, then the promotion commits between the shell read and the retry.
+ const shellProjects = yield* Ref.make([scratch, promoted]);
+ const layer = ScheduledTaskService.layer.pipe(
+ Layer.provide(
+ Layer.mergeAll(
+ Layer.mock(ThreadLaunchService.ThreadLaunchService)({}),
+ Layer.mock(ThreadManagementService.ThreadManagementService)({
+ sendToThread: (input) =>
+ Ref.updateAndGet(sends, (all) => [
+ ...all,
+ { projectId: input.projectId, commandId: input.commandId },
+ ]).pipe(
+ Effect.flatMap((all) =>
+ all.length < 3
+ ? Effect.fail(
+ new ThreadManagementService.ThreadManagementThreadNotFoundError({
+ projectId: input.projectId,
+ threadId: input.threadId,
+ }),
+ )
+ : Effect.succeed({} as never),
+ ),
+ ),
+ getThreadShell: () =>
+ Ref.modify(shellProjects, ([next, ...rest]) => [
+ { projectId: next ?? promoted } as never,
+ rest,
+ ]),
+ }),
+ Layer.mock(SecretRequests.SecretRequests)({}),
+ Layer.mock(ManagedProjectFolders.ManagedProjectFolders)({
+ namedProjectsRoot: "/projects",
+ isScratchProject: () => Effect.succeed(false),
+ }),
+ NodeCrypto.layer,
+ Scheduler.layer,
+ ),
+ ),
+ );
+ yield* Effect.gen(function* () {
+ const service = yield* ScheduledTaskService.ScheduledTaskService;
+ const threadId = ThreadId.make("thread:promoted-during-run");
+ const { task } = yield* service.upsert({
+ id: ScheduledTaskId.make("task:promoted-during-run"),
+ title: "Check in",
+ prompt: "Check progress",
+ enabled: true,
+ schedule: { type: "interval", everyMs: 60_000 },
+ projectId: promoted,
+ threadId,
+ workspaceStrategy: { type: "root" },
+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ });
+
+ const result = yield* service.runNow({ id: task.id });
+
+ assert.equal(result.threadId, threadId);
+ const attempts = yield* Ref.get(sends);
+ assert.deepEqual(
+ attempts.map((attempt) => attempt.projectId),
+ [promoted, scratch, promoted],
+ );
+ assert.equal(new Set(attempts.map((attempt) => attempt.commandId)).size, 1);
+ }).pipe(Effect.provide(layer));
+ }).pipe(Effect.provide(SqlitePersistence.layerMemory)),
+);
diff --git a/apps/server/src/scheduledTasks/ScheduledTaskService.ts b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
index 3dfedb0dfea..b3aa9440944 100644
--- a/apps/server/src/scheduledTasks/ScheduledTaskService.ts
+++ b/apps/server/src/scheduledTasks/ScheduledTaskService.ts
@@ -2,6 +2,7 @@ import {
CommandId,
MessageId,
PROVIDER_SEND_TURN_MAX_INPUT_CHARS,
+ type ProjectId,
ScheduledTask,
ScheduledTaskError,
ScheduledTaskId,
@@ -240,6 +241,11 @@ export class ScheduledTaskService extends Context.Service<
) => Effect.Effect<ScheduledTaskDeleteResult, ScheduledTaskError>;
/** Deletes only tasks that still target this thread, including their webhook deliveries. */
readonly deleteForThread: (threadId: ThreadId) => Effect.Effect<void, ScheduledTaskError>;
+ /** Points tasks bound to these threads at the project the threads moved to. */
+ readonly moveThreadTasks: (input: {
+ readonly threadIds: ReadonlyArray<ThreadId>;
+ readonly projectId: ProjectId;
+ }) => Effect.Effect<void, ScheduledTaskError>;
/** The dispatched thread, or null if dispatch failed; leaves the task's binding unchanged. */
readonly runNow: (
input: ScheduledTaskRunNowInput,
@@ -808,6 +814,42 @@ export const layer = Layer.effect(
// A webhook prompt was rendered from the row when the request arrived.
const prompt = webhook?.prompt ?? active.prompt;
+ // A bound thread can move to another project (No project to a project) while
+ // this fires. Follow it; one move needs at most two retries. Same ids replay safely.
+ const sendBound = (
+ threadId: ThreadId,
+ projectId: ProjectId,
+ retries: number,
+ ): ReturnType<typeof threadManagement.sendToThread> =>
+ threadManagement
+ .sendToThread({
+ projectId,
+ commandId,
+ threadId,
+ messageId,
+ scheduledTaskId: active.id,
+ text: prompt,
+ attachments: [],
+ mode: "queue",
+ createdBy: active.createdBy,
+ creationSource: active.creationSource,
+ })
+ .pipe(
+ Effect.catchTags({
+ ThreadManagementThreadNotFoundError: (error) =>
+ retries === 0
+ ? Effect.fail(error)
+ : threadManagement.getThreadShell(threadId).pipe(
+ Effect.orElseSucceed(() => null),
+ Effect.flatMap((shell) =>
+ shell === null || shell.projectId === projectId
+ ? Effect.fail(error)
+ : sendBound(threadId, shell.projectId, retries - 1),
+ ),
+ ),
+ }),
+ );
+
// Capture defects and interrupts too so dispatch failures still reach markCompleted.
const result =
active.threadId === null
@@ -835,20 +877,9 @@ export const layer = Layer.effect(
: yield* Effect.exit(
// The stored selection only seeds fresh threads. A bound run
// follows the thread's current provider, so it passes none.
- threadManagement
- .sendToThread({
- projectId: active.projectId,
- commandId,
- threadId: ThreadId.make(active.threadId),
- messageId,
- scheduledTaskId: active.id,
- text: prompt,
- attachments: [],
- mode: "queue",
- createdBy: active.createdBy,
- creationSource: active.creationSource,
- })
- .pipe(Effect.as(ThreadId.make(active.threadId))),
+ sendBound(ThreadId.make(active.threadId), active.projectId, 2).pipe(
+ Effect.as(ThreadId.make(active.threadId)),
+ ),
);
const runSucceeded = result._tag === "Success";
@@ -1262,6 +1293,22 @@ export const layer = Layer.effect(
if (removed.length > 0) yield* notifyChanged;
});
+ const moveThreadTasks: ScheduledTaskService["Service"]["moveThreadTasks"] = Effect.fn(
+ "ScheduledTaskService.moveThreadTasks",
+ )(function* (input) {
+ if (input.threadIds.length === 0) return;
+ const moved = yield* sql<{ task_id: ScheduledTaskId }>`
+ UPDATE scheduled_tasks SET project_id = ${input.projectId}
+ WHERE project_id != ${input.projectId} AND thread_id IN ${sql.in(input.threadIds)}
+ RETURNING task_id
+ `.pipe(
+ Effect.mapError((cause) =>
+ taskError("Could not move the thread's schedule tasks.", { cause }),
+ ),
+ );
+ if (moved.length > 0) yield* notifyChanged;
+ });
+
const runNow: ScheduledTaskService["Service"]["runNow"] = Effect.fn(
"ScheduledTaskService.runNow",
)(function* (input: ScheduledTaskRunNowInput) {
@@ -2138,6 +2185,7 @@ export const layer = Layer.effect(
setEnabled,
delete: deleteTask,
deleteForThread,
+ moveThreadTasks,
runNow,
rotateWebhookToken,
listWebhookDeliveries,
diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts
index ac60becc2d7..bce94507787 100644
--- a/apps/server/src/ws.test.ts
+++ b/apps/server/src/ws.test.ts
@@ -49,6 +49,7 @@ import * as EnvironmentTheme from "./environmentTheme.ts";
import * as GitWorkflowService from "./git/GitWorkflowService.ts";
import * as HostResources from "./resourceTelemetry/HostResources.ts";
import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts";
+import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts";
import * as McpAppRequests from "./mcpApps/McpAppRequests.ts";
import * as ModelManifest from "./provider/ModelManifest.ts";
import * as Orchestrator from "./orchestration-v2/Orchestrator.ts";
@@ -593,6 +594,7 @@ it.effect(
scratchRoot: Effect.succeedNone,
namedProjectsRoot: process.cwd(),
}),
+ Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
Layer.mock(ServerEnvironment.ServerEnvironment)({
getDescriptor: Effect.succeed({
environmentId: EnvironmentId.make("config-test"),
@@ -769,6 +771,7 @@ it.effect("on-demand clients get provider config without workspace snapshots", (
scratchRoot: Effect.succeedNone,
namedProjectsRoot: process.cwd(),
}),
+ Layer.mock(ScratchThreadPromotion.ScratchThreadPromotion)({}),
Layer.mock(ServerEnvironment.ServerEnvironment)({
getDescriptor: Effect.succeed({
environmentId: EnvironmentId.make("config-test"),
diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts
index 34eb11815b1..8c8509550bc 100644
--- a/apps/server/src/ws.ts
+++ b/apps/server/src/ws.ts
@@ -214,6 +214,7 @@ import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts
import * as ProjectService from "./project/ProjectService.ts";
import { threadWorkspaceRoot } from "./project/threadWorkspaceRoot.ts";
import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts";
+import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts";
import { projectMutationOperation } from "./project/ProjectMutation.ts";
import * as ProjectCloneTracker from "./project/ProjectCloneTracker.ts";
import * as RepositoryIdentityResolver from "./project/RepositoryIdentityResolver.ts";
@@ -1238,6 +1239,7 @@ export const layerWsRpc = (
const projectStore = yield* ProjectStore.ProjectStoreV2;
const projectService = yield* ProjectService.ProjectService;
const managedFolders = yield* ManagedProjectFolders.ManagedProjectFolders;
+ const scratchThreadPromotion = yield* ScratchThreadPromotion.ScratchThreadPromotion;
const eventLoopMonitor = yield* EventLoopMonitor.EventLoopMonitor;
const threadSearch = yield* ThreadSearch.ThreadSearch;
@@ -2716,6 +2718,14 @@ export const layerWsRpc = (
(cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }),
),
),
+ [WS_METHODS.projectsCreateFromThread]: (input) =>
+ scratchThreadPromotion
+ .promote(input)
+ .pipe(
+ Effect.mapError(
+ (cause) => new OrchestrationDispatchCommandError({ message: cause.message, cause }),
+ ),
+ ),
[WS_METHODS.projectCloneCancel]: (input) =>
projectCloneTracker.cancel(input.projectId).pipe(Effect.map((applied) => ({ applied }))),
[WS_METHODS.projectCloneRetry]: (input) =>
diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx
index 62934576e36..de16be6d2dc 100644
--- a/apps/web/src/components/Sidebar.tsx
+++ b/apps/web/src/components/Sidebar.tsx
@@ -115,7 +115,11 @@ import {
getThreadKeysToDeselectAfterDelete,
useThreadSelectionStore,
} from "../threadSelectionStore";
-import { useAcknowledgeThreadWoke, useThreadActions } from "../hooks/useThreadActions";
+import {
+ canTurnThreadIntoProject,
+ useAcknowledgeThreadWoke,
+ useThreadActions,
+} from "../hooks/useThreadActions";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups";
import { useTerminalFocus } from "../hooks/useTerminalFocus";
@@ -897,6 +901,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
unpinThread,
confirmAndUnpinThread,
setThreadAutoSettle,
+ turnThreadIntoProject,
reorderPinnedThread,
reorderActiveThread,
markThreadUnread,
@@ -2558,6 +2563,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
canShareWithGuest: appAtomRegistry.get(
canShareWithGuestAtom(threadRef.environmentId),
),
+ canTurnIntoProject: canTurnThreadIntoProject(threadRef),
supports: {
settlement: configLoaded,
autoSettleOptOut: supportsAutoSettleOptOut,
@@ -2638,6 +2644,26 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
case "unpin":
attemptUnpin(threadRef);
return;
+ case "turn-into-project": {
+ const result = await turnThreadIntoProject(threadRef);
+ if (result._tag === "Success") {
+ toastManager.add({
+ type: "success",
+ title: "Project created",
+ description: thread.title,
+ });
+ } else if (!isAtomCommandInterrupted(result)) {
+ const error = squashAtomCommandFailure(result);
+ toastManager.add(
+ stackedThreadToast({
+ type: "error",
+ title: "Could not turn thread into a project",
+ description: error instanceof Error ? error.message : "An error occurred.",
+ }),
+ );
+ }
+ return;
+ }
case "auto-settle:enabled":
case "auto-settle:disabled": {
const result = await setThreadAutoSettle(
diff --git a/apps/web/src/components/threadActionMenu.logic.test.ts b/apps/web/src/components/threadActionMenu.logic.test.ts
index 039c684dcdc..bd9dfdcdcc4 100644
--- a/apps/web/src/components/threadActionMenu.logic.test.ts
+++ b/apps/web/src/components/threadActionMenu.logic.test.ts
@@ -65,10 +65,13 @@ describe("buildThreadActionMenuItems", () => {
},
);
- it("disables archive while the thread is running", () => {
- const archiveItem = buildThreadActionMenuItems({ ...baseState, isRunning: true }).find(
- (item) => item.id === "archive",
- );
- expect(archiveItem?.disabled).toBe(true);
+ it("disables archive and turning into a project while the thread is running", () => {
+ const items = buildThreadActionMenuItems({
+ ...baseState,
+ isRunning: true,
+ canTurnIntoProject: true,
+ });
+ expect(items.find((item) => item.id === "archive")?.disabled).toBe(true);
+ expect(items.find((item) => item.id === "turn-into-project")?.disabled).toBe(true);
});
});
diff --git a/apps/web/src/components/threadActionMenu.logic.ts b/apps/web/src/components/threadActionMenu.logic.ts
index 7779a9db4c3..3c4626c1ea1 100644
--- a/apps/web/src/components/threadActionMenu.logic.ts
+++ b/apps/web/src/components/threadActionMenu.logic.ts
@@ -4,6 +4,7 @@ import type { SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"
export type ThreadActionMenuId =
| "new-thread-on-branch"
| "filter-by-project"
+ | "turn-into-project"
| "project-settings"
| "pin"
| "unpin"
@@ -90,6 +91,8 @@ export interface ThreadActionMenuState {
readonly snoozePresets: ReadonlyArray<SnoozePreset>;
/** Guest links need their own grant, so the caller checks it instead of `canOperate`. */
readonly canShareWithGuest?: boolean;
+ /** A No project thread with its own folder, on a server that can promote it. */
+ readonly canTurnIntoProject?: boolean;
}
/** Local navigation, read markers, and copying remain available to read-only clients. */
@@ -183,6 +186,16 @@ export function buildThreadActionMenuItems(
},
]
: []),
+ ...(state.canTurnIntoProject
+ ? [
+ {
+ id: "turn-into-project" as const,
+ label: "Turn into project",
+ icon: "folder-plus",
+ disabled: state.isRunning,
+ },
+ ]
+ : []),
...(state.supports.autoSettleOptOut
? [
{
diff --git a/apps/web/src/contextMenuFallback.ts b/apps/web/src/contextMenuFallback.ts
index 56e85545e6f..eece920cba6 100644
--- a/apps/web/src/contextMenuFallback.ts
+++ b/apps/web/src/contextMenuFallback.ts
@@ -124,6 +124,16 @@ const ICON_PATHS: Record<string, ReadonlyArray<{ tag: string; attrs: Record<stri
{ tag: "line", attrs: { x1: "19", x2: "19", y1: "8", y2: "14" } },
{ tag: "line", attrs: { x1: "22", x2: "16", y1: "11", y2: "11" } },
],
+ "folder-plus": [
+ { tag: "path", attrs: { d: "M12 10v6" } },
+ { tag: "path", attrs: { d: "M9 13h6" } },
+ {
+ tag: "path",
+ attrs: {
+ 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",
+ },
+ },
+ ],
"folder-tree": [
{
tag: "path",
diff --git a/apps/web/src/hooks/useThreadActionMenu.test.ts b/apps/web/src/hooks/useThreadActionMenu.test.ts
index 4fe9ad45ad5..e87092d59c3 100644
--- a/apps/web/src/hooks/useThreadActionMenu.test.ts
+++ b/apps/web/src/hooks/useThreadActionMenu.test.ts
@@ -119,6 +119,7 @@ vi.mock("./useSettings", () => ({
}),
}));
vi.mock("./useThreadActions", () => ({
+ canTurnThreadIntoProject: () => false,
useThreadActions: () =>
Object.fromEntries(
[
diff --git a/apps/web/src/hooks/useThreadActionMenu.ts b/apps/web/src/hooks/useThreadActionMenu.ts
index b7bec9d5e98..0e25cebeef8 100644
--- a/apps/web/src/hooks/useThreadActionMenu.ts
+++ b/apps/web/src/hooks/useThreadActionMenu.ts
@@ -45,7 +45,7 @@ import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models";
import { useCopyToClipboard } from "./useCopyToClipboard";
import { useNewThreadHandler } from "./useHandleNewThread";
import { useClientSettings } from "./useSettings";
-import { useThreadActions } from "./useThreadActions";
+import { canTurnThreadIntoProject, useThreadActions } from "./useThreadActions";
function failureToast(title: string, error: unknown) {
toastManager.add(
@@ -84,6 +84,7 @@ export function useThreadActionMenu(input: {
archiveThread,
deleteThread,
markThreadUnread,
+ turnThreadIntoProject,
} = useThreadActions();
const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
@@ -144,6 +145,7 @@ export function useThreadActionMenu(input: {
supports,
snoozePresets,
canShareWithGuest,
+ canTurnIntoProject: canTurnThreadIntoProject(threadRef),
});
const clicked = await settlePromise(() => api.contextMenu.show(items, position));
if (clicked._tag === "Failure" || clicked.value === null) return;
@@ -254,6 +256,19 @@ export function useThreadActionMenu(input: {
case "share-guest":
openGuestShareDialog(threadRef);
return;
+ case "turn-into-project": {
+ const result = await turnThreadIntoProject(threadRef);
+ if (result._tag === "Success") {
+ toastManager.add({
+ type: "success",
+ title: "Project created",
+ description: thread.title,
+ });
+ } else if (!isAtomCommandInterrupted(result)) {
+ failureToast("Could not turn thread into a project", squashAtomCommandFailure(result));
+ }
+ return;
+ }
case "copy-path": {
const workspacePath = thread.worktreePath ?? projectCwd;
if (!workspacePath) {
diff --git a/apps/web/src/hooks/useThreadActions.ts b/apps/web/src/hooks/useThreadActions.ts
index 211dc1bef67..32020316496 100644
--- a/apps/web/src/hooks/useThreadActions.ts
+++ b/apps/web/src/hooks/useThreadActions.ts
@@ -29,6 +29,7 @@ import { appAtomRegistry } from "../rpc/atomRegistry";
import { environmentServerConfigsAtom } from "../state/server";
import { isScratchProject } from "@t3tools/client-runtime/state/projects";
import { orchestrationEnvironment } from "../state/orchestration";
+import { projectEnvironment } from "../state/projects";
import { threadEnvironment } from "../state/threads";
import { vcsEnvironment } from "../state/vcs";
import { useNewThreadHandler } from "./useHandleNewThread";
@@ -228,6 +229,20 @@ export function useAcknowledgeThreadWoke() {
};
}
+/** A No project thread that already has its own folder, on a server that can promote it. */
+export function canTurnThreadIntoProject(threadRef: ScopedThreadRef): boolean {
+ const thread = readThreadShell(threadRef);
+ const config = appAtomRegistry.get(environmentServerConfigsAtom).get(threadRef.environmentId);
+ if (!thread?.worktreePath || config?.environment.capabilities.threadProjectFromScratch !== true) {
+ return false;
+ }
+ const project = readProject({
+ environmentId: threadRef.environmentId,
+ projectId: thread.projectId,
+ });
+ return project !== null && isScratchProject(project, config.scratchWorkspaceRoot);
+}
+
function threadOperationFailure(target: ScopedThreadRef) {
return readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope)
? null
@@ -279,6 +294,9 @@ export function useThreadActions() {
reportFailure: false,
});
const markThreadUnread = useMarkThreadUnread();
+ const createProjectFromThread = useAtomCommand(projectEnvironment.createFromThread, {
+ reportFailure: false,
+ });
const stopThreadSession = useOrchestrationCommand(threadEnvironment.stopSession);
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
reportFailure: false,
@@ -925,5 +943,10 @@ export function useThreadActions() {
reorderActiveThread,
markThreadUnread,
setThreadAutoSettle,
+ turnThreadIntoProject: (target: ScopedThreadRef) =>
+ createProjectFromThread({
+ environmentId: target.environmentId,
+ input: { threadId: target.threadId },
+ }),
};
}
diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md
index ce16b9df037..dfc7b1245ef 100644
--- a/docs/user/thread-sidebar.md
+++ b/docs/user/thread-sidebar.md
@@ -37,6 +37,12 @@ folder, so the files the agent wrote stay until you delete them. Branch, worktre
these folders are not Git repositories. This is unavailable when the data
directory itself sits inside a Git checkout.
+When the work grows into something real, pick **Turn into project** from the
+thread's menu. The thread's folder becomes a project where it is, so nothing
+moves and the agent keeps working in the same place. Other threads in that folder
+move with it. Rename the project in its settings, and use **Initialize Git** to
+get branch and diff controls.
+
### Start in the background
In a desktop browser or the desktop app, press `Cmd+Enter` on macOS or `Ctrl+Enter`
diff --git a/packages/client-runtime/src/state/projectCommands.ts b/packages/client-runtime/src/state/projectCommands.ts
index ede83d82957..03db9b869cc 100644
--- a/packages/client-runtime/src/state/projectCommands.ts
+++ b/packages/client-runtime/src/state/projectCommands.ts
@@ -201,6 +201,12 @@ export function createProjectEnvironmentAtoms<R, E>(
scheduler: projectScheduler,
concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
}),
+ createFromThread: createEnvironmentRpcCommand(runtime, {
+ label: "environment-data:projects:create-from-thread",
+ tag: WS_METHODS.projectsCreateFromThread,
+ scheduler: projectScheduler,
+ concurrency: { mode: "serial", key: ({ environmentId }) => environmentId },
+ }),
writeFile: createEnvironmentRpcCommand(runtime, {
label: "environment-data:projects:write-file",
tag: WS_METHODS.projectsWriteFile,
diff --git a/packages/contracts/src/clientRpcPermissions.ts b/packages/contracts/src/clientRpcPermissions.ts
index 3cd80feea6b..f9564b2e244 100644
--- a/packages/contracts/src/clientRpcPermissions.ts
+++ b/packages/contracts/src/clientRpcPermissions.ts
@@ -33,6 +33,7 @@ export const CLIENT_GUARDED_RPC_SCOPES = {
[WS_METHODS.pullRequestsSetLabels]: AuthSourceControlWriteScope,
// Writing a guide runs a model on this environment's providers, which reading one does not.
[WS_METHODS.pullRequestsGenerateReviewGuide]: AuthOrchestrationOperateScope,
+ [WS_METHODS.projectsCreateFromThread]: AuthOrchestrationOperateScope,
[WS_METHODS.sourceControlCloneRepository]: AuthSourceControlWriteScope,
[WS_METHODS.sourceControlPublishRepository]: AuthSourceControlWriteScope,
// Signing in replaces the server's GitHub credential, as saving a token in Settings does.
diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts
index a65a91e0d39..fbbffeddc92 100644
--- a/packages/contracts/src/environment.ts
+++ b/packages/contracts/src/environment.ts
@@ -110,6 +110,7 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
threadPinReorder: Schema.optionalKey(Schema.Boolean),
threadActiveReorder: Schema.optionalKey(Schema.Boolean),
threadAutoSettleOptOut: Schema.optionalKey(Schema.Boolean),
+ threadProjectFromScratch: Schema.optionalKey(Schema.Boolean),
threadTitleRegeneration: Schema.optionalKey(Schema.Boolean),
threadVisitedTracking: Schema.optionalKey(Schema.Boolean),
threadPullRequestLinking: Schema.optionalKey(Schema.Boolean),
diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts
index 498f81a0e84..747d05e7ce4 100644
--- a/packages/contracts/src/orchestrationV2.ts
+++ b/packages/contracts/src/orchestrationV2.ts
@@ -3335,6 +3335,13 @@ const OrchestrationV2InternalCommand = Schema.Union([
text: Schema.String,
attachments: Schema.optional(Schema.Array(ChatAttachment)),
}),
+ /** Moves a thread to a project rooted at the folder it already works in, so its cwd never changes. */
+ Schema.Struct({
+ type: Schema.Literal("thread.project.adopt-folder"),
+ commandId: CommandId,
+ threadId: ThreadId,
+ projectId: ProjectId,
+ }),
Schema.Struct({
type: Schema.Literal("thread.pull-request-watch.sync"),
commandId: CommandId,
diff --git a/packages/contracts/src/project.ts b/packages/contracts/src/project.ts
index 12934a7f8ed..79e164b71e9 100644
--- a/packages/contracts/src/project.ts
+++ b/packages/contracts/src/project.ts
@@ -10,6 +10,7 @@ import {
NonNegativeInt,
PositiveInt,
ProjectId,
+ ThreadId,
TrimmedNonEmptyString,
TrimmedString,
type UnknownUnionMember,
@@ -527,6 +528,16 @@ export const ProjectCreateNewResult = Schema.Struct({
});
export type ProjectCreateNewResult = typeof ProjectCreateNewResult.Type;
+export const ProjectCreateFromThreadInput = Schema.Struct({
+ threadId: ThreadId,
+});
+export type ProjectCreateFromThreadInput = typeof ProjectCreateFromThreadInput.Type;
+
+export const ProjectCreateFromThreadResult = Schema.Struct({
+ projectId: ProjectId,
+});
+export type ProjectCreateFromThreadResult = typeof ProjectCreateFromThreadResult.Type;
+
export class ProjectWriteFileError extends Schema.TaggedError<ProjectWriteFileError>()(
"ProjectWriteFileError",
{
diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts
index 658f6276e24..aae86bd9db4 100644
--- a/packages/contracts/src/rpc.ts
+++ b/packages/contracts/src/rpc.ts
@@ -230,6 +230,8 @@ import {
import {
ProjectCreateNewInput,
ProjectCreateNewResult,
+ ProjectCreateFromThreadInput,
+ ProjectCreateFromThreadResult,
ProjectEnsureScratchResult,
ProjectListEntriesError,
ProjectListEntriesInput,
@@ -405,6 +407,7 @@ export const WS_METHODS = {
projectsMutate: "projects.mutate",
projectsEnsureScratch: "projects.ensureScratch",
projectsCreateNew: "projects.createNew",
+ projectsCreateFromThread: "projects.createFromThread",
shellOpenInEditor: "shell.openInEditor",
@@ -1313,6 +1316,12 @@ const WsProjectsCreateNewRpc = Rpc.make(WS_METHODS.projectsCreateNew, {
error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]),
});
+const WsProjectsCreateFromThreadRpc = Rpc.make(WS_METHODS.projectsCreateFromThread, {
+ payload: ProjectCreateFromThreadInput,
+ success: ProjectCreateFromThreadResult,
+ error: Schema.Union([OrchestrationDispatchCommandError, EnvironmentAuthorizationError]),
+});
+
const WsShellOpenInEditorRpc = Rpc.make(WS_METHODS.shellOpenInEditor, {
payload: LaunchEditorInput,
error: Schema.Union([ExternalLauncherError, EnvironmentAuthorizationError]),
@@ -2043,6 +2052,7 @@ export const WsRpcGroup = RpcGroup.make(
WsProjectsSearchEntriesRpc,
WsProjectsEnsureScratchRpc,
WsProjectsCreateNewRpc,
+ WsProjectsCreateFromThreadRpc,
WsProjectsWriteFileRpc,
WsProjectsMutateRpc,
WsShellOpenInEditorRpc,