Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
Merge remote-tracking branch 'upstream/main' into fix/session-move-worktree-bound
Zhang Yunjin81f267b8d8e5
diff --cc apps/desktop/src/main/bootstrap-electron.tsindex 29a82f32d3,0422b01cba..fba20f16f9--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@@ -8993,9 -8882,6 +8883,7 @@@ app.on('ready', async () =>readHistoryLiveMessages: getSessionThinkingSnapshots,resolveContextWindow: (session) => resolveSessionContextWindow(getActiveCatalog(), session),requestWorktreeRecycle,+ lookupSessionWorktreeBinding: (sessionId) => worktreeStore.get(sessionId)?.path ?? null,- cancelSessionOperations: cancelIOSSimulatorSessionOperations,- cleanupRemovedSession: cleanupIOSSimulatorRemovedSession,closeIdleSessionForMove: async (sessionId) => {const maker = getMakerIfReady();if (maker?.getSession(sessionId)?.isTurnRunning()) return false;diff --cc apps/desktop/src/main/localDb/ipc/registerAll.tsindex 03e8336543,fc2c0e9320..f8cad91407--- a/apps/desktop/src/main/localDb/ipc/registerAll.ts+++ b/apps/desktop/src/main/localDb/ipc/registerAll.ts@@@ -16,9 -18,6 +18,7 @@@ import { getCurrentDbClientUserId, tryGimport {registerSessionIpc,type RegisterSessionIpcOpts,- setSessionRemovalCancelOperations,- setSessionRemovalCleanup,+ setSessionWorktreeBindingLookup,setSessionWorktreeRecycle,} from './sessions';import { registerMessageIpc } from './messages';@@@ -87,18 -88,10 +89,12 @@@ export interface RegisterLocalDbIpcOptdiscardStaleOwner?: (userId: string) => void | Promise<void>;/** ensureReady 打开/创建目标库前执行;失败时阻断,避免跳过认领后创建空库。 */beforeEnsureReady?: (userId: string) => void | Promise<void>;- /** Stop Host-owned session operations before an archived/deleted worktree is recycled. */- cancelSessionOperations?: (sessionId: string) => Promise<void>;- /** Release Host-owned runtime and ownership after task removal is revalidated. */- cleanupRemovedSession?: (sessionId: string) => Promise<void>;/** Record worktree recycle intent before a terminal session status is persisted. */requestWorktreeRecycle?: (sessionId: string, resources?: readonly string[]) => Promise<void>;+ /** 当前 worktree 绑定(worktreeStore 是 source of truth,DB 只存反范式快照)。 */+ lookupSessionWorktreeBinding?: (sessionId: string) => string | null;/** Close a moved local Pi/Codex runtime after revalidating that its turn is idle. */closeIdleSessionForMove?: (sessionId: string) => Promise<boolean>;- /** Reconcile persisted Host-owned task runtimes once the owner DB is readable. */- reconcilePersistedSessionRuntimes?: () => Promise<void>;/** Serialize startup tombstone cleanup with task restore/start/send operations. */withSessionLock?: <T>(sessionId: string, task: () => Promise<T>) => Promise<T>;/**@@@ -121,10 -114,7 +117,8 @@@}export function registerLocalDbIpc(opts: RegisterLocalDbIpcOpts = {}): void {- setSessionRemovalCancelOperations(opts.cancelSessionOperations ?? null);- setSessionRemovalCleanup(opts.cleanupRemovedSession ?? null);setSessionWorktreeRecycle(opts.requestWorktreeRecycle ?? null);+ setSessionWorktreeBindingLookup(opts.lookupSessionWorktreeBinding ?? null);setSessionRouteLockImplementation(opts.withSessionLock ?? null);const runEnsureReady = createOwnerEnsureCoordinator({isOwnerCurrent: opts.isOwnerCurrent ?? (() => true),diff --cc apps/desktop/src/main/localDb/ipc/sessions.tsindex 5c4b4dc4e0,4c3356a420..cd25acc46f--- a/apps/desktop/src/main/localDb/ipc/sessions.ts+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts@@@ -164,40 -158,8 +163,22 @@@ export interface RegisterSessionIpcOpt/** Close a local Pi/Codex runtime only if its current turn is idle. */closeIdleSessionForMove?: (sessionId: string) => Promise<boolean>;}-- let sessionRemovalCancelOperations: SessionRemovalCancelOperations | null = null;- let sessionRemovalCleanup: SessionRemovalCleanup | null = null;let sessionWorktreeRecycle: SessionWorktreeRecycle | null = null;+/**+ * 会话当前 worktree 绑定的查询口。source of truth 是 worktreeStore(electron-store):+ * `sessions.worktree_path` 只是反范式快照,且回收后刻意保留历史值(徽标看 store+ * 是否存在),所以不能用它当「是否仍持有 worktree」的判据。+ */+type SessionWorktreeBindingLookup = (sessionId: string) => string | null;+let sessionWorktreeBindingLookup: SessionWorktreeBindingLookup | null = null;++/** Composition-root injection keeps the localDb IPC layer independent of worktree implementation modules. */+export function setSessionWorktreeBindingLookup(+ lookup: SessionWorktreeBindingLookup | null,+): void {+ sessionWorktreeBindingLookup = lookup;+}-- /** Composition-root injection for Host-owned operations that must stop before worktree recycle. */- export function setSessionRemovalCancelOperations(- cancelOperations: SessionRemovalCancelOperations | null,- ): void {- sessionRemovalCancelOperations = cancelOperations;- }-- /** Composition-root injection for destructive cleanup after removal is revalidated. */- export function setSessionRemovalCleanup(- cleanupRemovedSession: SessionRemovalCleanup | null,- ): void {- sessionRemovalCleanup = cleanupRemovedSession;- }-/** Composition-root injection keeps the localDb IPC layer independent of worktree implementation modules. */export function setSessionWorktreeRecycle(recycle: SessionWorktreeRecycle | null): void {sessionWorktreeRecycle = recycle;diff --cc apps/desktop/src/main/maker-host/__tests__/codexPickerHarness.tsindex 0000000000,b8e4e806bf..d0f44a0494mode 000000,100644..100644--- a/apps/desktop/src/main/maker-host/__tests__/codexPickerHarness.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexPickerHarness.ts@@@ -1,0 -1,137 +1,138 @@@+ import fs from 'node:fs';+ import path from 'node:path';+ import vm from 'node:vm';+ import ts from 'typescript';+ import { eq } from 'drizzle-orm';+ import type { Maker } from '../../../../../../packages/maker-core/src/maker.js';+ import type { DbClient } from '../../localDb/client/DbClient.js';+ import { sessions } from '../../localDb/schema.js';+ import * as providers from '../session-provider-store.js';+ import * as efforts from '../session-effort-store.js';+ import * as routeGuard from '../model-route-guard.js';+ import * as control from '../../maker-ipc/sessionRuntimeControl.js';+ import * as axes from '../../maker-ipc/runtimeSelectionAxes.js';+ import * as relink from '../../maker-ipc/codexProviderThreadRelink.js';+ import * as windowGate from '../../../shared/runtimeModelSwitchGate.js';+ import * as overflow from '../../maker-ipc/contextOverflowRollover.js';+ import { applyRuntimeSetModelChange } from '../../maker-ipc/runtimeSetModel.js';+ import { normalizeDeviceLinkSetModelWireArgs } from '../../maker-ipc/setModelWireArgs.js';+ import { CredentialModeSwitchBusyError } from '../codex-credential-switch.js';+ import { createPendingAgentSwitchRegistry, applyPendingAgentSwitchIfIdle, projectPendingAgentSwitchIntent, type MakerSessionAgentSwitchHandlerDeps } from '../../maker-ipc/sessionAgentSwitchHandler.js';+ import { registerSessionSetModelHandler } from '../../maker-ipc/sessionSetModelHandler.js';+ import { registerMakerSessionSendHandler } from '../../maker-ipc/sessionSendHandler.js';+ import { createMakerSendTransaction, type MakerSendTransactionDeps } from '../../maker-ipc/makerSendTransaction.js';+ import { acquireSendToSessionLock, withSendToSessionLock } from '../../maker-ipc/sendToSessionLock.js';+ import type { IpcHandler } from '../../maker-ipc/ipcHandlerRegistry.js';+ import { MAKER_INVOKE } from '../../maker-ipc/channels.js';+ import { createSharedTaskSettingGuard } from '../../maker-ipc/sharedTaskSetting.js';++ // Execute the full production closures, not copied branches or source assertions.+ // Electron ingress, owner, catalog metadata and UI broadcasts are fixture inputs;+ // pending selection, runtime replacement, native fork and SQLite CAS stay real.+ const source = fs.readFileSync(path.resolve(__dirname, '../../maker-ipc/register.ts'), 'utf8');+ const ast = ts.createSourceFile('register.ts', source, ts.ScriptTarget.Latest, true);+ function closure(name: string): string {+ let expression: ts.Expression | undefined;+ const visit = (node: ts.Node) => {+ if (ts.isVariableDeclaration(node) && node.name.getText(ast) === name) expression = node.initializer;+ if (ts.isPropertyAssignment(node) && node.name.getText(ast) === name && ts.isArrowFunction(node.initializer)) expression = node.initializer;+ if (ts.isBinaryExpression(node) && node.left.getText(ast) === name && ts.isArrowFunction(node.right)) expression = node.right;+ ts.forEachChild(node, visit);+ };+ visit(ast);+ if (!expression) throw new Error(`Missing production closure ${name}`);+ return ts.transpileModule(`(${expression.getText(ast)})`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;+ }++ export function createCodexPickerHarness(input: {+ maker: Maker;+ db: Pick<DbClient, 'drizzle'>;+ workingDir: string;+ createMessage(id: string, message: { clientId: string; content: unknown }): Promise<unknown>;+ }) {+ const { maker, db, workingDir } = input;+ const pending = createPendingAgentSwitchRegistry();+ const noop = () => {};+ const asyncNoop = async () => {};+ const log = { info: noop, warn: noop, debug: noop, error: noop };+ const readRow = async (id: string) => (await db.drizzle.select().from(sessions).where(eq(sessions.id, id)).limit(1))[0];+ const bootstrap = async (id: string) => {+ const row = await readRow(id);+ return maker.createSession({ id, agentKind: 'codex', model: row.model!, providerId: row.providerId,+ resumeSessionId: row.sdkSessionId ?? undefined, workingDir });+ };+ const env: Record<string, unknown> = {+ ...providers, ...efforts, ...routeGuard, ...control, ...axes, ...relink, ...windowGate, ...overflow,+ maker, sessions, eq, log, agentSwitchPending: pending,+ // Ordinary local picker has no shared-task invocation context.+ captureSharedTaskSettingGuard: (id: string) => createSharedTaskSettingGuard(undefined, id, { admitted: false }),+ normalizeDeviceLinkSetModelWireArgs, applyRuntimeSetModelChange, CredentialModeSwitchBusyError,+ projectPendingAgentSwitchIntent, acquireSendToSessionLock, withSendToSessionLock, applyPendingAgentSwitchIfIdle,+ getDbClient: () => db, getCurrentDbClientSnapshot: () => ({ client: db, clientEpoch: 1 }),+ captureDataOwnerBroadcastScope: () => 'synthetic-owner', isDataOwnerBroadcastScopeCurrent: () => true,+ assertReviewSettingsUnlocked: asyncNoop, isDeviceLinkInvoke: () => false,+ deviceLinkInvokeControllerSupports: () => false, CONTROLLER_CAPABILITY_SET_MODEL_EXPLICIT_PROVIDER_NULL_V1: 'fixture',+ throwIpcError: (code: string, message: string) => { throw new Error(`${code}: ${message}`); },+ dbToMakerAgentKind: (kind: string) => kind, getSessionDbAgentKind: () => 'codex',+ assertModelRouteUsable: asyncNoop, shouldApplyExclusiveProviderRerouteLive: () => false,+ clearPendingCredentialSwitchForSession: noop, registerPendingCredentialSwitchForSession: noop,+ getPendingCredentialSwitchTarget: () => undefined, pendingCredentialSwitchHolder: null,+ wakeSessionInputAfterCredentialSwitch: noop, broadcastSessionPatched: noop,+ broadcastSessionRuntimeProjection: asyncNoop, recordSessionContextSnapshot: asyncNoop,+ isSessionInTurn: (id: string) => maker.getSession(id)?.isTurnRunning() ?? false,+ getCodexProxyAuthInjectionState: () => 'oauth-bearer',+ getActiveCatalog: () => ({}), resolveConfiguredContextWindow: () => 258400,+ getDesktopProviderService: () => ({ listProviders: async () => ['openai', 'xd', 'cprov-fixture'].map(id => ({ id, connected: true })) }),+ findCatalogModel: () => ({ id: 'fixture-model', efforts: ['high'], contextWindow: 258400, supportsFastMode: false }),+ reconcileBotModelRoute: asyncNoop, contextOverflowRolloverHolder: null,+ withRehydrateCloseSuppressed: async (_id: string, run: () => Promise<unknown>) => run(),+ persistSessionFields: async (id: string, patch: Partial<typeof sessions.$inferInsert>) => db.drizzle.update(sessions).set(patch).where(eq(sessions.id, id)),+ };+ const context = vm.createContext(env);+ type Apply = (id: string, model: string, providerId: string | null | undefined, revision: unknown, selection: unknown, options: Record<string, unknown>) => Promise<{ deferred?: boolean; superseded?: boolean }>;+ const apply = vm.runInContext(closure('handleSetModel'), context) as Apply;+ env.applySessionRuntimeSelection = (id: string, model: string, providerId: string | null | undefined, selection: unknown, options: Record<string, unknown>) => apply(id, model, providerId, undefined, selection, options);+ const switchDeps = {+ pendingSwitches: pending, getLiveSession: (id: string) => maker.getSession(id),+ bootstrapSwitchedSession: bootstrap, log,+ selectSameAgentModel: vm.runInContext(closure('selectSameAgentModel'), context),+ } as unknown as MakerSessionAgentSwitchHandlerDeps;+ env.agentSwitchDeps = switchDeps;+ const beforeSend = vm.runInContext(closure('pendingAgentSwitchApplyHolder'), context) as (id: string) => Promise<{ release(): void }>;+ const transactionDeps: MakerSendTransactionDeps = {++ statDirectory: async () => ({ isDirectory: () => true }),+ getSession: id => maker.getSession(id), closeSession: id => maker.closeSession(id), getSessionMeta: id => maker.getSessionMeta(id),+ preflightBotRuntimeResources: asyncNoop, ensureRemoteReadyForSessionStart: asyncNoop,+ checkWorkDirExists: async () => true, readSessionWorkingDirFromDb: async () => workingDir,+ readWorkingDirectoryRecoveryCreateOpts: async id => {+ const row = await readRow(id);+ return { id, agentKind: 'codex', model: row.model ?? undefined, providerId: row.providerId,+ resumeSessionId: row.sdkSessionId ?? undefined, workingDir };+ },+ isOrcaMcpHydrated: () => true, buildCreateOptsWithStderr: opts => opts,+ synthesizeOrcaVendorOptionsFromDb: async () => false, readSessionExtraDirsFromDb: async () => [],+ withRehydrateCloseSuppressed: async (_id, run) => run(),+ bootstrapSession: async opts => ({ session: await bootstrap(opts.id!), didInjectOrcaInstructions: false, didInjectProjectContext: false }),+ markOrcaRoleIfNeeded: asyncNoop, broadcastSessionCreated: noop,+ prepareSendUserMessage: async (_id, message) => message as string,+ createDbMessage: input.createMessage, isSessionRunningError: () => false, log,+ };+ const transaction = createMakerSendTransaction(transactionDeps);+ const handlers = new Map<string, IpcHandler>();+ const registry = { handle: (channel: string, handler: IpcHandler) => { handlers.set(channel, handler); } };+ registerSessionSetModelHandler(registry, { isDeviceLinkInvoke: () => false, assertTrustedSender: noop,+ apply: (id, model, providerId, revision, selection) => apply(id as string, model as string, providerId as string, revision, selection, { source: 'user' }),+ });+ registerMakerSessionSendHandler(registry, { sendToAgentAccepted: async (id, message, opts, sendOpts) => {+ const lease = await beforeSend(id);+ try { return await transaction.sendToAgentAccepted(id, message, opts, sendOpts); }+ finally { lease.release(); }+ } });+ return {+ pending,+ pick: (id: string, providerId: string, model = 'fixture-model') => handlers.get(MAKER_INVOKE.SET_MODEL)!(null, id, model, providerId),+ send: (id: string, clientId: string) => handlers.get(MAKER_INVOKE.SEND)!(null, id, 'picker fixture',+ { id, agentKind: 'codex', model: 'fixture-model', workingDir },+ { messageUuid: clientId, persistUserMessage: { clientId, content: 'picker fixture' } }),+ };+ }diff --cc apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.tsindex 1f0c731cbc,22da21b745..e7c37d2c2d--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts@@@ -10962,6 -11576,65 +11576,66 @@@ describe('AgentInputCoordinator replace},);+ it('preserves typed plugin receipts from queue snapshot through durable persistence and review', async () => {+ const h = createHarness();+ const sid = 'plugin-empty-authorship';+ await h.coordinator.ensureQueueRestored(sid);+ h.setRunning(true);+ h.coordinator.enqueue(sid, { ...makeItem('plugin-input', 'Plugin task'), autoReviewUserText: { kind: 'delegated-continuation' } });+ await flush();+ const snapshot = JSON.parse(JSON.stringify(h.persistQueueSnapshot.mock.calls.at(-1)?.[1] ?? []));+ expect(snapshot[0]).toMatchObject({ autoReviewUserText: { kind: 'delegated-continuation' } });+ const restarted = createHarness();+ restarted.setLoadQueueSnapshot(async () => snapshot);+ await restarted.coordinator.ensureQueueRestored(sid);+ expect(restarted.coordinator.getQueueControlSnapshot(sid).pendingQueue[0]).toMatchObject({ autoReviewUserText: { kind: 'delegated-continuation' } });+ const history: AutoReviewHistoryMessage[] = [{clientId:'human',role:'user',createdAt:1,content:{text:'Do not modify files'},agentMeta:{delivery:'turn',autoReviewUserText:'Do not modify files'}}];+ const session: MakerSendTransactionSession = {+ id:sid,instanceId:'runtime',agentKind:'codex',workDir:'/answer',remoteHostId:null,isTurnRunning:()=>false,+ send:vi.fn(async (_message,opts)=>{await opts?.onAccepted?.();return {accepted:true as const};}),+ };+ const transaction=createMakerSendTransaction({++ statDirectory:async()=>({isDirectory:()=>true}),+ getSession:()=>session,closeSession:async()=>{},preflightBotRuntimeResources:async()=>{},+ getSessionMeta:async()=>({}),ensureRemoteReadyForSessionStart:async()=>{},checkWorkDirExists:async()=>true,+ isOrcaMcpHydrated:()=>true,buildCreateOptsWithStderr:x=>x,synthesizeOrcaVendorOptionsFromDb:async()=>false,+ readSessionExtraDirsFromDb:async()=>[],readSessionWorkingDirFromDb:async()=>'/answer',+ readWorkingDirectoryRecoveryCreateOpts:async()=>({agentKind:'codex',workingDir:'/answer',model:'m'}),+ withRehydrateCloseSuppressed:async(_id,fn)=>fn(),bootstrapSession:async()=>({session,didInjectOrcaInstructions:false,didInjectProjectContext:false}),+ markOrcaRoleIfNeeded:async()=>{},broadcastSessionCreated:()=>{},prepareSendUserMessage:async(_id,m)=>m as string,+ createDbMessage:async(_id,row)=>{history.push(JSON.parse(JSON.stringify({...row,createdAt:history.length+1})));},+ readAutoReviewHistory:async()=>history,isSessionRunningError:()=>false,log:{info:()=>{},warn:()=>{}},+ });+ restarted.sendToAgent.mockImplementation(async (...args)=>{+ const result=await transaction.sendToAgentAccepted(...args);+ expect(result.accepted).toBe(true);+ return sendSuccess();+ });+ restarted.coordinator.enqueue(sid, makeItem('resume-input', 'Continue'), { resumeRestorePausedQueue: true });+ await flush();+ expect(restarted.sendToAgent.mock.calls[0]?.[3][AUTO_REVIEW_SOURCE_CONTENT]).toBe('');+ expect(restarted.sendToAgent.mock.calls[0]?.[3][AUTO_REVIEW_DELEGATED_CONTINUATION]).toBe(true);+ await restarted.sendToAgent.mock.results[0]!.value;+ expect(history[1]?.agentMeta?.autoReviewUserText).toEqual({kind:'delegated-continuation'});+ const route={agentKind:'codex' as const,providerId:'p',model:'m',effort:'high',fastMode:false};+ const authority: PluginReviewSnapshot={pluginId:'test',authorized:true,revision:1,registeredRoute:route,+ session:{workingDir:'/answer',permissionMode:'auto',status:'active',route},lead:{permissionMode:'auto',status:'active'},+ plan:{task:'Inspect project',items:[],concurrency:null},history,sessionHistory:history,historyComplete:true};+ const resolve=createPluginTaskReviewResolver(async()=>authority);+ const live=vi.mocked(session.send).mock.calls[0]![1]![AUTO_REVIEW_USER_INTENT]!;+ for(const userIntent of [live,restoreAutoReviewUserIntent(history)]){+ const reviewed=await resolve({sessionId:sid,agentKind:'codex',model:'m',userIntent,workspaceRoots:['/answer'],platform:'linux',action:{kind:'exec',command:'ls',cwd:'/answer'}});+ expect(reviewed.authorizationError).toBeUndefined();expect(reviewed.userIntent).toBe('Do not modify files');expect(reviewed.delegatedTask).toBeDefined();+ }+ // Genuine human resource input, without the Main-only symbol, still resets old consent.+ await transaction.sendToAgentAccepted(sid,'New attachment',undefined,{+ [AUTO_REVIEW_SOURCE_CONTENT]:'',+ persistUserMessage:{clientId:'new-resource',content:JSON.stringify({text:'',files:[{name:'new.txt'}]}),delivery:'turn'},+ });+ expect(history.at(-1)?.agentMeta?.autoReviewUserText).toBe('');+ expect(restoreAutoReviewUserIntent(history)).toBe('');+ });+it('编辑保留主机接收时间,清空边界后的条目崩溃恢复时不会被误删', async () => {const h = createHarness();const sid = 'replace-after-clear';diff --cc apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsxindex 28ec646ab5,f983ad5ef9..c830ccfdc9--- a/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/SessionContentHeader.tsx@@@ -68,18 -68,11 +68,12 @@@ import { SessionRenameInput } from './Simport { useSessionBoundSchedules } from '@/features/scheduler/lib/scheduleSessionBinding';import { ScheduleBindingBadge } from './sidebar/ScheduleBindingBadge';import { RemoteProjectIcon } from './sidebar/RemoteProjectIcon';- import {- MENU_CONTENT_CLASS,- MENU_ITEM_CLASS,- MENU_ROW_CLASS,- MENU_SEPARATOR_CLASS,- MENU_SUB_CONTENT_CLASS,- } from './sidebar/menuStyles';+ import { VendorIcon, agentKindToVendor } from '@/components/sidebar/VendorIcon';+ import { MENU_ITEM_CLASS, MENU_ROW_CLASS } from './sidebar/menuStyles';import { SessionProjectMoveSubmenu } from './sidebar/SessionProjectMoveSubmenu';+import { sessionMoveFailureFeedback } from '../../../shared/worktreeMoveGuardError';import type { SessionMoveTarget } from './sidebar/sessionMoveTarget';import { SessionShareExportDialog } from './sidebar/SessionShareExportDialog';- import { SessionBranchTreeDialog } from './SessionBranchTreeDialog';import { useRemoteProjectSessions } from '@/features/device-link/remoteProjectsStore';import { isRemoteSessionWriteBlocked } from './lib/remoteSessionWriteGuard';import { Tip } from '@/components/ui/tooltip';@@@ -148,11 -187,11 +188,13 @@@ export function SessionContentHeader(// 会停留在旧值(Codex review P2)。prop 兜底覆盖 archived 等不在// active 桶里的会话。const session = routeSessionById.get(sessionProp.id) ?? sessionProp;+ const sharedGuest = isSharedTaskPeer(session.deviceLinkDeviceId ?? '');const { runningSessionIds } = useSessionRunningStatus(session.id);+ // worktree 归属取 store 镜像(与 main 的 worktreeStore 同源):回收后仍留历史路径、+ // 或存量半移动行的会话,不能靠 cwd 猜归属。const { confirm: confirmDialog } = useConfirmDialog();- const { runSessionAction, unarchiveSession } = useSessionLifecycleActions();+ const { runSessionAction, unarchiveSession, beginRemoteArchive, cancelRemoteArchive } =+ useSessionLifecycleActions();const isPinned = session.pinnedAt != null;const isArchived = session.status === 'archived';