From 05d47b5dc455767a649fb4cf7afc99b82c366c3a Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Wed, 11 Nov 2026 14:08:00 -0800 Subject: [PATCH 1/4] feat(server): adopt existing Claude Code sessions into T3 threads Discover Claude transcripts for a project and adopt one into a managed thread that resumes the native session, inspired by OpenRig discover/adopt. --- apps/server/src/auth/RpcAuthorization.ts | 2 + .../src/observability/RpcInstrumentation.ts | 2 + .../src/project/AgentSessionImporter.test.ts | 108 ++++ .../src/project/AgentSessionImporter.ts | 566 +++++++++++------- apps/server/src/telemetry/FeatureUsage.ts | 1 + apps/server/src/ws.ts | 2 + .../settings/ClaudeSessionAdoptSection.tsx | 239 ++++++++ .../settings/ProviderInstanceCard.tsx | 8 + apps/web/src/state/agentSessions.ts | 20 + docs/user/providers-claude.md | 9 + packages/contracts/src/agentSessions.ts | 84 ++- packages/contracts/src/rpc.ts | 33 + 12 files changed, 871 insertions(+), 203 deletions(-) create mode 100644 apps/web/src/components/settings/ClaudeSessionAdoptSection.tsx diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index 180f053f111f4..cd783ca45d505 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -161,6 +161,8 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.filesystemGetMetadata]: AuthFilesystemReadScope, [WS_METHODS.agentSessionsScan]: AuthOrchestrationReadScope, [WS_METHODS.agentSessionsImport]: AuthOrchestrationOperateScope, + [WS_METHODS.agentSessionsList]: AuthOrchestrationReadScope, + [WS_METHODS.agentSessionsAdopt]: AuthOrchestrationOperateScope, [WS_METHODS.assetsCreateUrl]: AuthOrchestrationReadScope, [WS_METHODS.assetsPersistChatAttachments]: AuthOrchestrationOperateScope, [WS_METHODS.attachmentsCreateUploadUrl]: AuthOrchestrationOperateScope, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f9a861cca23fb..7edde24e259ce 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -167,6 +167,8 @@ const RPC_AGGREGATES = { [WS_METHODS.filesystemGetMetadata]: "workspace", [WS_METHODS.agentSessionsScan]: "workspace", [WS_METHODS.agentSessionsImport]: "workspace", + [WS_METHODS.agentSessionsList]: "workspace", + [WS_METHODS.agentSessionsAdopt]: "workspace", [WS_METHODS.assetsCreateUrl]: "workspace", [WS_METHODS.assetsPersistChatAttachments]: "orchestration", [WS_METHODS.attachmentsCreateUploadUrl]: "workspace", diff --git a/apps/server/src/project/AgentSessionImporter.test.ts b/apps/server/src/project/AgentSessionImporter.test.ts index c659622a2f1e8..a2f32de73f6fa 100644 --- a/apps/server/src/project/AgentSessionImporter.test.ts +++ b/apps/server/src/project/AgentSessionImporter.test.ts @@ -268,6 +268,8 @@ const makeImporter = Effect.fn(function* ( const importer = Context.get(context, AgentSessionImporter.AgentSessionImporter); return { run: importer.importRecentAgentThreads({ projectId }), + listSessions: importer.listSessions, + adoptSession: importer.adoptSession, importNativeHistory: importer.importNativeHistory, published, }; @@ -788,3 +790,109 @@ it.effect("imports under a policy ceiling in the project's default, kept under t ); }).pipe(Effect.scoped, Effect.provide(persistence)), ); + +it.effect("lists Claude sessions for a project and marks already adopted ones", () => + Effect.gen(function* () { + const claude = candidate( + CLAUDE_MODEL_SELECTION, + "020e7f00-dce6-406b-8ec6-ed90498945d6", + "claudeAgent", + ); + const codex = candidate(CODEX_MODEL_SELECTION, "codex-listed"); + const importer = yield* makeImporter([claude, codex]); + expect(yield* importer.listSessions({ projectId, provider: "claudeAgent" })).toEqual({ + sessions: [ + { + provider: "claudeAgent", + providerInstanceId: claude.source.providerInstanceId, + providerSessionId: claude.source.providerSessionId, + title: "Imported thread", + model: CLAUDE_MODEL_SELECTION.model, + updatedAt: timestamp, + filePath: claude.source.filePath, + importedThreadId: null, + }, + ], + }); + expect( + yield* importer.adoptSession({ + projectId, + provider: "claudeAgent", + providerInstanceId: claude.source.providerInstanceId, + providerSessionId: claude.source.providerSessionId, + }), + ).toEqual({ threadId: importId(claude), adopted: true }); + expect(yield* importer.listSessions({ projectId, provider: "claudeAgent" })).toEqual({ + sessions: [ + { + provider: "claudeAgent", + providerInstanceId: claude.source.providerInstanceId, + providerSessionId: claude.source.providerSessionId, + title: "Imported thread", + model: CLAUDE_MODEL_SELECTION.model, + updatedAt: timestamp, + filePath: claude.source.filePath, + importedThreadId: importId(claude), + }, + ], + }); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); + +it.effect("adopts a Claude session into a resumable T3 thread without recreating it", () => + Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; + const claude = candidate( + CLAUDE_MODEL_SELECTION, + "120e7f00-dce6-406b-8ec6-ed90498945d6", + "claudeAgent", + ); + const importer = yield* makeImporter([claude]); + const threadId = importId(claude); + + expect( + yield* importer.adoptSession({ + projectId, + provider: "claudeAgent", + providerInstanceId: claude.source.providerInstanceId, + providerSessionId: claude.source.providerSessionId, + title: "Adopted Claude session", + }), + ).toEqual({ threadId, adopted: true }); + + const records = yield* projections.getThreadRecords(threadId, ["messages", "providerThreads"]); + expect(records.thread.title).toBe("Adopted Claude session"); + expect(records.thread.historyOrigin).toBe("v1_import"); + expect(records.messages.map((message) => message.text)).toEqual(["Fix it", "Fixed"]); + expect(records.providerThreads[0]?.nativeThreadRef).toEqual({ + driver: "claudeAgent", + nativeId: claude.source.providerSessionId, + strength: "strong", + }); + expect(Option.getOrThrow(yield* runtimes.getByThreadId({ threadId })).resumeCursor).toEqual({ + threadId, + resume: claude.source.providerSessionId, + }); + + expect( + yield* importer.adoptSession({ + projectId, + provider: "claudeAgent", + providerInstanceId: claude.source.providerInstanceId, + providerSessionId: claude.source.providerSessionId, + }), + ).toEqual({ threadId, adopted: false }); + + expect( + yield* Effect.flip( + importer.adoptSession({ + projectId, + provider: "claudeAgent", + providerInstanceId: claude.source.providerInstanceId, + providerSessionId: "220e7f00-dce6-406b-8ec6-ed90498945d6", + }), + ), + ).toMatchObject({ _tag: "AgentSessionAdoptNotFoundError" }); + }).pipe(Effect.scoped, Effect.provide(persistence)), +); diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index de699840c0b88..39f39954303af 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -4,6 +4,8 @@ import { DEFAULT_PROVIDER_INTERACTION_MODE, DEFAULT_RUNTIME_MODE, isRuntimeModeAbove, + AgentSessionAdoptNotFoundError, + AgentSessionAdoptUnavailableError, AgentSessionImportProjectChangedError, AgentSessionImportProjectNotFoundError, AgentSessionScanError, @@ -14,13 +16,19 @@ import { ProviderDriverKind, ThreadId, TurnItemId, + type AgentSessionAdoptInput, + type AgentSessionAdoptResult, type AgentSessionImportInput, type AgentSessionImportResult, + type AgentSessionListInput, + type AgentSessionListResult, + type AgentSessionListed, type OrchestrationV2AppThread, type OrchestrationV2ConversationMessage, type OrchestrationV2DomainEvent, type OrchestrationV2ProviderThread, type OrchestrationV2TurnItem, + type RuntimeMode, } from "@t3tools/contracts"; import { normalizeProjectPathForComparison } from "@t3tools/shared/path"; import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; @@ -57,6 +65,7 @@ class AgentSessionUnresumableSessionError extends Schema.TaggedError()( "AgentSessionThreadProjectConflictError", @@ -189,6 +198,13 @@ function messageEvents(input: { ]; } +function importedThreadId(input: { + readonly providerInstanceId: string; + readonly providerSessionId: string; +}) { + return ThreadId.make(`import:${input.providerInstanceId}:${input.providerSessionId}`); +} + const make = Effect.gen(function* () { const scanner = yield* AgentSessionScanner.AgentSessionScanner; const orchestrator = yield* Orchestrator.OrchestratorV2; @@ -200,41 +216,51 @@ const make = Effect.gen(function* () { const threadCommands = yield* ThreadCommandExecutor.ThreadCommandExecutor; const settingsService = yield* ServerSettings.ServerSettingsService; const ceiling = settingsService.managedPolicy?.limits?.maxRuntimeMode; - const importRecentAgentThreads = Effect.fn("importRecentAgentThreadsV2")(function* ( - input: AgentSessionImportInput, + + const requireProject = Effect.fn("AgentSessionImporter.requireProject")(function* ( + projectId: ProjectId, + expectedWorkspaceRoot?: string, ) { - const project = yield* projects.getById(input.projectId).pipe( + const project = yield* projects.getById(projectId).pipe( Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })), Effect.flatMap( Option.match({ - onNone: () => - Effect.fail(new AgentSessionImportProjectNotFoundError({ projectId: input.projectId })), + onNone: () => Effect.fail(new AgentSessionImportProjectNotFoundError({ projectId })), onSome: Effect.succeed, }), ), ); if ( - input.expectedWorkspaceRoot !== undefined && + expectedWorkspaceRoot !== undefined && normalizeProjectPathForComparison(project.workspaceRoot) !== - normalizeProjectPathForComparison(input.expectedWorkspaceRoot) + normalizeProjectPathForComparison(expectedWorkspaceRoot) ) { - return yield* new AgentSessionImportProjectChangedError({ projectId: input.projectId }); + return yield* new AgentSessionImportProjectChangedError({ projectId }); } - // Imports run in full access, except under a policy ceiling: then in the project's default, - // which the policy keeps under it, so imported threads never sit above the ceiling. - const runtimeMode = - ceiling === undefined - ? DEFAULT_RUNTIME_MODE - : yield* settingsService.getSettings.pipe( - Effect.mapError( - (cause) => new AgentSessionScanError({ operation: "read-settings", cause }), - ), - Effect.map((settings) => { - const mode = resolveProjectSettings(settings, input.projectId, project).settings - .defaultRuntimeMode; - return isRuntimeModeAbove(mode, ceiling) ? ceiling : mode; - }), - ); + return project; + }); + + const resolveImportRuntimeMode = Effect.fn("AgentSessionImporter.resolveImportRuntimeMode")( + function* (projectId: ProjectId, project: Parameters[2]) { + // Imports run in full access, except under a policy ceiling: then in the project's default, + // which the policy keeps under it, so imported threads never sit above the ceiling. + if (ceiling === undefined) return DEFAULT_RUNTIME_MODE; + return yield* settingsService.getSettings.pipe( + Effect.mapError( + (cause) => new AgentSessionScanError({ operation: "read-settings", cause }), + ), + Effect.map((settings) => { + const mode = resolveProjectSettings(settings, projectId, project).settings + .defaultRuntimeMode; + return isRuntimeModeAbove(mode, ceiling) ? ceiling : mode; + }), + ); + }, + ); + + const completedSourcesFor = Effect.fn("AgentSessionImporter.completedSourcesFor")(function* ( + workspaceRoot: string, + ) { const runtimeRows = yield* runtimes .list() .pipe( @@ -242,18 +268,207 @@ const make = Effect.gen(function* () { (cause) => new AgentSessionScanError({ operation: "read-projects", cause }), ), ); - const completedSources = runtimeRows.flatMap((runtime) => { + return runtimeRows.flatMap((runtime) => { const payload = AgentSessionScanner.decodeImportedTranscriptPayload(runtime.runtimePayload); if ( Option.isNone(payload) || payload.value.cwd === undefined || normalizeProjectPathForComparison(payload.value.cwd) !== - normalizeProjectPathForComparison(project.workspaceRoot) + normalizeProjectPathForComparison(workspaceRoot) ) { return []; } return payload.value.importedTranscripts ?? []; }); + }); + + const importOneThread = Effect.fn("AgentSessionImporter.importOneThread")(function* (input: { + readonly projectId: ProjectId; + readonly workspaceRoot: string; + readonly runtimeMode: RuntimeMode; + readonly outcome: Extract; + readonly title?: string | undefined; + }) { + const { source, thread } = input.outcome; + const threadId = importedThreadId(source); + if ( + thread.source === "claudeAgent" && + !CLAUDE_SESSION_ID_PATTERN.test(thread.providerSessionId) + ) { + return yield* new AgentSessionUnresumableSessionError({ + source: thread.source, + providerSessionId: thread.providerSessionId, + }); + } + const driver = ProviderDriverKind.make(thread.source); + // Pi resumes by session file path; its session UUID only names the thread. + const nativeThreadId = thread.source === "pi" ? source.filePath : thread.providerSessionId; + const persistRuntime = runtimes.upsert( + { + threadId, + providerName: driver, + providerInstanceId: thread.providerInstanceId, + adapterKey: driver, + runtimeMode: input.runtimeMode, + status: "stopped", + lastSeenAt: thread.updatedAt, + resumeCursor: + thread.source === "claudeAgent" + ? { threadId, resume: thread.providerSessionId } + : { threadId: nativeThreadId }, + runtimePayload: { cwd: input.workspaceRoot }, + }, + { onConflict: "ignore" }, + ); + const existing = yield* Effect.option(orchestrator.getThreadRecords(threadId, [])); + if (Option.isSome(existing)) { + if (existing.value.thread.projectId !== input.projectId) { + return yield* new AgentSessionThreadProjectConflictError({ + threadId, + expectedProjectId: input.projectId, + actualProjectId: existing.value.thread.projectId, + }); + } + if (existing.value.thread.historyOrigin !== "v1_import") { + return yield* new AgentSessionThreadModifiedError({ threadId }); + } + yield* persistRuntime; + yield* runtimes.recordImportedTranscript({ threadId, source }); + return { threadId, status: "already_present" as const }; + } + + const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[driver] ?? DEFAULT_MODEL; + const providerThreadId = idAllocator.derive.providerThread({ + driver, + providerInstanceId: thread.providerInstanceId, + nativeThreadId, + }); + const createdAt = dateTime(thread.createdAt); + const updatedAt = dateTime(thread.updatedAt); + const title = + input.title?.trim() || (thread.title.trim() === "" ? "Untitled thread" : thread.title); + const appThread: OrchestrationV2AppThread = { + createdBy: "system", + creationSource: "server", + id: threadId, + projectId: input.projectId, + title, + providerInstanceId: thread.providerInstanceId, + modelSelection: { instanceId: thread.providerInstanceId, model }, + runtimeMode: input.runtimeMode, + interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, + branch: null, + worktreePath: null, + linkedPullRequest: null, + branchPullRequest: null, + activeProviderThreadId: providerThreadId, + historyOrigin: "v1_import", + lineage: { + parentThreadId: null, + relationshipToParent: null, + rootThreadId: threadId, + }, + forkedFrom: null, + createdAt, + updatedAt, + archivedAt: null, + settledOverride: "settled", + settledAt: updatedAt, + unsettledAt: null, + snoozedUntil: null, + snoozedAt: null, + pinnedAt: null, + pinOrderKey: null, + activeOrderKey: null, + lastVisitedAt: null, + deletedAt: null, + }; + const providerThread: OrchestrationV2ProviderThread = { + id: providerThreadId, + driver, + providerInstanceId: thread.providerInstanceId, + providerSessionId: null, + appThreadId: threadId, + ownerNodeId: null, + nativeThreadRef: { + driver, + nativeId: nativeThreadId, + strength: "strong", + }, + nativeConversationHeadRef: null, + status: "idle", + firstRunOrdinal: null, + lastRunOrdinal: null, + handoffIds: [], + forkedFrom: null, + pendingBackgroundTasks: [], + createdAt, + updatedAt, + }; + + const committed = yield* eventSink.write({ + unlessNativeThreadOwned: providerThread, + events: [ + { + id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${threadId}:created`), + type: "thread.created", + threadId, + providerInstanceId: thread.providerInstanceId, + occurredAt: createdAt, + payload: appThread, + }, + ...(thread.omittedMessageCount > 0 + ? [ + { + id: EventId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), + type: "turn-item.updated" as const, + threadId, + occurredAt: createdAt, + payload: { + id: TurnItemId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), + threadId, + runId: null, + nodeId: null, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 0, + status: "completed" as const, + title: null, + startedAt: createdAt, + completedAt: createdAt, + updatedAt: createdAt, + type: "system_notice" as const, + message: `${thread.omittedMessageCount} earlier ${thread.omittedMessageCount === 1 ? "message was" : "messages were"} not imported. This thread keeps the first user message and the most recent history. The original session transcript is unchanged.`, + }, + }, + ] + : []), + ...thread.messages.flatMap((message, index) => messageEvents({ threadId, index, message })), + { + id: EventId.make(`${IMPORT_EVENT_PREFIX}:provider-thread:${providerThreadId}`), + type: "provider-thread.updated", + threadId, + driver, + providerInstanceId: thread.providerInstanceId, + occurredAt: updatedAt, + payload: providerThread, + }, + ], + }); + if (committed.length === 0) return null; + yield* persistRuntime; + yield* runtimes.recordImportedTranscript({ threadId, source }); + return { threadId, status: "created" as const }; + }); + + const importRecentAgentThreads = Effect.fn("importRecentAgentThreadsV2")(function* ( + input: AgentSessionImportInput, + ) { + const project = yield* requireProject(input.projectId, input.expectedWorkspaceRoot); + const runtimeMode = yield* resolveImportRuntimeMode(input.projectId, project); + const completedSources = yield* completedSourcesFor(project.workspaceRoot); const outcomes = scanner.recentThreads(project.workspaceRoot, completedSources); const importedThreadIds = new Set(); let importedCount = 0; @@ -266,9 +481,7 @@ const make = Effect.gen(function* () { return; } const source = outcome.source; - const threadId = ThreadId.make( - `import:${source.providerInstanceId}:${source.providerSessionId}`, - ); + const threadId = importedThreadId(source); if (outcome._tag === "AlreadyImported") { importedThreadIds.add(threadId); importedCount += 1; @@ -281,180 +494,14 @@ const make = Effect.gen(function* () { return; } - const imported = yield* Effect.gen(function* () { - const thread = outcome.thread; - if ( - thread.source === "claudeAgent" && - !CLAUDE_SESSION_ID_PATTERN.test(thread.providerSessionId) - ) { - return yield* new AgentSessionUnresumableSessionError({ - source: thread.source, - providerSessionId: thread.providerSessionId, - }); - } - const driver = ProviderDriverKind.make(thread.source); - // Pi resumes by session file path; its session UUID only names the thread. - const nativeThreadId = - thread.source === "pi" ? source.filePath : thread.providerSessionId; - const persistRuntime = runtimes.upsert( - { - threadId, - providerName: driver, - providerInstanceId: thread.providerInstanceId, - adapterKey: driver, - runtimeMode, - status: "stopped", - lastSeenAt: thread.updatedAt, - resumeCursor: - thread.source === "claudeAgent" - ? { threadId, resume: thread.providerSessionId } - : { threadId: nativeThreadId }, - runtimePayload: { cwd: project.workspaceRoot }, - }, - { onConflict: "ignore" }, - ); - const existing = yield* Effect.option(orchestrator.getThreadRecords(threadId, [])); - if (Option.isSome(existing)) { - if (existing.value.thread.projectId !== input.projectId) { - return yield* new AgentSessionThreadProjectConflictError({ - threadId, - expectedProjectId: input.projectId, - actualProjectId: existing.value.thread.projectId, - }); - } - if (existing.value.thread.historyOrigin !== "v1_import") { - return yield* new AgentSessionThreadModifiedError({ threadId }); - } - yield* persistRuntime; - yield* runtimes.recordImportedTranscript({ threadId, source }); - return true; - } - - const model = thread.model ?? DEFAULT_MODEL_BY_PROVIDER[driver] ?? DEFAULT_MODEL; - const providerThreadId = idAllocator.derive.providerThread({ - driver, - providerInstanceId: thread.providerInstanceId, - nativeThreadId, - }); - const createdAt = dateTime(thread.createdAt); - const updatedAt = dateTime(thread.updatedAt); - const appThread: OrchestrationV2AppThread = { - createdBy: "system", - creationSource: "server", - id: threadId, - projectId: input.projectId, - title: thread.title.trim() === "" ? "Untitled thread" : thread.title, - providerInstanceId: thread.providerInstanceId, - modelSelection: { instanceId: thread.providerInstanceId, model }, - runtimeMode, - interactionMode: DEFAULT_PROVIDER_INTERACTION_MODE, - branch: null, - worktreePath: null, - linkedPullRequest: null, - branchPullRequest: null, - activeProviderThreadId: providerThreadId, - historyOrigin: "v1_import", - lineage: { - parentThreadId: null, - relationshipToParent: null, - rootThreadId: threadId, - }, - forkedFrom: null, - createdAt, - updatedAt, - archivedAt: null, - settledOverride: "settled", - settledAt: updatedAt, - unsettledAt: null, - snoozedUntil: null, - snoozedAt: null, - pinnedAt: null, - pinOrderKey: null, - activeOrderKey: null, - lastVisitedAt: null, - deletedAt: null, - }; - const providerThread: OrchestrationV2ProviderThread = { - id: providerThreadId, - driver, - providerInstanceId: thread.providerInstanceId, - providerSessionId: null, - appThreadId: threadId, - ownerNodeId: null, - nativeThreadRef: { - driver, - nativeId: nativeThreadId, - strength: "strong", - }, - nativeConversationHeadRef: null, - status: "idle", - firstRunOrdinal: null, - lastRunOrdinal: null, - handoffIds: [], - forkedFrom: null, - pendingBackgroundTasks: [], - createdAt, - updatedAt, - }; - - const committed = yield* eventSink.write({ - unlessNativeThreadOwned: providerThread, - events: [ - { - id: EventId.make(`${IMPORT_EVENT_PREFIX}:thread:${threadId}:created`), - type: "thread.created", - threadId, - providerInstanceId: thread.providerInstanceId, - occurredAt: createdAt, - payload: appThread, - }, - ...(thread.omittedMessageCount > 0 - ? [ - { - id: EventId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), - type: "turn-item.updated" as const, - threadId, - occurredAt: createdAt, - payload: { - id: TurnItemId.make(`${IMPORT_EVENT_PREFIX}:history-truncated:${threadId}`), - threadId, - runId: null, - nodeId: null, - providerThreadId: null, - providerTurnId: null, - nativeItemRef: null, - parentItemId: null, - ordinal: 0, - status: "completed" as const, - title: null, - startedAt: createdAt, - completedAt: createdAt, - updatedAt: createdAt, - type: "system_notice" as const, - message: `${thread.omittedMessageCount} earlier ${thread.omittedMessageCount === 1 ? "message was" : "messages were"} not imported. This thread keeps the first user message and the most recent history. The original session transcript is unchanged.`, - }, - }, - ] - : []), - ...thread.messages.flatMap((message, index) => - messageEvents({ threadId, index, message }), - ), - { - id: EventId.make(`${IMPORT_EVENT_PREFIX}:provider-thread:${providerThreadId}`), - type: "provider-thread.updated", - threadId, - driver, - providerInstanceId: thread.providerInstanceId, - occurredAt: updatedAt, - payload: providerThread, - }, - ], - }); - if (committed.length === 0) return null; - yield* persistRuntime; - yield* runtimes.recordImportedTranscript({ threadId, source }); - return true; + const imported = yield* importOneThread({ + projectId: input.projectId, + workspaceRoot: project.workspaceRoot, + runtimeMode, + outcome, }).pipe( + // null: another thread already owns the native session. + Effect.map((result) => (result === null ? null : true)), Effect.catch((cause) => Effect.logWarning("Could not import an agent session", { provider: outcome.thread.source, @@ -475,6 +522,121 @@ const make = Effect.gen(function* () { return { importedCount, skippedCount } satisfies AgentSessionImportResult; }); + const listSessions = Effect.fn("AgentSessionImporter.listSessions")(function* ( + input: AgentSessionListInput, + ) { + const project = yield* projects.getById(input.projectId).pipe( + Effect.mapError((cause) => new AgentSessionScanError({ operation: "read-projects", cause })), + Effect.flatMap( + Option.match({ + onNone: () => + Effect.fail(new AgentSessionImportProjectNotFoundError({ projectId: input.projectId })), + onSome: Effect.succeed, + }), + ), + ); + const provider = input.provider ?? "claudeAgent"; + // Skip completedSources so list keeps titles; adoption status comes from the thread id. + const outcomes = yield* scanner.recentThreads(project.workspaceRoot).pipe(Stream.runCollect); + const sessions: Array = []; + for (const outcome of outcomes) { + if (outcome._tag !== "Importable") continue; + if (outcome.thread.source !== provider) continue; + const threadId = importedThreadId(outcome.source); + const existing = yield* Effect.option(orchestrator.getThreadRecords(threadId, [])); + sessions.push({ + provider, + providerInstanceId: outcome.source.providerInstanceId, + providerSessionId: outcome.source.providerSessionId, + title: + outcome.thread.title.trim() === "" + ? outcome.source.providerSessionId + : outcome.thread.title, + model: outcome.thread.model, + updatedAt: outcome.thread.updatedAt, + filePath: outcome.source.filePath, + importedThreadId: Option.isSome(existing) ? threadId : null, + }); + } + sessions.sort((left, right) => right.updatedAt.localeCompare(left.updatedAt)); + return { sessions: sessions.slice(0, 256) } satisfies AgentSessionListResult; + }); + + const adoptSession = Effect.fn("AgentSessionImporter.adoptSession")(function* ( + input: AgentSessionAdoptInput, + ) { + const project = yield* requireProject(input.projectId, input.expectedWorkspaceRoot); + const runtimeMode = yield* resolveImportRuntimeMode(input.projectId, project); + const threadId = importedThreadId({ + providerInstanceId: input.providerInstanceId, + providerSessionId: input.providerSessionId, + }); + const existing = yield* Effect.option(orchestrator.getThreadRecords(threadId, [])); + if (Option.isSome(existing)) { + if (existing.value.thread.projectId !== input.projectId) { + return yield* new AgentSessionAdoptUnavailableError({ + provider: input.provider, + providerSessionId: input.providerSessionId, + reason: "import_failed", + }); + } + return { threadId, adopted: false } satisfies AgentSessionAdoptResult; + } + + const outcomes = yield* scanner.recentThreads(project.workspaceRoot).pipe(Stream.runCollect); + const match = outcomes.find( + (outcome): outcome is Extract => + outcome._tag === "Importable" && + outcome.thread.source === input.provider && + outcome.source.providerInstanceId === input.providerInstanceId && + outcome.source.providerSessionId === input.providerSessionId, + ); + if (match === undefined) { + return yield* new AgentSessionAdoptNotFoundError({ + projectId: input.projectId, + provider: input.provider, + providerSessionId: input.providerSessionId, + }); + } + + const result = yield* importOneThread({ + projectId: input.projectId, + workspaceRoot: project.workspaceRoot, + runtimeMode, + outcome: match, + title: input.title, + }).pipe( + Effect.mapError((cause) => { + const reason = isAgentSessionUnresumableSessionError(cause) + ? "unresumable" + : "import_failed"; + return new AgentSessionAdoptUnavailableError({ + provider: input.provider, + providerSessionId: input.providerSessionId, + reason, + }); + }), + Effect.tapError((error) => + Effect.logWarning("Could not adopt an agent session", { + provider: input.provider, + sessionId: input.providerSessionId, + reason: error.reason, + }), + ), + ); + if (result === null) { + return yield* new AgentSessionAdoptUnavailableError({ + provider: input.provider, + providerSessionId: input.providerSessionId, + reason: "owned", + }); + } + return { + threadId: result.threadId, + adopted: result.status === "created", + } satisfies AgentSessionAdoptResult; + }); + /** * Loading a native session replays its history only into the adapter's own * snapshot, so copy that snapshot into the thread as run-less history. The @@ -573,7 +735,7 @@ const make = Effect.gen(function* () { return yield* commit(messages); }); - return { importRecentAgentThreads, importNativeHistory }; + return { importRecentAgentThreads, listSessions, adoptSession, importNativeHistory }; }); type AgentSessionImporterShape = Effect.Success; diff --git a/apps/server/src/telemetry/FeatureUsage.ts b/apps/server/src/telemetry/FeatureUsage.ts index 61fb57ada454e..4ec11e9b0ab9c 100644 --- a/apps/server/src/telemetry/FeatureUsage.ts +++ b/apps/server/src/telemetry/FeatureUsage.ts @@ -68,6 +68,7 @@ const METHOD_FEATURES: Readonly FeatureUsag [WS_METHODS.scheduledTasksUpsert]: () => ({ feature: "scheduled_task.save" }), [WS_METHODS.scheduledTasksRunNow]: () => ({ feature: "scheduled_task.run_now" }), [WS_METHODS.agentSessionsImport]: () => ({ feature: "agent_session.import" }), + [WS_METHODS.agentSessionsAdopt]: () => ({ feature: "agent_session.adopt" }), [WS_METHODS.projectCloneStart]: () => ({ feature: "project.clone" }), [WS_METHODS.sourceControlPublishRepository]: () => ({ feature: "repository.publish" }), [WS_METHODS.sourceControlSignInStart]: () => ({ feature: "source_control.sign_in" }), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 5257da599c4f2..93258a07027f8 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -2957,6 +2957,8 @@ export const layerWsRpc = ( [WS_METHODS.agentSessionsScan]: () => agentSessionScanner.scan, [WS_METHODS.agentSessionsImport]: (input) => agentSessionImporter.importRecentAgentThreads(input), + [WS_METHODS.agentSessionsList]: (input) => agentSessionImporter.listSessions(input), + [WS_METHODS.agentSessionsAdopt]: (input) => agentSessionImporter.adoptSession(input), [WS_METHODS.assetsCreateUrl]: /* Request instrumentation already owns the span; keep this helper in that context. */ Effect.fnUntraced(function* (input) { diff --git a/apps/web/src/components/settings/ClaudeSessionAdoptSection.tsx b/apps/web/src/components/settings/ClaudeSessionAdoptSection.tsx new file mode 100644 index 0000000000000..363e23d3d4c49 --- /dev/null +++ b/apps/web/src/components/settings/ClaudeSessionAdoptSection.tsx @@ -0,0 +1,239 @@ +import { + AuthOrchestrationOperateScope, + AuthOrchestrationReadScope, + type AgentSessionListed, + type EnvironmentId, + type ProjectId, +} from "@t3tools/contracts"; +import { + isAtomCommandInterrupted, + squashAtomCommandFailure, + type AtomCommandResult, +} from "@t3tools/client-runtime/state/runtime"; +import { useLayoutEffect, useRef, useState } from "react"; + +import { useEnvironmentScope, readEnvironmentScope } from "~/state/session"; +import { agentSessionAdopt, agentSessionList } from "../../state/agentSessions"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { Button } from "../ui/button"; +import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; +import { toastManager } from "../ui/toast"; +import { SettingsRow, SettingsSection } from "./settingsLayout"; + +interface ClaudeSessionProject { + readonly id: ProjectId; + readonly title: string; + readonly workspaceRoot: string; +} + +function reportFailure(title: string, result: AtomCommandResult) { + if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; + const error = squashAtomCommandFailure(result); + toastManager.add({ + type: "error", + title, + description: error instanceof Error ? error.message : "The adopt operation failed.", + }); +} + +interface ClaudeSessionAdoptProps { + readonly environmentId: EnvironmentId; + readonly projects: ReadonlyArray; + readonly readOnly: boolean; +} + +export function ClaudeSessionAdoptSection(props: ClaudeSessionAdoptProps) { + const [selectedProjectId, setSelectedProjectId] = useState(null); + const projectId = + props.projects.find((project) => project.id === selectedProjectId)?.id ?? + props.projects[0]?.id ?? + null; + if (selectedProjectId !== projectId) setSelectedProjectId(projectId); + + return ( + + ); +} + +function ProjectSessionAdopt( + props: ClaudeSessionAdoptProps & { + readonly projectId: ProjectId | null; + readonly onProjectChange: (projectId: ProjectId) => void; + }, +) { + const canOperate = useEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope); + const canRead = useEnvironmentScope(props.environmentId, AuthOrchestrationReadScope); + const { projectId } = props; + const projectGeneration = useRef(0); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- Late continuations must not act on a replaced project scope. + useLayoutEffect(() => { + return () => { + projectGeneration.current += 1; + }; + // oxlint-disable-next-line react/exhaustive-effect-dependencies -- Retiring a project invalidates its pending operations even when the instance stays mounted. + }, [projectId]); + const [sessions, setSessions] = useState>([]); + const [loading, setLoading] = useState(false); + const [adoptingSessionId, setAdoptingSessionId] = useState(null); + const [previousProjectId, setPreviousProjectId] = useState(projectId); + if (previousProjectId !== projectId) { + setPreviousProjectId(projectId); + setSessions([]); + setLoading(false); + setAdoptingSessionId(null); + } + const listSessions = useAtomCommand(agentSessionList, { reportFailure: false }); + const adoptSession = useAtomCommand(agentSessionAdopt, { reportFailure: false }); + + const loadSessions = async () => { + const generation = projectGeneration.current; + if (projectId === null || loading) return; + setLoading(true); + const result = await listSessions({ + environmentId: props.environmentId, + input: { projectId, provider: "claudeAgent" }, + }); + if (generation !== projectGeneration.current) return; + setLoading(false); + if (result._tag === "Success") { + setSessions(result.value.sessions); + return; + } + reportFailure("Could not list Claude sessions", result); + }; + + const adoptListedSession = async (session: AgentSessionListed) => { + const generation = projectGeneration.current; + if ( + !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope) || + projectId === null || + adoptingSessionId !== null || + session.importedThreadId !== null + ) + return; + setAdoptingSessionId(session.providerSessionId); + const result = await adoptSession({ + environmentId: props.environmentId, + input: { + projectId, + provider: "claudeAgent", + providerInstanceId: session.providerInstanceId, + providerSessionId: session.providerSessionId, + title: session.title, + }, + }); + if (generation !== projectGeneration.current) return; + setAdoptingSessionId(null); + if (result._tag === "Success") { + setSessions((current) => + current.map((candidate) => + candidate.providerSessionId === session.providerSessionId + ? { ...candidate, importedThreadId: result.value.threadId } + : candidate, + ), + ); + toastManager.add({ + type: "success", + title: result.value.adopted ? "Claude session adopted" : "Claude session already adopted", + }); + return; + } + reportFailure("Could not adopt Claude session", result); + }; + + return ( + + + {props.projects.length > 0 ? ( + <> + + + + ) : null} + + } + > + {sessions.length > 0 ? ( +
+ {sessions.map((session) => ( +
+
+

{session.title}

+ + {session.providerSessionId} + +
+ +
+ ))} +
+ ) : null} +
+
+ ); +} diff --git a/apps/web/src/components/settings/ProviderInstanceCard.tsx b/apps/web/src/components/settings/ProviderInstanceCard.tsx index 36a737959c508..c211d1bab5ca9 100644 --- a/apps/web/src/components/settings/ProviderInstanceCard.tsx +++ b/apps/web/src/components/settings/ProviderInstanceCard.tsx @@ -68,6 +68,7 @@ import { ProviderAccentColorPicker } from "./ProviderAccentColorPicker"; import { RedactedSensitiveText } from "./RedactedSensitiveText"; import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout"; import { AcpSessionManagementSection } from "./AcpSessionManagementSection"; +import { ClaudeSessionAdoptSection } from "./ClaudeSessionAdoptSection"; import { FoldedSettingsSection } from "./FoldedSettingsSection"; import { readCodexSetupMode } from "./CodexSetupSection.logic"; import { getProviderRestartNotice } from "../ProviderUpdateLaunchNotification.logic"; @@ -1393,6 +1394,13 @@ export function ProviderInstanceCard({ readOnly={readOnly} /> ) : null} + {environmentId !== undefined && driverKind === "claudeAgent" ? ( + + ) : null} {driverOption !== undefined ? ( diff --git a/apps/web/src/state/agentSessions.ts b/apps/web/src/state/agentSessions.ts index 58670d4d6c8f0..e969851430074 100644 --- a/apps/web/src/state/agentSessions.ts +++ b/apps/web/src/state/agentSessions.ts @@ -17,3 +17,23 @@ export const agentSessionImport = createEnvironmentRpcCommand(connectionAtomRunt label: "environment-data:agent-sessions:import", tag: WS_METHODS.agentSessionsImport, }); + +export const agentSessionList = createEnvironmentRpcCommand(connectionAtomRuntime, { + label: "environment-data:agent-sessions:list", + tag: WS_METHODS.agentSessionsList, + concurrency: { + mode: "singleFlight", + key: ({ environmentId, input }) => + `${environmentId}:${input.projectId}:${input.provider ?? "claudeAgent"}`, + }, +}); + +export const agentSessionAdopt = createEnvironmentRpcCommand(connectionAtomRuntime, { + label: "environment-data:agent-sessions:adopt", + tag: WS_METHODS.agentSessionsAdopt, + concurrency: { + mode: "singleFlight", + key: ({ environmentId, input }) => + `${environmentId}:${input.projectId}:${input.providerInstanceId}:${input.providerSessionId}`, + }, +}); diff --git a/docs/user/providers-claude.md b/docs/user/providers-claude.md index 5d4295a942638..4e413dde71e55 100644 --- a/docs/user/providers-claude.md +++ b/docs/user/providers-claude.md @@ -81,6 +81,15 @@ over 200,000 tokens. Each Claude provider's settings can override it: - **Never** skips idle compaction and Claude's resume prompt. **Auto-compact after** still applies, and you can still compact by hand. +## Adopt existing sessions + +To bring a Claude Code session you already ran outside T3 Code into a managed +thread, open **Settings > Providers**, expand the Claude instance, choose a +project under **Adopt sessions**, and select **Discover**. **Adopt** creates a +T3 thread bound to that session id so later turns resume it instead of starting +cold. Adopting the same session again returns the existing thread. Onboarding +can still import every recent session for a project in one step. + ## Usage limits If your Claude subscription runs out of usage mid-turn, the thread shows which diff --git a/packages/contracts/src/agentSessions.ts b/packages/contracts/src/agentSessions.ts index 93e0e36e4fbd4..d6fc6e0528c10 100644 --- a/packages/contracts/src/agentSessions.ts +++ b/packages/contracts/src/agentSessions.ts @@ -1,10 +1,20 @@ import * as Schema from "effect/Schema"; -import { IsoDateTime, NonNegativeInt, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { + IsoDateTime, + NonNegativeInt, + ProjectId, + ThreadId, + TrimmedNonEmptyString, +} from "./baseSchemas.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; export const AgentSessionSource = Schema.Literals(["claudeAgent", "codex", "pi"]); export type AgentSessionSource = typeof AgentSessionSource.Type; +/** First adopt slice is Claude; Codex/Pi reuse the same shape when their UI lands. */ +export const AgentSessionAdoptSource = Schema.Literal("claudeAgent"); +export type AgentSessionAdoptSource = typeof AgentSessionAdoptSource.Type; + export const AgentSessionImportSource = Schema.Struct({ provider: AgentSessionSource, providerInstanceId: ProviderInstanceId, @@ -89,3 +99,75 @@ export class AgentSessionScanError extends Schema.TaggedError()( + "AgentSessionAdoptNotFoundError", + { + projectId: ProjectId, + provider: AgentSessionAdoptSource, + providerSessionId: TrimmedNonEmptyString, + }, +) { + override get message(): string { + return `No ${this.provider} session '${this.providerSessionId}' was found for project '${this.projectId}'.`; + } +} + +export class AgentSessionAdoptUnavailableError extends Schema.TaggedError()( + "AgentSessionAdoptUnavailableError", + { + provider: AgentSessionAdoptSource, + providerSessionId: TrimmedNonEmptyString, + reason: Schema.Literals(["owned", "unresumable", "import_failed"]), + }, +) { + override get message(): string { + switch (this.reason) { + case "owned": + return `Session '${this.providerSessionId}' is already bound to another T3 thread.`; + case "unresumable": + return `Session '${this.providerSessionId}' cannot be resumed.`; + case "import_failed": + return `Could not adopt session '${this.providerSessionId}'.`; + } + } +} diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 0f6af19188e18..3b930366a7465 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -91,10 +91,16 @@ import { FilesystemBrowseError, } from "./filesystem.ts"; import { + AgentSessionAdoptInput, + AgentSessionAdoptNotFoundError, + AgentSessionAdoptResult, + AgentSessionAdoptUnavailableError, AgentSessionImportInput, AgentSessionImportProjectChangedError, AgentSessionImportProjectNotFoundError, AgentSessionImportResult, + AgentSessionListInput, + AgentSessionListResult, AgentSessionScanInput, AgentSessionScanResult, AgentSessionScanError, @@ -430,6 +436,8 @@ export const WS_METHODS = { filesystemGetMetadata: "filesystem.getMetadata", agentSessionsScan: "agentSessions.scan", agentSessionsImport: "agentSessions.import", + agentSessionsList: "agentSessions.list", + agentSessionsAdopt: "agentSessions.adopt", assetsCreateUrl: "assets.createUrl", assetsPersistChatAttachments: "assets.persistChatAttachments", attachmentsCreateUploadUrl: "attachments.createUploadUrl", @@ -1427,6 +1435,29 @@ const WsAgentSessionsImportRpc = Rpc.make(WS_METHODS.agentSessionsImport, { ]), }); +const WsAgentSessionsListRpc = Rpc.make(WS_METHODS.agentSessionsList, { + payload: AgentSessionListInput, + success: AgentSessionListResult, + error: Schema.Union([ + AgentSessionImportProjectNotFoundError, + AgentSessionScanError, + EnvironmentAuthorizationError, + ]), +}); + +const WsAgentSessionsAdoptRpc = Rpc.make(WS_METHODS.agentSessionsAdopt, { + payload: AgentSessionAdoptInput, + success: AgentSessionAdoptResult, + error: Schema.Union([ + AgentSessionAdoptNotFoundError, + AgentSessionAdoptUnavailableError, + AgentSessionImportProjectChangedError, + AgentSessionImportProjectNotFoundError, + AgentSessionScanError, + EnvironmentAuthorizationError, + ]), +}); + const WsAssetsCreateUrlRpc = Rpc.make(WS_METHODS.assetsCreateUrl, { payload: AssetCreateUrlInput, success: AssetCreateUrlResult, @@ -2198,6 +2229,8 @@ export const WsRpcGroup = RpcGroup.make( WsFilesystemGetMetadataRpc, WsAgentSessionsScanRpc, WsAgentSessionsImportRpc, + WsAgentSessionsListRpc, + WsAgentSessionsAdoptRpc, WsAssetsCreateUrlRpc, WsAssetsPersistChatAttachmentsRpc, WsAttachmentsCreateUploadUrlRpc, From 95c5ee66a3d7b81491245b5ef86c6e19914fd265 Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Wed, 11 Nov 2026 14:34:22 -0800 Subject: [PATCH 2/4] fix(server): refresh Claude session discovery on adopt list Discover/Adopt bypass the permanent scanner candidate cache so sessions created after the first discovery show up without a server restart. --- .../src/project/AgentSessionImporter.ts | 8 ++- .../src/project/AgentSessionScanner.test.ts | 61 +++++++++++++++++++ .../server/src/project/AgentSessionScanner.ts | 12 +++- 3 files changed, 77 insertions(+), 4 deletions(-) diff --git a/apps/server/src/project/AgentSessionImporter.ts b/apps/server/src/project/AgentSessionImporter.ts index 39f39954303af..edbb277ad9546 100644 --- a/apps/server/src/project/AgentSessionImporter.ts +++ b/apps/server/src/project/AgentSessionImporter.ts @@ -537,7 +537,9 @@ const make = Effect.gen(function* () { ); const provider = input.provider ?? "claudeAgent"; // Skip completedSources so list keeps titles; adoption status comes from the thread id. - const outcomes = yield* scanner.recentThreads(project.workspaceRoot).pipe(Stream.runCollect); + const outcomes = yield* scanner + .recentThreads(project.workspaceRoot, [], { refresh: true }) + .pipe(Stream.runCollect); const sessions: Array = []; for (const outcome of outcomes) { if (outcome._tag !== "Importable") continue; @@ -583,7 +585,9 @@ const make = Effect.gen(function* () { return { threadId, adopted: false } satisfies AgentSessionAdoptResult; } - const outcomes = yield* scanner.recentThreads(project.workspaceRoot).pipe(Stream.runCollect); + const outcomes = yield* scanner + .recentThreads(project.workspaceRoot, [], { refresh: true }) + .pipe(Stream.runCollect); const match = outcomes.find( (outcome): outcome is Extract => outcome._tag === "Importable" && diff --git a/apps/server/src/project/AgentSessionScanner.test.ts b/apps/server/src/project/AgentSessionScanner.test.ts index ad7d6cfff4d4a..1dfdf9ab1c381 100644 --- a/apps/server/src/project/AgentSessionScanner.test.ts +++ b/apps/server/src/project/AgentSessionScanner.test.ts @@ -1150,6 +1150,67 @@ it.layer(NodeServices.layer)("AgentSessionScanner", (it) => { }); describe("recentThreads", () => { + it.effect("refresh rediscovers Claude sessions created after the first discovery", () => + Effect.gen(function* () { + const path = yield* Path.Path; + const nowMs = Date.parse("2026-08-24T12:00:00.000Z"); + yield* TestClock.setTime(nowMs); + const claudeHomePath = yield* makeTempDir("t3code-claude-home-refresh-"); + const codexHomePath = yield* makeTempDir("t3code-codex-home-refresh-"); + const workspace = yield* makeTempDir("t3code-workspace-refresh-"); + const claudeTranscript = (cwd: string, sessionId: string) => + `${JSON.stringify({ + type: "user", + cwd, + sessionId, + timestamp: "2026-08-24T11:00:00.000Z", + message: { role: "user", content: "First prompt" }, + })}\n${JSON.stringify({ + type: "assistant", + sessionId, + timestamp: "2026-08-24T11:01:00.000Z", + message: { role: "assistant", content: [{ type: "text", text: "Done" }] }, + })}\n`; + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-selected", "claude-first.jsonl"), + contents: claudeTranscript(workspace, "claude-first"), + mtimeMs: nowMs - 60_000, + }); + + yield* Effect.gen(function* () { + const scanner = yield* AgentSessionScanner.AgentSessionScanner; + const first = yield* scanner.recentThreads(workspace).pipe(Stream.runCollect); + expect( + first.flatMap((outcome) => + outcome._tag === "Importable" ? [outcome.thread.providerSessionId] : [], + ), + ).toEqual(["claude-first"]); + + yield* writeTranscript({ + filePath: path.join(claudeHomePath, "projects", "-selected", "claude-second.jsonl"), + contents: claudeTranscript(workspace, "claude-second"), + mtimeMs: nowMs - 30_000, + }); + + const stale = yield* scanner.recentThreads(workspace).pipe(Stream.runCollect); + expect( + stale.flatMap((outcome) => + outcome._tag === "Importable" ? [outcome.thread.providerSessionId] : [], + ), + ).toEqual(["claude-first"]); + + const refreshed = yield* scanner + .recentThreads(workspace, [], { refresh: true }) + .pipe(Stream.runCollect); + expect( + refreshed.flatMap((outcome) => + outcome._tag === "Importable" ? [outcome.thread.providerSessionId] : [], + ), + ).toEqual(["claude-second", "claude-first"]); + }).pipe(Effect.provide(layerScannerTest({ claudeHomePath, codexHomePath }))); + }), + ); + it.effect("imports recent Claude, Codex, and Pi sessions for the selected project only", () => Effect.gen(function* () { const path = yield* Path.Path; diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index fe206ac465133..b9957ce24ca57 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -228,6 +228,7 @@ export class AgentSessionScanner extends Context.Service< readonly recentThreads: ( workspaceRoot: string, completedSources?: ReadonlyArray, + options?: { readonly refresh?: boolean }, ) => Stream.Stream; } >()("t3/project/AgentSessionScanner") {} @@ -1807,6 +1808,7 @@ export const make = Effect.gen(function* () { const prepareRecentThreads = Effect.fn("AgentSessionScanner.prepareRecentThreads")(function* ( workspaceRoot: string, completedSources: ReadonlyArray, + options?: { readonly refresh?: boolean }, ) { const root = path.resolve(expandHomePath(workspaceRoot, homeDir)); const realRoot = yield* fileSystem.realPath(root).pipe(Effect.orElseSucceed(() => root)); @@ -1815,8 +1817,13 @@ export const make = Effect.gen(function* () { const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const cutoffMs = nowMs - RECENT_THREAD_WINDOW_MS; + // Onboarding scan fills the cache; bulk import reuses it. Explicit Discover/Adopt refresh. // Imports recorded since a budget-truncated collection can free budget for transcripts it cut off. - if (cachedCandidates === null || cachedCandidates.metadataTruncated) { + if ( + options?.refresh === true || + cachedCandidates === null || + cachedCandidates.metadataTruncated + ) { cachedCandidates = yield* collectCandidates(); } const { candidates } = cachedCandidates; @@ -2027,7 +2034,8 @@ export const make = Effect.gen(function* () { const recentThreads: AgentSessionScanner["Service"]["recentThreads"] = ( workspaceRoot, completedSources = [], - ) => Stream.unwrap(prepareRecentThreads(workspaceRoot, completedSources)); + options, + ) => Stream.unwrap(prepareRecentThreads(workspaceRoot, completedSources, options)); return AgentSessionScanner.of({ scan, recentThreads }); }); From 845f94d1200bc6d7ae113f08df9a08c5c850d4f3 Mon Sep 17 00:00:00 2001 From: maria-rcks Date: Wed, 11 Nov 2026 23:47:49 +0000 Subject: [PATCH 3/4] fix(web): expose projects for Claude session adoption --- apps/web/src/components/settings/ProviderSettingsPanel.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx index aca6e5eb56fc5..7a1972903f905 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx @@ -1265,7 +1265,8 @@ function ProviderInstanceRow({ const allProjects = useProjects(); const secretSources = useSecretSources(environmentId); const acpProjects = - mode === "editor" && liveProvider?.driver === "acpRegistry" + mode === "editor" && + (liveProvider?.driver === "acpRegistry" || liveProvider?.driver === "claudeAgent") ? allProjects.filter((project) => project.environmentId === environmentId) : undefined; const instance = explicitInstance ?? { driver }; From cb3279b4d74ee188c3225576c6dec1ba2e2cbaed Mon Sep 17 00:00:00 2001 From: wSedlacek Date: Wed, 11 Nov 2026 15:50:31 -0800 Subject: [PATCH 4/4] feat(web): project Import shortcut and open adopted Claude threads Prefer project settings / sidebar / palette for Claude session import, open the thread after import, and fix provider-card project listing plus macOS worktree realPath exclusion. --- .../server/src/project/AgentSessionScanner.ts | 11 +- apps/web/src/components/CommandPalette.tsx | 25 ++++ apps/web/src/components/Sidebar.tsx | 12 +- .../settings/ClaudeSessionAdoptSection.tsx | 118 +++++++++++------- .../settings/ProjectSettingsPanel.tsx | 15 +++ docs/user/providers-claude.md | 15 ++- 6 files changed, 144 insertions(+), 52 deletions(-) diff --git a/apps/server/src/project/AgentSessionScanner.ts b/apps/server/src/project/AgentSessionScanner.ts index b9957ce24ca57..5953913df1f9e 100644 --- a/apps/server/src/project/AgentSessionScanner.ts +++ b/apps/server/src/project/AgentSessionScanner.ts @@ -825,6 +825,11 @@ export const make = Effect.gen(function* () { const runtimes = yield* ProviderSessionRuntime.ProviderSessionRuntimeRepository; const baseDir = path.resolve(serverConfig.baseDir); const worktreesDir = path.resolve(serverConfig.worktreesDir); + // macOS resolves `/var/...` worktrees to `/private/var/...`; match both spellings. + const baseDirReal = yield* fileSystem.realPath(baseDir).pipe(Effect.orElseSucceed(() => baseDir)); + const worktreesDirReal = yield* fileSystem + .realPath(worktreesDir) + .pipe(Effect.orElseSucceed(() => worktreesDir)); const isWindows = (yield* HostProcess.Platform) === "win32"; const foldWorktreeCase = isWindows; const hostEnvironment = yield* HostProcess.Environment; @@ -850,7 +855,11 @@ export const make = Effect.gen(function* () { normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( normalizeForWorktreeMatch(baseDir, foldWorktreeCase), ) || - isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase); + normalizeForWorktreeMatch(candidatePath, foldWorktreeCase).startsWith( + normalizeForWorktreeMatch(baseDirReal, foldWorktreeCase), + ) || + isT3ManagedWorktree(candidatePath, worktreesDir, foldWorktreeCase) || + isT3ManagedWorktree(candidatePath, worktreesDirReal, foldWorktreeCase); const listDirectory = (directory: string) => fileSystem.readDirectory(directory).pipe(Effect.orElseSucceed((): ReadonlyArray => [])); diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 15c00fcba186d..df1dc3f1f9f20 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -1756,6 +1756,31 @@ function OpenCommandPaletteDialog(props: { }); }, }); + actionItems.push({ + kind: "action", + value: "action:project-import-claude-sessions", + searchTerms: [ + "import", + "adopt", + "claude", + "session", + "sessions", + "discover", + "project", + "history", + ], + title: "Import Claude sessions", + description: contextualProjectGroup.displayName, + icon: , + run: async () => { + await navigate({ + to: "/projects/$projectKey", + params: { projectKey: contextualProjectGroup.projectKey }, + hash: "import-claude-sessions", + hashScrollIntoView: false, + }); + }, + }); } const rootGroups = buildRootGroups({ actionItems, recentThreadItems }); diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 8fa58d8456f75..3a7884917daa6 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -1219,7 +1219,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve }); const openProjectSettings = useStableCallback( - (projectGroup: SidebarProjectSnapshot, projectRef?: ScopedProjectRef) => { + ( + projectGroup: SidebarProjectSnapshot, + projectRef?: ScopedProjectRef, + options?: { readonly hash?: string }, + ) => { if (isMobile) { setOpenMobile(false); } @@ -1233,6 +1237,8 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve projectRef, ), }, + ...(options?.hash === undefined ? {} : { hash: options.hash }), + hashScrollIntoView: false, }); }, ); @@ -1274,6 +1280,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve : { id: "pin", label: "Pin project", icon: "pin" }, ] : []), + { id: "import-claude-sessions", label: "Import Claude sessions" }, { id: "project-settings", label: "Project settings", icon: "settings" }, ], position, @@ -1291,6 +1298,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve case "unpin": setProjectGroupPinned(group, clicked.value === "pin"); return; + case "import-claude-sessions": + openProjectSettings(group, undefined, { hash: "import-claude-sessions" }); + return; case "project-settings": openProjectSettings(group); return; diff --git a/apps/web/src/components/settings/ClaudeSessionAdoptSection.tsx b/apps/web/src/components/settings/ClaudeSessionAdoptSection.tsx index 363e23d3d4c49..340cf65b57a19 100644 --- a/apps/web/src/components/settings/ClaudeSessionAdoptSection.tsx +++ b/apps/web/src/components/settings/ClaudeSessionAdoptSection.tsx @@ -4,20 +4,24 @@ import { type AgentSessionListed, type EnvironmentId, type ProjectId, + type ThreadId, } from "@t3tools/contracts"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { isAtomCommandInterrupted, squashAtomCommandFailure, type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; +import { useNavigate } from "@tanstack/react-router"; import { useLayoutEffect, useRef, useState } from "react"; import { useEnvironmentScope, readEnvironmentScope } from "~/state/session"; +import { buildThreadRouteParams } from "../../threadRoutes"; import { agentSessionAdopt, agentSessionList } from "../../state/agentSessions"; import { useAtomCommand } from "../../state/use-atom-command"; import { Button } from "../ui/button"; import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; -import { toastManager } from "../ui/toast"; +import { stackedThreadToast, toastManager } from "../ui/toast"; import { SettingsRow, SettingsSection } from "./settingsLayout"; interface ClaudeSessionProject { @@ -32,7 +36,7 @@ function reportFailure(title: string, result: AtomCommandResult; readonly readOnly: boolean; + /** When set, skip the project picker and import for this project only. */ + readonly lockedProjectId?: ProjectId; } export function ClaudeSessionAdoptSection(props: ClaudeSessionAdoptProps) { - const [selectedProjectId, setSelectedProjectId] = useState(null); + const locked = + props.lockedProjectId !== undefined + ? (props.projects.find((project) => project.id === props.lockedProjectId) ?? null) + : null; + const [selectedProjectId, setSelectedProjectId] = useState(locked?.id ?? null); const projectId = + locked?.id ?? props.projects.find((project) => project.id === selectedProjectId)?.id ?? props.projects[0]?.id ?? null; - if (selectedProjectId !== projectId) setSelectedProjectId(projectId); + if (locked === null && selectedProjectId !== projectId) setSelectedProjectId(projectId); return ( ); } @@ -64,8 +76,10 @@ function ProjectSessionAdopt( props: ClaudeSessionAdoptProps & { readonly projectId: ProjectId | null; readonly onProjectChange: (projectId: ProjectId) => void; + readonly projectSelectHidden: boolean; }, ) { + const navigate = useNavigate(); const canOperate = useEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope); const canRead = useEnvironmentScope(props.environmentId, AuthOrchestrationReadScope); const { projectId } = props; @@ -90,6 +104,13 @@ function ProjectSessionAdopt( const listSessions = useAtomCommand(agentSessionList, { reportFailure: false }); const adoptSession = useAtomCommand(agentSessionAdopt, { reportFailure: false }); + const openAdoptedThread = (threadId: ThreadId) => { + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)), + }); + }; + const loadSessions = async () => { const generation = projectGeneration.current; if (projectId === null || loading) return; @@ -109,11 +130,14 @@ function ProjectSessionAdopt( const adoptListedSession = async (session: AgentSessionListed) => { const generation = projectGeneration.current; + if (session.importedThreadId !== null) { + openAdoptedThread(session.importedThreadId); + return; + } if ( !readEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope) || projectId === null || - adoptingSessionId !== null || - session.importedThreadId !== null + adoptingSessionId !== null ) return; setAdoptingSessionId(session.providerSessionId); @@ -137,53 +161,60 @@ function ProjectSessionAdopt( : candidate, ), ); - toastManager.add({ - type: "success", - title: result.value.adopted ? "Claude session adopted" : "Claude session already adopted", - }); + toastManager.add( + stackedThreadToast({ + type: "success", + title: result.value.adopted + ? "Claude session imported" + : "Claude session already imported", + }), + ); + openAdoptedThread(result.value.threadId); return; } - reportFailure("Could not adopt Claude session", result); + reportFailure("Could not import Claude session", result); }; return ( - + {props.projects.length > 0 ? ( <> - + + + {props.projects.find((project) => project.id === projectId)?.title} + + + + {props.projects.map((project) => ( + + {project.title} + + ))} + + + )} ))} diff --git a/apps/web/src/components/settings/ProjectSettingsPanel.tsx b/apps/web/src/components/settings/ProjectSettingsPanel.tsx index fe0ac1e4e152f..37bbe05d968d2 100644 --- a/apps/web/src/components/settings/ProjectSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProjectSettingsPanel.tsx @@ -48,6 +48,7 @@ import { canPickExternalProjectFavicon, ProjectFaviconPickerDialog, } from "./ProjectFaviconPickerDialog"; +import { ClaudeSessionAdoptSection } from "./ClaudeSessionAdoptSection"; import { ProjectActionsSettings } from "./ProjectActionsSettings"; import { ProjectDefaultsSettings } from "./ProjectDefaultsSettings"; import { @@ -651,6 +652,20 @@ function ProjectDetail({ + {filePickerProject ? ( + + ) : null} {checkoutChoices} Providers**, expand the Claude instance, choose a -project under **Adopt sessions**, and select **Discover**. **Adopt** creates a -T3 thread bound to that session id so later turns resume it instead of starting -cold. Adopting the same session again returns the existing thread. Onboarding -can still import every recent session for a project in one step. +thread, open the project (**Settings > Projects**, the project folder menu, or +**Import Claude sessions** in the command palette), then under **Import Claude +sessions** select **Discover**. **Import** creates a T3 thread bound to that +session id and opens it so later turns resume the session instead of starting +cold. Importing the same session again opens the existing thread. The same +controls also live on the Claude provider card. Onboarding can still import +every recent session for a project in one step. This is separate from connecting +Claude as an outside MCP app. ## Usage limits