Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(coding): clean up app-created worktrees when their topic is archived or trashed (#23241)

Bryanefa59cbeed62
diff --git a/apps/cli/src/commands/connect.test.ts b/apps/cli/src/commands/connect.test.ts
index e973b33d2b3..ec608b15538 100644
--- a/apps/cli/src/commands/connect.test.ts
+++ b/apps/cli/src/commands/connect.test.ts
@@ -105,8 +105,14 @@ const getGlobalConfig = vi.hoisted(() => vi.fn());
const createPublicLambdaClientMock = vi.hoisted(() =>
vi.fn(() => ({ config: { getGlobalConfig: { query: getGlobalConfig } } })),
);
+// Worktree cleanups that waited for this device, drained on every connect.
+const drainWorktreeCleanups = vi.hoisted(() => vi.fn(async () => ({ scheduled: true })));
+const createLambdaClientMock = vi.hoisted(() =>
+ vi.fn(() => ({ device: { drainWorktreeCleanups: { mutate: drainWorktreeCleanups } } })),
+);
vi.mock('../api/client', async (importOriginal) => ({
...(await importOriginal<typeof ApiClientModule>()),
+ createLambdaClient: createLambdaClientMock,
createPublicLambdaClient: createPublicLambdaClientMock,
}));
@@ -266,6 +272,19 @@ describe('connect command', () => {
);
});
+ it('asks the server to run the worktree cleanups waiting on this device on each connect', async () => {
+ drainWorktreeCleanups.mockClear();
+ const program = createProgram();
+ await program.parseAsync(['node', 'test', 'connect']);
+ expect(drainWorktreeCleanups).not.toHaveBeenCalled();
+
+ clientEventHandlers.connected?.();
+ clientEventHandlers.connected?.();
+
+ expect(drainWorktreeCleanups).toHaveBeenCalledTimes(2);
+ expect(drainWorktreeCleanups).toHaveBeenLastCalledWith({ deviceId: 'mock-device-id' });
+ });
+
it('should persist deviceId in status for daemon child connections', async () => {
const program = createProgram();
await program.parseAsync(['node', 'test', 'connect', '--daemon-child']);
@@ -500,6 +519,28 @@ describe('connect command', () => {
});
});
+ it('drains the worktree cleanups of a workspace share in its own workspace', async () => {
+ vi.mocked(resolveToken).mockResolvedValue({ ...OFFICIAL_AUTH, serverUrl: SELF_HOSTED });
+ getGlobalConfig.mockResolvedValue({
+ serverConfig: { deviceGatewayUrl: 'https://gw.example.com' },
+ });
+ await connect();
+ await clientEventHandlers['rpc_request']?.({
+ method: 'enrollWorkspace',
+ params: { token: 'ws-token', workspaceId: 'ws-1' },
+ requestId: 'rpc-1',
+ type: 'rpc_request',
+ });
+ createLambdaClientMock.mockClear();
+ drainWorktreeCleanups.mockClear();
+
+ // `clientEventHandlers` now belongs to the share connection.
+ clientEventHandlers.connected?.();
+
+ expect(createLambdaClientMock).toHaveBeenCalledWith(expect.anything(), 'ws-1');
+ expect(drainWorktreeCleanups).toHaveBeenCalledWith({ deviceId: 'mock-device-id' });
+ });
+
it('passes --gateway through to the daemon child, which resolves the same way', async () => {
await connect('--daemon', '--gateway', 'https://gateway.example.com');
diff --git a/apps/cli/src/commands/connect/index.ts b/apps/cli/src/commands/connect/index.ts
index dbd1a73bb11..888a58e555d 100644
--- a/apps/cli/src/commands/connect/index.ts
+++ b/apps/cli/src/commands/connect/index.ts
@@ -688,6 +688,13 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
managedAuthRetried = false;
updateStatus('connected');
void metricsSampler?.flush();
+ // Back online: the server runs the worktree cleanups that waited for this
+ // device (topics archived or trashed while it was offline) over the gateway.
+ const connectedDeviceId = client.currentDeviceId;
+ if (connectedDeviceId)
+ void createLambdaClient(auth, managed ? managedWorkspaceId : workspaceId)
+ .device.drainWorktreeCleanups.mutate({ deviceId: connectedDeviceId })
+ .catch((err) => info(`Worktree cleanup drain failed: ${(err as Error).message}`));
// A (re)connection reprobes so an upgraded or downgraded Codex is reported, and
// warms the cache before the gateway's first system_info_request.
nativeRuntimes.invalidate();
@@ -748,6 +755,16 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
});
bindGatewayClientHandlers(wsClient, handlerContext, wsId);
+ // The share has its own device id: drain what waited for it, in its workspace.
+ wsClient.on('connected', () => {
+ const shareDeviceId = wsClient.currentDeviceId;
+ if (shareDeviceId)
+ void createLambdaClient(auth, wsId)
+ .device.drainWorktreeCleanups.mutate({ deviceId: shareDeviceId })
+ .catch((err) =>
+ info(`Worktree cleanup drain failed (${wsId}): ${(err as Error).message}`),
+ );
+ });
const entry: WorkspaceShareConnection = { cancelRefresh: null, client: wsClient };
diff --git a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
index 1a4aa487c9c..b0efbdf1068 100644
--- a/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
+++ b/apps/desktop/src/main/controllers/GatewayConnectionCtr.ts
@@ -39,6 +39,12 @@ import { setDesktopUserAgentHeader } from '@/utils/user-agent';
import BrowserControlCtr from './BrowserControlCtr';
import { executeGatewayAgentRun, type PlatformTaskEntry } from './gatewayAgentRun';
import { createDesktopDeviceControlDeps } from './gatewayDeviceControlDeps';
+import {
+ type AgentNotifyParams,
+ postAgentNotify,
+ postDeviceRegistration,
+ requestWorktreeCleanupDrain,
+} from './gatewayDeviceServerCalls';
import HeterogeneousAgentCtr from './HeterogeneousAgentCtr';
import { ControllerModule, createProtocolHandler, IpcMethod } from './index';
import LocalFileCtr from './LocalFileCtr';
@@ -223,7 +229,13 @@ export default class GatewayConnectionCtr extends ControllerModule {
srv.setRpcHandler((method, params) => this.executeDeviceRpc(method, params));
// Wire up device registrar (persists this device to the server registry)
- srv.setDeviceRegistrar((info, auth) => this.registerDevice(info, auth));
+ srv.setDeviceRegistrar((info, auth) => postDeviceRegistration(info, auth));
+
+ // Back online: the server runs the worktree cleanups that waited for this
+ // device (topics archived or trashed while it was offline).
+ srv.setConnectedHandler(({ deviceId, workspaceId }) =>
+ this.drainWorktreeCleanups(deviceId, workspaceId),
+ );
// Wire up the workspace-share hooks: connect-token minting (startup restore
// + token expiry) and the "row still registered?" probe that keeps a share
@@ -1187,76 +1199,33 @@ export default class GatewayConnectionCtr extends ControllerModule {
/**
* Send a notify message to the server so the frontend receives agent output or
- * a completion signal. Uses the tRPC agentNotify.notify endpoint directly —
- * this is the desktop counterpart to `lh notify` used by the CLI path.
+ * a completion signal — the desktop counterpart to `lh notify` used by the CLI path.
*/
- private async sendNotify(params: {
- agentId?: string;
- cancelled?: boolean;
- content: string;
- done?: boolean;
- error?: { message: string; type?: string };
- operationId?: string;
- role: string;
- topicId: string;
- /**
- * Workspace scope for the notify. When set, attaches `X-Workspace-Id` so
- * agentNotify resolves the workspace-owned topic instead of falling back
- * to personal mode (which would 404 the lookup).
- */
- workspaceId?: string;
- }): Promise<void> {
+ private async sendNotify(params: AgentNotifyParams): Promise<void> {
try {
const [serverUrl, token] = await Promise.all([
this.remoteServerConfigCtr.getRemoteServerUrl(),
this.remoteServerConfigCtr.getAccessToken(),
]);
if (!serverUrl || !token) return;
-
- const { workspaceId, ...body } = params;
- const headers: Record<string, string> = {
- 'Content-Type': 'application/json',
- 'Oidc-Auth': token,
- };
- if (workspaceId) headers['X-Workspace-Id'] = workspaceId;
- setDesktopUserAgentHeader(headers);
-
- await fetch(`${serverUrl}/trpc/lambda/agentNotify.notify`, {
- body: JSON.stringify({ json: body }),
- headers,
- method: 'POST',
- });
+ await postAgentNotify(params, { serverUrl, token });
} catch {
// Fire-and-forget: openclaw's own `lh notify` calls are the primary channel.
}
}
/**
- * Persist this device to the server registry via `device.register`.
- * Fire-and-forget from the connect path: a failure must not block the WS
- * connection, the device just won't appear in the offline list until the
- * next successful connect.
+ * Ask the server to run the worktree cleanups waiting on this device (topics
+ * archived or trashed while it was offline). Best-effort: anything missed
+ * waits for the next connect, or for the renderer's drain on startup.
*/
- private async registerDevice(
- info: {
- deviceId: string;
- hostname: string;
- identitySource: string;
- platform: string;
- },
- { serverUrl, token }: { serverUrl: string; token: string },
- ): Promise<void> {
- const headers: Record<string, string> = {
- 'Content-Type': 'application/json',
- 'Oidc-Auth': token,
- };
- setDesktopUserAgentHeader(headers);
-
- await fetch(`${serverUrl}/trpc/lambda/device.register`, {
- body: JSON.stringify({ json: info }),
- headers,
- method: 'POST',
- });
+ private async drainWorktreeCleanups(deviceId: string, workspaceId?: string): Promise<void> {
+ const [serverUrl, token] = await Promise.all([
+ this.remoteServerConfigCtr.getRemoteServerUrl(),
+ this.remoteServerConfigCtr.getAccessToken(),
+ ]);
+ if (serverUrl && token)
+ await requestWorktreeCleanupDrain({ deviceId, workspaceId }, { serverUrl, token });
}
/**
diff --git a/apps/desktop/src/main/controllers/GitCtr.ts b/apps/desktop/src/main/controllers/GitCtr.ts
index fcc2b589125..7525925a80b 100644
--- a/apps/desktop/src/main/controllers/GitCtr.ts
+++ b/apps/desktop/src/main/controllers/GitCtr.ts
@@ -9,6 +9,8 @@ import type {
GitDeleteBranchResult,
GitFileRevertResult,
GitLinkedPullRequestResult,
+ GitOwnedWorktreeCleanupResult,
+ GitOwnedWorktreeRestoreResult,
GitPullRequestAction,
GitPullRequestActionResult,
GitPullRequestActivity,
@@ -203,6 +205,7 @@ export default class GitController extends ControllerModule {
@IpcMethod()
async addGitWorktree(payload: {
branch: string;
+ ownerToken?: string;
path: string;
startPoint?: string;
worktreePath: string;
@@ -211,6 +214,41 @@ export default class GitController extends ControllerModule {
return runAddGitWorktree(payload);
}
+ /**
+ * Remove a worktree the app created for a conversation (archived or trashed),
+ * or with `discard` the one the user chose to drop with its changes. The
+ * guards run in `local-file-shell`; the root is this machine's own.
+ */
+ @IpcMethod()
+ async cleanupOwnedWorktree(payload: {
+ discard?: boolean;
+ ownerToken?: string;
+ sourcePath: string;
+ worktreePath: string;
+ }): Promise<GitOwnedWorktreeCleanupResult> {
+ const { cleanupOwnedWorktree } = await loadGit();
+ const { discard, ownerToken, sourcePath, worktreePath } = payload;
+ return cleanupOwnedWorktree({
+ discard: discard === true,
+ ownerToken,
+ sourcePath,
+ worktreePath,
+ });
+ }
+
+ /** Check a cleaned-up worktree out again at its path, for a restored conversation. */
+ @IpcMethod()
+ async restoreOwnedWorktree(payload: {
+ branch: string;
+ ownerToken?: string;
+ sourcePath: string;
+ worktreePath: string;
+ }): Promise<GitOwnedWorktreeRestoreResult> {
+ const { restoreOwnedWorktree } = await loadGit();
+ const { branch, ownerToken, sourcePath, worktreePath } = payload;
+ return restoreOwnedWorktree({ branch, ownerToken, sourcePath, worktreePath });
+ }
+
@IpcMethod()
async pullGitBranch(payload: { branch?: string; path: string }): Promise<GitPullResult> {
const { pullGitBranch: runPullGitBranch } = await loadGit();
diff --git a/apps/desktop/src/main/controllers/__tests__/controllerDefaultExport.test.ts b/apps/desktop/src/main/controllers/__tests__/controllerDefaultExport.test.ts
index 8d6e8031c1d..b201359662e 100644
--- a/apps/desktop/src/main/controllers/__tests__/controllerDefaultExport.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/controllerDefaultExport.test.ts
@@ -19,6 +19,26 @@ describe('controller default exports', () => {
});
});
+describe('controller discovery', () => {
+ // `App` loads controllers with this same flat glob; a controller turned into
+ // a `FooCtr/index.ts` directory is silently never registered (its IPC calls
+ // fail with "No handler registered"). Keep controllers as `*Ctr.ts` files and
+ // put extracted helpers beside them.
+ it('every registered controller is a module App.importAll discovers', () => {
+ const discovered = new Set(Object.values(controllerModules).map((mod) => mod.default));
+ for (const Ctor of controllerIpcConstructors) {
+ expect(discovered.has(Ctor), Ctor.groupName).toBe(true);
+ }
+ });
+
+ it('no service is a directory the *Srv.ts glob would skip', () => {
+ const services = import.meta.glob('../../services/*Srv.ts');
+ const nested = import.meta.glob('../../services/*Srv/index.ts');
+ expect(Object.keys(services).length).toBeGreaterThan(0);
+ expect(Object.keys(nested)).toEqual([]);
+ });
+});
+
describe('controllerIpcConstructors', () => {
it('registers HeteroSessionCtr with unique non-empty group names', () => {
expect(controllerIpcConstructors).toContain(HeteroSessionCtr);
diff --git a/apps/desktop/src/main/controllers/gatewayDeviceServerCalls.ts b/apps/desktop/src/main/controllers/gatewayDeviceServerCalls.ts
new file mode 100644
index 00000000000..4d3bc321ee7
--- /dev/null
+++ b/apps/desktop/src/main/controllers/gatewayDeviceServerCalls.ts
@@ -0,0 +1,86 @@
+import { setDesktopUserAgentHeader } from '@/utils/user-agent';
+
+/**
+ * The authed server calls the gateway connection makes on this device's
+ * behalf, over the desktop's own OIDC token (the device has no tRPC client).
+ */
+
+interface ServerAuth {
+ serverUrl: string;
+ token: string;
+}
+
+const authedHeaders = (token: string, workspaceId?: string): Record<string, string> => {
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/json',
+ 'Oidc-Auth': token,
+ };
+ if (workspaceId) headers['X-Workspace-Id'] = workspaceId;
+ setDesktopUserAgentHeader(headers);
+ return headers;
+};
+
+export interface AgentNotifyParams {
+ agentId?: string;
+ cancelled?: boolean;
+ content: string;
+ done?: boolean;
+ error?: { message: string; type?: string };
+ operationId?: string;
+ role: string;
+ topicId: string;
+ /**
+ * Workspace scope for the notify. When set, attaches `X-Workspace-Id` so
+ * agentNotify resolves the workspace-owned topic instead of falling back
+ * to personal mode (which would 404 the lookup).
+ */
+ workspaceId?: string;
+}
+
+/** Relay agent output or a completion signal through `agentNotify.notify`. */
+export const postAgentNotify = async (
+ { workspaceId, ...body }: AgentNotifyParams,
+ { serverUrl, token }: ServerAuth,
+): Promise<void> => {
+ await fetch(`${serverUrl}/trpc/lambda/agentNotify.notify`, {
+ body: JSON.stringify({ json: body }),
+ headers: authedHeaders(token, workspaceId),
+ method: 'POST',
+ });
+};
+
+/**
+ * Persist this device to the server registry via `device.register`.
+ * Fire-and-forget from the connect path: a failure must not block the WS
+ * connection, the device just won't appear in the offline list until the
+ * next successful connect.
+ */
+export const postDeviceRegistration = async (
+ info: { deviceId: string; hostname: string; identitySource: string; platform: string },
+ { serverUrl, token }: ServerAuth,
+): Promise<void> => {
+ await fetch(`${serverUrl}/trpc/lambda/device.register`, {
+ body: JSON.stringify({ json: info }),
+ headers: authedHeaders(token),
+ method: 'POST',
+ });
+};
+
+/**
+ * Ask the server to run the worktree cleanups waiting on this device. It
+ * calls back over the gateway (`cleanupOwnedWorktree`) after answering, so
+ * this returns at once.
+ */
+export const requestWorktreeCleanupDrain = async (
+ { deviceId, workspaceId }: { deviceId: string; workspaceId?: string },
+ { serverUrl, token }: ServerAuth,
+): Promise<void> => {
+ const response = await fetch(`${serverUrl}/trpc/lambda/device.drainWorktreeCleanups`, {
+ body: JSON.stringify({ json: { deviceId } }),
+ // A share connection's cleanups live in its workspace.
+ headers: authedHeaders(token, workspaceId),
+ method: 'POST',
+ signal: AbortSignal.timeout(10_000),
+ });
+ if (!response.ok) throw new Error(`Worktree cleanup drain failed: HTTP ${response.status}`);
+};
diff --git a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts
index 2fa532cd711..c65df6dccc1 100644
--- a/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts
+++ b/apps/desktop/src/main/services/__tests__/gatewayConnectionSrv.test.ts
@@ -130,6 +130,43 @@ describe('GatewayConnectionService system_info_request', () => {
);
});
+ /** @example Topics archived while this device was offline get their worktrees cleaned on reconnect. */
+ it('runs the connected handler with the registered device id on every (re)connect', async () => {
+ vi.spyOn(service as any, 'syncPowerSaveBlocker').mockImplementation(() => {});
+ vi.spyOn(service as any, 'scheduleStatusBroadcast').mockImplementation(() => {});
+ const handler = vi.fn(async () => {});
+ service.setConnectedHandler(handler);
+
+ // Not registered yet (signed out): nothing to name the device by.
+ service['setStatus']('connected');
+ expect(handler).not.toHaveBeenCalled();
+
+ service['connectedDeviceId'] = 'device-1';
+ service['setStatus']('reconnecting');
+ service['setStatus']('connected');
+ service['setStatus']('reconnecting');
+ service['setStatus']('connected');
+ expect(handler).toHaveBeenCalledTimes(2);
+ expect(handler).toHaveBeenLastCalledWith({ deviceId: 'device-1' });
+ });
+
+ /** @example A workspace share connection drains the cleanups waiting on its own device id. */
+ it('runs the connected handler for a workspace share connection with its workspace', async () => {
+ const handler = vi.fn(async () => {});
+ service.setConnectedHandler(handler);
+ const listeners: Record<string, () => void> = {};
+ const shareClient = {
+ currentDeviceId: 'ws-device-1',
+ on: (event: string, listener: () => void) => {
+ listeners[event] = listener;
+ },
+ };
+ service['setupClientEvents'](shareClient as any, { workspaceId: 'ws-1' });
+
+ listeners.connected();
+ expect(handler).toHaveBeenCalledWith({ deviceId: 'ws-device-1', workspaceId: 'ws-1' });
+ });
+
/** @example Updating or removing Codex changes the capability after reconnecting. */
it('revokes native support when a reconnect probe fails', async () => {
getShellInfoMock.mockResolvedValue({ displayName: 'zsh' });
diff --git a/apps/desktop/src/main/services/gatewayConnectionHandlers.ts b/apps/desktop/src/main/services/gatewayConnectionHandlers.ts
new file mode 100644
index 00000000000..ff0e56d4f1b
--- /dev/null
+++ b/apps/desktop/src/main/services/gatewayConnectionHandlers.ts
@@ -0,0 +1,120 @@
+import type { AgentRunRequestMessage, GatewayMcpParams } from '@lobechat/device-gateway-client';
+import type { IdentitySource } from '@lobechat/device-identity';
+
+/**
+ * The contracts of the handlers `GatewayConnectionService` is wired with: the
+ * controller injects them, the service calls them as gateway traffic arrives.
+ */
+
+/**
+ * Result envelope a tool-call handler must return. Mirrors
+ * `BuiltinServerRuntimeOutput` so the renderer-side and remote-device paths
+ * stay symmetric: `content` is the LLM-facing prompt text; `state` carries the
+ * structured payload that downstream persists into `pluginState`.
+ */
+export interface ToolCallResult {
+ content: string;
+ error?: unknown;
+ state?: unknown;
+ success: boolean;
+}
+
+export interface MessageApiHandler {
+ (platform: string, apiName: string, payload: Record<string, unknown>): Promise<unknown>;
+}
+
+export interface ToolCallHandler {
+ (identifier: string | undefined, apiName: string, args: unknown): Promise<ToolCallResult>;
+}
+
+/**
+ * Handler for tunneled stdio MCP calls. Unlike {@link ToolCallHandler} (which
+ * keys on `apiName` for builtin local-system tools), this carries the MCP
+ * server identity + connection params so the device can spawn the local stdio
+ * server and invoke the tool on it.
+ */
+export interface McpCallHandler {
+ (mcpCall: {
+ apiName: string;
+ arguments: string;
+ identifier: string;
+ params: GatewayMcpParams;
+ }): Promise<ToolCallResult>;
+}
+
+/**
+ * Coerce a runtime error (which may be an Error, string, or `{ message }`
+ * object) into the string shape the wire protocol expects. Returns undefined
+ * when there's no error to transmit.
+ */
+export interface AgentRunHandler {
+ (request: AgentRunRequestMessage): Promise<{ reason?: string; status: 'accepted' | 'rejected' }>;
+}
+
+/**
+ * Handler for generic server-internal device RPCs (e.g. workspace-init scans).
+ * Dispatches by `method` name and returns the JSON-serializable result. Distinct
+ * from {@link ToolCallHandler} — RPCs are never exposed to the agent.
+ */
+export interface RpcHandler {
+ (method: string, params: unknown): Promise<unknown>;
+}
+
+/** The server + credential one connection attempt was resolved against. */
+export interface GatewayAuthContext {
+ serverUrl: string;
+ token: string;
+}
+
+/** Runs each time a connection comes up, with the device id it is connected as. */
+export interface ConnectedHandler {
+ /** `workspaceId`: a workspace share connection, identified by its own device id. */
+ (info: { deviceId: string; workspaceId?: string }): Promise<void>;
+}
+
+export interface DeviceRegistrar {
+ (
+ info: {
+ architecture: string;
+ deviceId: string;
+ hostname: string;
+ identitySource: IdentitySource;
+ metadata: Record<string, string>;
+ platform: string;
+ },
+ auth: GatewayAuthContext,
+ ): Promise<void>;
+}
+
+/**
+ * Mint a fresh workspace-device connect token for a share connection. Injected
+ * by the controller (which owns the authed server calls) — used when restoring
+ * persisted enrollments on startup and when a workspace connection's token
+ * expires. `serverUrl` is the server the personal connection belongs to: the
+ * provider returns null instead of minting on another server (signed out or
+ * switched meanwhile).
+ */
+export interface WorkspaceTokenProvider {
+ (workspaceId: string, serverUrl: string): Promise<string | null>;
+}
+
+/** What the server says about this machine's row in a workspace. */
+export interface WorkspaceDeviceRegistration {
+ /** The member who enrolled the row, when the server reports one. */
+ enrollerUserId?: string;
+ registered: boolean;
+}
+
+/**
+ * Check whether the workspace-scoped deviceId still has a registered row on
+ * `serverUrl`. `registered: false` is a definitive "row gone" answer (share
+ * revoked while offline); `undefined` means the check could not be performed —
+ * callers must NOT clear local state on `undefined`.
+ */
+export interface WorkspaceDeviceChecker {
+ (
+ workspaceId: string,
+ deviceId: string,
+ serverUrl: string,
+ ): Promise<WorkspaceDeviceRegistration | undefined>;
+}
diff --git a/apps/desktop/src/main/services/gatewayConnectionSrv.ts b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
index d272367ebd4..dae0c9b3e90 100644
--- a/apps/desktop/src/main/services/gatewayConnectionSrv.ts
+++ b/apps/desktop/src/main/services/gatewayConnectionSrv.ts
@@ -12,7 +12,6 @@ import type { DeviceMetricsSampler } from '@lobechat/device-control/metrics';
import type {
AgentRunRequestMessage,
GatewayClient,
- GatewayMcpParams,
MessageApiRequestMessage,
RpcRequestMessage,
SystemInfoRequestMessage,
@@ -43,11 +42,24 @@ import { createLogger } from '@/utils/logger';
import { getDesktopUserAgent } from '@/utils/user-agent';
import { safeGetPath } from '@/utils/user-path';
+import type {
+ AgentRunHandler,
+ ConnectedHandler,
+ DeviceRegistrar,
+ McpCallHandler,
+ MessageApiHandler,
+ RpcHandler,
+ ToolCallHandler,
+ WorkspaceDeviceChecker,
+ WorkspaceTokenProvider,
+} from './gatewayConnectionHandlers';
import { discoverDeviceGateway } from './gatewayDiscovery';
import { collectBundledCliAgentRuntimes, collectGatewaySystemInfo } from './gatewaySystemInfo';
import { prepareToolCallReply, serializeWireError, toWireResult } from './gatewayToolCallReply';
import { ServiceModule } from './index';
+export type { WorkspaceDeviceRegistration } from './gatewayConnectionHandlers';
+
const logger = createLogger('services:GatewayConnectionSrv');
/**
@@ -57,113 +69,6 @@ const logger = createLogger('services:GatewayConnectionSrv');
*/
const RECONNECT_UI_GRACE_MS = 5000;
-/**
- * Result envelope a tool-call handler must return. Mirrors
- * `BuiltinServerRuntimeOutput` so the renderer-side and remote-device paths
- * stay symmetric: `content` is the LLM-facing prompt text; `state` carries the
- * structured payload that downstream persists into `pluginState`.
- */
-interface ToolCallResult {
- content: string;
- error?: unknown;
- state?: unknown;
- success: boolean;
-}
-
-interface MessageApiHandler {
- (platform: string, apiName: string, payload: Record<string, unknown>): Promise<unknown>;
-}
-
-interface ToolCallHandler {
- (identifier: string | undefined, apiName: string, args: unknown): Promise<ToolCallResult>;
-}
-
-/**
- * Handler for tunneled stdio MCP calls. Unlike {@link ToolCallHandler} (which
- * keys on `apiName` for builtin local-system tools), this carries the MCP
- * server identity + connection params so the device can spawn the local stdio
- * server and invoke the tool on it.
- */
-interface McpCallHandler {
- (mcpCall: {
- apiName: string;
- arguments: string;
- identifier: string;
- params: GatewayMcpParams;
- }): Promise<ToolCallResult>;
-}
-
-/**
- * Coerce a runtime error (which may be an Error, string, or `{ message }`
- * object) into the string shape the wire protocol expects. Returns undefined
- * when there's no error to transmit.
- */
-interface AgentRunHandler {
- (request: AgentRunRequestMessage): Promise<{ reason?: string; status: 'accepted' | 'rejected' }>;
-}
-
-/**
- * Handler for generic server-internal device RPCs (e.g. workspace-init scans).
- * Dispatches by `method` name and returns the JSON-serializable result. Distinct
- * from {@link ToolCallHandler} — RPCs are never exposed to the agent.
- */
-interface RpcHandler {
- (method: string, params: unknown): Promise<unknown>;
-}
-
-/** The server + credential one connection attempt was resolved against. */
-interface GatewayAuthContext {
- serverUrl: string;
- token: string;
-}
-
-interface DeviceRegistrar {
- (
- info: {
- architecture: string;
- deviceId: string;
- hostname: string;
- identitySource: IdentitySource;
- metadata: Record<string, string>;
- platform: string;
- },
- auth: GatewayAuthContext,
- ): Promise<void>;
-}
-
-/**
- * Mint a fresh workspace-device connect token for a share connection. Injected
- * by the controller (which owns the authed server calls) — used when restoring
- * persisted enrollments on startup and when a workspace connection's token
- * expires. `serverUrl` is the server the personal connection belongs to: the
- * provider returns null instead of minting on another server (signed out or
- * switched meanwhile).
- */
-interface WorkspaceTokenProvider {
- (workspaceId: string, serverUrl: string): Promise<string | null>;
-}
-
-/** What the server says about this machine's row in a workspace. */
-export interface WorkspaceDeviceRegistration {
- /** The member who enrolled the row, when the server reports one. */
- enrollerUserId?: string;
- registered: boolean;
-}
-
-/**
- * Check whether the workspace-scoped deviceId still has a registered row on
- * `serverUrl`. `registered: false` is a definitive "row gone" answer (share
- * revoked while offline); `undefined` means the check could not be performed —
- * callers must NOT clear local state on `undefined`.
- */
-interface WorkspaceDeviceChecker {
- (
- workspaceId: string,
- deviceId: string,
- serverUrl: string,
- ): Promise<WorkspaceDeviceRegistration | undefined>;
-}
-
/**
* The context a personal connection was opened in. Workspace share connections
* reuse it, so every socket of one session talks to the same gateway on behalf
@@ -245,6 +150,9 @@ export default class GatewayConnectionService extends ServiceModule {
private agentRunHandler: AgentRunHandler | null = null;
private rpcHandler: RpcHandler | null = null;
private deviceRegistrar: DeviceRegistrar | null = null;
+ private connectedHandler: ConnectedHandler | null = null;
+ /** The device id the current personal connection registered as. */
+ private connectedDeviceId: string | null = null;
/** Samples CPU / memory / load for the personal device while the connection is on. */
private metricsSampler: { deviceId: string; sampler: DeviceMetricsSampler } | null = null;
private workspaceTokenProvider: WorkspaceTokenProvider | null = null;
@@ -356,6 +264,14 @@ export default class GatewayConnectionService extends ServiceModule {
this.deviceRegistrar = registrar;
}
+ /**
+ * Called each time the personal connection is (re)established — e.g. to run
+ * the work that waited for this device while it was offline.
+ */
+ setConnectedHandler(handler: ConnectedHandler) {
+ this.connectedHandler = handler;
+ }
+
/**
* Set the workspace connect-token minter used by share connections (startup
* restore + token expiry). Injected by the controller, which owns the authed
@@ -660,6 +576,7 @@ export default class GatewayConnectionService extends ServiceModule {
if (userId) {
const identity = await this.resolveDeviceIdentity(userId);
if (this.isStale(generation)) return CANCELLED;
+ this.connectedDeviceId = identity.deviceId;
await this.deviceRegistrar?.(
{
architecture: os.arch(),
@@ -785,6 +702,12 @@ export default class GatewayConnectionService extends ServiceModule {
// client's late success says nothing about the current one.
if (scope) {
this.workspaceAuthRetried.delete(client);
+ // A share connection has its own device id: drain what waited for it.
+ const deviceId = client.currentDeviceId;
+ if (deviceId)
+ void this.connectedHandler?.({ deviceId, workspaceId: scope.workspaceId }).catch(
+ (error) => logger.warn(`Connected handler failed: ${(error as Error).message}`),
+ );
} else if (this.client === client) {
this.authRecoveryAttempted = false;
}
@@ -1510,6 +1433,11 @@ export default class GatewayConnectionService extends ServiceModule {
// A (re)connection reprobes the bundled CLI and warms the cache for the first request.
this.agentRuntimes.invalidate();
void this.agentRuntimes.get();
+ const deviceId = this.connectedDeviceId;
+ if (deviceId)
+ void this.connectedHandler?.({ deviceId }).catch((error) => {
+ logger.warn(`Connected handler failed (non-fatal): ${(error as Error).message}`);
+ });
}
this.syncPowerSaveBlocker();
this.scheduleStatusBroadcast(status);
diff --git a/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.ts
index 9b3314fb692..0f2c8b40252 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/sessionAgentCompat.integration.test.ts
@@ -33,7 +33,10 @@ afterAll(() => vi.unstubAllEnvs());
let db: LobeChatDatabase;
vi.mock('@/database/core/db-adaptor', () => ({ getServerDB: vi.fn(() => db) }));
-vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after: vi.fn() }));
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({
+ after: vi.fn(),
+ afterUnscoped: vi.fn(),
+}));
vi.mock('@/server/services/file', () => ({
FileService: vi.fn(function () {
return { getFileAccessUrl: vi.fn(async () => 'mock-url') };
diff --git a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
index 4fd458e3783..50853c88608 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/topic.integration.test.ts
@@ -20,6 +20,8 @@ vi.mock('@/server/utils/scheduleAfterResponse', () => ({
after: vi.fn(function (callback: () => void) {
return callback();
}),
+ // Trash / archive hand the worktree cleanup to the host; nothing to run here.
+ afterUnscoped: vi.fn(),
}));
const legacyInboxTopic = (userId: string): typeof topics.$inferInsert => ({
diff --git a/apps/server/src/routers/lambda/device/git.ts b/apps/server/src/routers/lambda/device/git.ts
index 2e30a6dd0d6..07ae0f4896b 100644
--- a/apps/server/src/routers/lambda/device/git.ts
+++ b/apps/server/src/routers/lambda/device/git.ts
@@ -8,6 +8,8 @@ import { requireWorkspaceRoleWhenScoped } from '@/business/server/trpc-middlewar
import { TopicModel } from '@/database/models/topic';
import { router } from '@/libs/trpc/lambda';
import { deviceGateway } from '@/server/services/deviceGateway';
+import { WorktreeCleanupService } from '@/server/services/worktreeCleanup';
+import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';
import { assertWorkspaceRootApproved } from '../deviceWorkspaceGuard';
import { deviceProcedure } from './procedures';
@@ -30,6 +32,24 @@ const requireDeviceAnswer = <T>(result: T | undefined, what: string): T => {
};
export const gitRouter = router({
+ /**
+ * A device just connected to the gateway (desktop main process, `lh
+ * connect`): run the worktree cleanups that waited for it while it was
+ * offline. They run over the gateway after the response, so the device can
+ * call this from its `connected` handler and move on.
+ */
+ drainWorktreeCleanups: deviceProcedure
+ .input(z.object({ deviceId: z.string().min(1).max(64) }))
+ .mutation(async ({ ctx, input }) => {
+ const service = new WorktreeCleanupService(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ afterUnscoped(async () => {
+ const summary = await service.runPendingForDevice(input.deviceId);
+ if (Object.keys(summary.results).length > 0)
+ log('drained worktree cleanups for %s: %o', input.deviceId, summary.results);
+ });
+ return { scheduled: true };
+ }),
+
/**
* Granular git reads for a directory on a remote device, each via its own
* device RPC so the web/remote git status bar mirrors the local desktop's
@@ -312,6 +332,8 @@ export const gitRouter = router({
z.object({
branch: z.string(),
deviceId: z.string(),
+ /** Creation receipt for an app-created worktree (`ownedWorktrees`). */
+ ownerToken: z.string().max(128).optional(),
path: z.string(),
/** The repo's main checkout, which keys the folder; `path` may be a linked worktree. */
sourcePath: z.string().optional(),
@@ -344,6 +366,7 @@ export const gitRouter = router({
return deviceGateway.addGitWorktree({
branch: input.branch,
deviceId: input.deviceId,
+ ownerToken: input.ownerToken,
path: input.path,
startPoint: input.startPoint,
userId: ctx.userId,
diff --git a/apps/server/src/routers/lambda/device/index.procedures.test.ts b/apps/server/src/routers/lambda/device/index.procedures.test.ts
index df6c312b35f..42e707f3581 100644
--- a/apps/server/src/routers/lambda/device/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/device/index.procedures.test.ts
@@ -49,6 +49,7 @@ function expected(): Array<
['createTerminalSession', 'mutation', 12],
['createTunnel', 'mutation', 12],
['deleteGitBranch', 'mutation', 12],
+ ['drainWorktreeCleanups', 'mutation', 12],
['getAgentDeviceBindings', 'query', 12],
['getAgentProfile', 'query', 12],
['getAntigravityQuota', 'query', 12],
diff --git a/apps/server/src/routers/lambda/topic/index.procedures.test.ts b/apps/server/src/routers/lambda/topic/index.procedures.test.ts
index 3616a48f747..2b8cfe51fa4 100644
--- a/apps/server/src/routers/lambda/topic/index.procedures.test.ts
+++ b/apps/server/src/routers/lambda/topic/index.procedures.test.ts
@@ -33,10 +33,12 @@ function expected(): Array<
['batchMoveTopics', 'mutation', 13],
['branchTopicAtMessage', 'mutation', 13],
['cancelRateLimitContinuation', 'mutation', 13],
+ ['claimLocalWorktreeCleanups', 'mutation', 14],
['cloneTopic', 'mutation', 13],
['countTopics', 'query', 12],
['createTopic', 'mutation', 13],
['disableSharing', 'mutation', 13],
+ ['discardOwnedWorktree', 'mutation', 14],
['enableSharing', 'mutation', 13],
['forkTopic', 'mutation', 13],
['getHeteroSessionImportStatus', 'query', 11],
@@ -51,12 +53,16 @@ function expected(): Array<
['hasTopics', 'query', 11],
['importHeteroSessions', 'mutation', 13],
['importTopic', 'mutation', 13],
+ ['issueWorktreeReceipt', 'mutation', 13],
+ ['keepOwnedWorktree', 'mutation', 14],
['markTopicRead', 'mutation', 13],
['queryTopics', 'query', 12],
['rankTopics', 'query', 12],
['recentTopics', 'query', 12],
['removeAllTopics', 'mutation', 12],
['removeTopic', 'mutation', 13],
+ ['reportOwnedWorktreeCleanup', 'mutation', 14],
+ ['restoreOwnedWorktree', 'mutation', 14],
['searchTopics', 'query', 13],
['settleRunningOperation', 'mutation', 13],
['updateShareVisibility', 'mutation', 13],
diff --git a/apps/server/src/routers/lambda/topic/index.ts b/apps/server/src/routers/lambda/topic/index.ts
index 748e886424f..c36b2daa8bb 100644
--- a/apps/server/src/routers/lambda/topic/index.ts
+++ b/apps/server/src/routers/lambda/topic/index.ts
@@ -2,6 +2,7 @@ import { mergeRouters } from '@/libs/trpc/lambda';
import { createRouter } from './create';
import { operationReadRouter } from './operationReads';
+import { ownedWorktreeRouter } from './ownedWorktree';
import { queryRouter } from './queries';
import { removeRouter } from './remove';
import { shareRouter } from './share';
@@ -14,6 +15,7 @@ export const topicRouter = mergeRouters(
removeRouter,
shareRouter,
operationReadRouter,
+ ownedWorktreeRouter,
);
export type TopicRouter = typeof topicRouter;
diff --git a/apps/server/src/routers/lambda/topic/ownedWorktree.test.ts b/apps/server/src/routers/lambda/topic/ownedWorktree.test.ts
new file mode 100644
index 00000000000..efe57558e67
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/ownedWorktree.test.ts
@@ -0,0 +1,110 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { topics, workspaces } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import type { ChatTopicMetadata } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cleanupTestUser, createTestUser } from '../__tests__/integration/setup';
+
+// Opened once: a first PGlite boot inside a hook can outlast the hook timeout.
+const testDB: LobeChatDatabase = await getTestDB();
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+// General access to the agent has its own tests; this file covers who may act
+// on a topic's worktree and on which device.
+vi.mock('../_helpers/conversationResourceGuard', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ assertCanUseTopicTargets: vi.fn(async () => []),
+}));
+
+const discard = vi.hoisted(() => vi.fn(async () => ({ path: 'x' })));
+vi.mock('@/server/services/worktreeCleanup', () => ({
+ WorktreeCleanupService: class {
+ discard = discard;
+ },
+}));
+
+const { topicRouter } = await import('./index');
+
+const WT = '/Users/me/.lobehub/worktrees/repo-1a2b3c4d/quiet-hill';
+
+/**
+ * "Discard changes and delete" force-removes a worktree's uncommitted work, so
+ * in a workspace it stays the topic creator's call (or an owner's), and only on
+ * a device the caller may operate — the service dispatches to it directly.
+ */
+describe('topic.discardOwnedWorktree authorization', () => {
+ let creatorId: string;
+ let teammateId: string;
+ let workspaceId: string;
+
+ beforeEach(async () => {
+ creatorId = await createTestUser(testDB);
+ teammateId = await createTestUser(testDB);
+ const [workspace] = await testDB
+ .insert(workspaces)
+ .values({ name: 'Team', primaryOwnerId: creatorId, slug: `ws-owt-${creatorId}` })
+ .returning();
+ workspaceId = workspace.id;
+ });
+
+ afterEach(async () => {
+ discard.mockClear();
+ await cleanupTestUser(testDB, teammateId);
+ await cleanupTestUser(testDB, creatorId);
+ });
+
+ const seed = async (deviceId?: string) => {
+ const metadata: ChatTopicMetadata = {
+ ownedWorktrees: [
+ {
+ branch: 'lobehub/quiet-hill',
+ cleanup: { at: 'x', dirtyFiles: 2, state: 'keptDirty', trigger: 'archived' },
+ createdAt: 'y',
+ ...(deviceId && { deviceId }),
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ };
+ const [topic] = await testDB
+ .insert(topics)
+ .values({ metadata, status: 'completed', title: 't', userId: creatorId, workspaceId })
+ .returning();
+ return topic.id;
+ };
+
+ const caller = (userId: string, workspaceRole: 'member' | 'owner' = 'member') =>
+ topicRouter.createCaller({ userId, workspaceId, workspaceRole } as any);
+
+ it("refuses a teammate discarding the creator's worktree", async () => {
+ const topicId = await seed();
+ await expect(caller(teammateId).discardOwnedWorktree({ path: WT, topicId })).rejects.toThrow();
+ expect(discard).not.toHaveBeenCalled();
+ });
+
+ it('lets the creator discard it', async () => {
+ const topicId = await seed();
+ await caller(creatorId).discardOwnedWorktree({ path: WT, topicId });
+ expect(discard).toHaveBeenCalledWith(topicId, WT, { local: undefined });
+ });
+
+ it('refuses a desktop claiming the IPC jobs of a device that is not its own', async () => {
+ await expect(
+ caller(teammateId).claimLocalWorktreeCleanups({ deviceId: 'device-not-mine' }),
+ ).rejects.toThrow(/machine itself/i);
+ });
+
+ it('refuses a device the caller may not operate, even for the creator', async () => {
+ const topicId = await seed('device-not-in-this-workspace');
+ await expect(caller(creatorId).discardOwnedWorktree({ path: WT, topicId })).rejects.toThrow(
+ /device/i,
+ );
+ expect(discard).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/routers/lambda/topic/ownedWorktree.ts b/apps/server/src/routers/lambda/topic/ownedWorktree.ts
new file mode 100644
index 00000000000..a3611346659
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/ownedWorktree.ts
@@ -0,0 +1,224 @@
+import { resolveOwnedWorktrees } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
+import { type WorkspaceRole } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { DeviceModel } from '@/database/models/device';
+import type { TopicModel } from '@/database/models/topic';
+import type { LobeChatDatabase } from '@/database/type';
+import { router } from '@/libs/trpc/lambda';
+import { WorktreeCleanupService } from '@/server/services/worktreeCleanup';
+import { issueWorktreeReceipt } from '@/server/services/worktreeCleanup/receipt';
+
+import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
+import { assertCanUseTopicTargets } from '../_helpers/conversationResourceGuard';
+import { assertCreatorTopicTargets } from '../_helpers/shareVisitorTargetGuard';
+import { assertDeviceOperable } from '../device/guards';
+import { guardCtx, topicProcedure } from './procedures';
+
+/**
+ * The worktrees the app created for a topic (`metadata.ownedWorktrees`): the
+ * user's "Discard changes and delete" / "Keep" on a kept one, bringing one
+ * back for a restored topic, and the desktop's own IPC executions reporting
+ * in. Archive and trash start the automatic cleanup themselves.
+ */
+
+const target = z.object({ path: z.string().min(1), topicId: z.string() });
+
+const cleanupResultSchema = z.object({
+ branch: z.string().optional(),
+ dirtyFiles: z.number().int().nonnegative().optional(),
+ error: z.string().max(2000).optional(),
+ outcome: z.enum(['dirty', 'error', 'locked', 'refused', 'removed']),
+ unpushedSubmodules: z.number().int().nonnegative().optional(),
+});
+
+const restoreResultSchema = z.object({
+ error: z.string().max(2000).optional(),
+ outcome: z.enum(['branchMissing', 'error', 'refused', 'restored']),
+});
+
+const ownedWorktreeProcedure = topicProcedure
+ .use(withScopedPermission('topic:update'))
+ .use(async (opts) => {
+ const { ctx } = opts;
+ return opts.next({
+ ctx: {
+ worktreeCleanup: new WorktreeCleanupService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ),
+ },
+ });
+ });
+
+const assertTopic = async (ctx: Parameters<typeof guardCtx>[0], topicId: string) => {
+ await assertCanUseTopicTargets(guardCtx(ctx), [topicId]);
+ await assertCreatorTopicTargets(guardCtx(ctx), [topicId]);
+};
+
+interface OwnedWorktreeCtx {
+ serverDB: LobeChatDatabase;
+ topicModel: TopicModel;
+ userId: string;
+ workspaceId?: string | null;
+ workspaceRole?: WorkspaceRole;
+}
+
+/** The topic row (recycle bin included) and its record for `path`. */
+const loadOwnedWorktree = async (ctx: OwnedWorktreeCtx, topicId: string, path: string) => {
+ const [row] = await ctx.topicModel.findOwnedWorktreeTopics([topicId]);
+ const entry = resolveOwnedWorktrees(row?.metadata).find((item) => item.path === path);
+ if (!row || !entry) throw new TRPCError({ code: 'NOT_FOUND', message: 'Unknown worktree.' });
+ return { entry, row };
+};
+
+/**
+ * The device a worktree lives on must be one the caller may operate: the
+ * service dispatches to it directly, past `deviceProcedure`'s own guard.
+ */
+const assertWorktreeDevice = async (ctx: OwnedWorktreeCtx, deviceId: string | undefined) => {
+ if (!deviceId) return;
+ const workspaceId = ctx.workspaceId ?? undefined;
+ await assertDeviceOperable(
+ {
+ deviceModel: new DeviceModel(ctx.serverDB, ctx.userId, workspaceId),
+ userId: ctx.userId,
+ workspaceId,
+ workspaceRole: ctx.workspaceRole,
+ },
+ deviceId,
+ 'remove or restore a worktree',
+ );
+};
+
+/**
+ * Running cleanups over IPC is the job of the machine itself: in a workspace,
+ * only its enrolling member's desktop claims a device's jobs.
+ */
+const assertOwnDevice = async (ctx: OwnedWorktreeCtx, deviceId: string | undefined) => {
+ if (!deviceId || !ctx.workspaceId) return;
+ const device = await new DeviceModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId,
+ ).findWorkspaceDeviceById(deviceId);
+ if (device?.userId !== ctx.userId)
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Only the machine itself runs its worktree cleanups.',
+ });
+};
+
+/** Destructive or settling actions belong to the topic's creator (or a workspace owner). */
+const assertTopicCreator = (ctx: OwnedWorktreeCtx, topicUserId: string) =>
+ assertWorkspaceRowManageable(ctx, topicUserId, 'topic');
+
+export const ownedWorktreeRouter = router({
+ /**
+ * A creation receipt for the worktree the composer is about to create for a
+ * new topic: signed over the caller's user id, so only that user's topics
+ * can later present it to the device. `null` when the server has no secret
+ * to sign with (the worktree then has no receipt: never discarded by force).
+ */
+ issueWorktreeReceipt: ownedWorktreeProcedure.mutation(
+ async ({ ctx }) => issueWorktreeReceipt(ctx.userId) ?? null,
+ ),
+
+ /**
+ * Discard a kept worktree's changes and delete it — the topic creator's
+ * call, on a device they may operate. `local`: the desktop runs it over IPC,
+ * so only the claim is taken here and the result arrives with
+ * `reportOwnedWorktreeCleanup`.
+ */
+ discardOwnedWorktree: ownedWorktreeProcedure
+ .input(target.extend({ local: z.boolean().optional() }))
+ .mutation(async ({ ctx, input }) => {
+ await assertTopic(ctx, input.topicId);
+ const { entry, row } = await loadOwnedWorktree(ctx, input.topicId, input.path);
+ assertTopicCreator(ctx, row.userId);
+ await assertWorktreeDevice(ctx, entry.deviceId);
+ return (
+ (await ctx.worktreeCleanup.discard(input.topicId, input.path, { local: input.local })) ??
+ null
+ );
+ }),
+
+ keepOwnedWorktree: ownedWorktreeProcedure.input(target).mutation(async ({ ctx, input }) => {
+ await assertTopic(ctx, input.topicId);
+ const { row } = await loadOwnedWorktree(ctx, input.topicId, input.path);
+ assertTopicCreator(ctx, row.userId);
+ return (await ctx.worktreeCleanup.keep(input.topicId, input.path)) ?? null;
+ }),
+
+ /**
+ * The desktop takes the cleanups that wait on it (its own device id with the
+ * gateway off, or records without a device) to run over IPC.
+ */
+ claimLocalWorktreeCleanups: ownedWorktreeProcedure
+ .input(z.object({ deviceId: z.string().optional() }))
+ .mutation(async ({ ctx, input }) => {
+ await assertOwnDevice(ctx, input.deviceId);
+ return ctx.worktreeCleanup.claimLocalCleanups(input.deviceId, {
+ canClaim: async (row) => {
+ try {
+ await assertTopic(ctx, row.id);
+ return true;
+ } catch {
+ return false;
+ }
+ },
+ });
+ }),
+
+ /**
+ * A desktop's IPC result. Accepted from the topic's creator, or from whoever
+ * operates the device the worktree is on (a shared workspace device runs its
+ * teammates' cleanups).
+ */
+ reportOwnedWorktreeCleanup: ownedWorktreeProcedure
+ .input(
+ target.extend({
+ result: cleanupResultSchema,
+ trigger: z.enum(['archived', 'discarded', 'trashed']),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const { entry, row } = await loadOwnedWorktree(ctx, input.topicId, input.path);
+ if (entry.deviceId) await assertWorktreeDevice(ctx, entry.deviceId);
+ else assertTopicCreator(ctx, row.userId);
+ return (
+ (await ctx.worktreeCleanup.recordCleanupResult(
+ input.topicId,
+ input.path,
+ input.trigger,
+ input.result,
+ )) ?? null
+ );
+ }),
+
+ /**
+ * Check a cleaned-up worktree out again before a restored topic's next turn
+ * (any member who may use the topic and operate its device). Runs on the
+ * device unless the desktop runs it (`local`) and reports its `result`.
+ */
+ restoreOwnedWorktree: ownedWorktreeProcedure
+ .input(
+ target.extend({
+ /** The worktree is on the calling desktop: answer `needsLocal` instead of the RPC. */
+ local: z.boolean().optional(),
+ result: restoreResultSchema.optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ await assertTopic(ctx, input.topicId);
+ const { entry } = await loadOwnedWorktree(ctx, input.topicId, input.path);
+ await assertWorktreeDevice(ctx, entry.deviceId);
+ return ctx.worktreeCleanup.restore(input.topicId, input.path, {
+ local: input.local,
+ result: input.result,
+ });
+ }),
+});
diff --git a/apps/server/src/routers/lambda/topic/update.ts b/apps/server/src/routers/lambda/topic/update.ts
index 362c90e305f..2fdd81f271e 100644
--- a/apps/server/src/routers/lambda/topic/update.ts
+++ b/apps/server/src/routers/lambda/topic/update.ts
@@ -10,6 +10,7 @@ import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPer
import { TopicRepository } from '@/database/repositories/topic';
import { router } from '@/libs/trpc/lambda';
import { GoalTopicHandoffService } from '@/server/services/goal/topicHandoff';
+import { TopicArchiveService } from '@/server/services/topicArchive';
import { assertWorkspaceRowManageable } from '../_helpers/assertWorkspaceRowManageable';
import {
@@ -51,8 +52,15 @@ export const updateRouter = router({
// view-only members are read-only.
await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);
await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);
+ // Every archive goes through `TopicArchiveService`, which sets off what
+ // archiving a topic does (cleanup of the worktree the app created).
+ const archive = new TopicArchiveService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
const { agentId, sessionId, ...restValue } = input.value;
- if (!agentId && !sessionId) return ctx.topicModel.update(input.id, restValue);
+ if (!agentId && !sessionId) return archive.updateTopic(input.id, restValue);
const resolved = await resolveContext(
{ agentId, sessionId },
ctx.serverDB,
@@ -60,7 +68,7 @@ export const updateRouter = router({
ctx.workspaceId ?? undefined,
);
await assertCanUseConversationTargets(guardCtx(ctx), [resolved]);
- return ctx.topicModel.update(input.id, {
+ return archive.updateTopic(input.id, {
...restValue,
agentId: resolved.agentId,
sessionId: resolved.sessionId,
diff --git a/apps/server/src/routers/lambda/topic/update.worktreeCleanup.test.ts b/apps/server/src/routers/lambda/topic/update.worktreeCleanup.test.ts
new file mode 100644
index 00000000000..8f39dba233d
--- /dev/null
+++ b/apps/server/src/routers/lambda/topic/update.worktreeCleanup.test.ts
@@ -0,0 +1,71 @@
+// @vitest-environment node
+import { type LobeChatDatabase } from '@lobechat/database';
+import { topics } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cleanupTestUser, createTestUser } from '../__tests__/integration/setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+const scheduleWorktreeCleanup = vi.hoisted(() => vi.fn());
+vi.mock('@/server/services/worktreeCleanup', () => ({ scheduleWorktreeCleanup }));
+
+const { topicRouter } = await import('./index');
+
+/**
+ * "Archive" in the UI is `updateTopic({ status: 'completed' })` — single, bulk
+ * and "archive merged PRs" alike. That write is what starts the cleanup of the
+ * worktree the app created for the topic, with the status it replaced.
+ */
+describe('topic.updateTopic archive → worktree cleanup', () => {
+ let userId: string;
+
+ beforeEach(async () => {
+ testDB = await getTestDB();
+ userId = await createTestUser(testDB);
+ });
+
+ afterEach(async () => {
+ scheduleWorktreeCleanup.mockReset();
+ await cleanupTestUser(testDB, userId);
+ });
+
+ const seed = async (status: 'active' | 'completed' | 'running') => {
+ const [topic] = await testDB.insert(topics).values({ status, title: 't', userId }).returning();
+ return topic.id;
+ };
+
+ it('schedules the cleanup with the previous status when a topic is archived', async () => {
+ const id = await seed('running');
+ const caller = topicRouter.createCaller({ userId } as any);
+
+ await caller.updateTopic({ id, value: { completedAt: new Date(), status: 'completed' } });
+
+ expect(scheduleWorktreeCleanup).toHaveBeenCalledWith(
+ expect.objectContaining({
+ previousStatus: { [id]: 'running' },
+ topicIds: [id],
+ trigger: 'archived',
+ userId,
+ }),
+ );
+ });
+
+ it('does not schedule for other status writes or an already archived topic', async () => {
+ const active = await seed('active');
+ const archived = await seed('completed');
+ const caller = topicRouter.createCaller({ userId } as any);
+
+ await caller.updateTopic({ id: active, value: { status: 'unread' } });
+ await caller.updateTopic({ id: active, value: { title: 'renamed' } });
+ await caller.updateTopic({ id: archived, value: { status: 'completed' } });
+
+ expect(scheduleWorktreeCleanup).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
index 247bd25e285..3e6be7d2cb4 100644
--- a/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
+++ b/apps/server/src/services/aiAgent/pipeline/heteroDispatch/device.ts
@@ -15,6 +15,7 @@ import {
wakeManagedDevice,
} from '@/server/services/deviceGateway/managedDeviceWake';
import { buildRemoteDeviceHeteroContext } from '@/server/services/heterogeneousAgent/remoteDeviceHeteroContext';
+import { restoreOwnedWorktreeBeforeServerRun } from '@/server/services/worktreeCleanup';
import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';
import {
@@ -120,7 +121,7 @@ export const dispatchToCliDevice = async (
heteroExecArgs,
heteroParams,
resumeSessionId,
- topic,
+ topic: preparedTopic,
topicRepos,
unansweredUserTurns,
} = prepared;
@@ -190,6 +191,26 @@ export const dispatchToCliDevice = async (
}
const nativeCodex = codexRuntime.kind === 'native' ? codexRuntime : undefined;
+ // A turn the server starts on its own (a delegated task reporting back)
+ // never passed the composer's restore step: bring back the worktree a
+ // cleanup removed, so the CLI does not spawn in a folder that is gone.
+ const restored =
+ preparedTopic && topicId
+ ? await traceHeteroStage('device restore_owned_worktree', () =>
+ restoreOwnedWorktreeBeforeServerRun({
+ db: deps.db,
+ metadata: preparedTopic.metadata,
+ topicId,
+ userId: deps.userId,
+ workspaceId: deps.workspaceId,
+ }),
+ )
+ : undefined;
+ const topic =
+ preparedTopic && restored
+ ? { ...preparedTopic, metadata: restored.metadata ?? undefined }
+ : preparedTopic;
+
// Resolve the working directory for the run: a topic-level override
// wins, else the device's user-configured defaultCwd.
const dispatchWorkspaceId = cliDeviceWorkspaceId;
diff --git a/apps/server/src/services/deviceGateway/gitWrite.ts b/apps/server/src/services/deviceGateway/gitWrite.ts
index b26f68af352..694156c30fe 100644
--- a/apps/server/src/services/deviceGateway/gitWrite.ts
+++ b/apps/server/src/services/deviceGateway/gitWrite.ts
@@ -11,7 +11,10 @@ import type {
DeviceGitRemoveWorktreeResult,
DeviceGitRenameBranchResult,
DeviceGitSyncResult,
+ OwnedWorktreeCleanupResult,
+ OwnedWorktreeRestoreResult,
} from '@lobechat/types';
+import { OWNED_WORKTREE_RPC_UNSUPPORTED } from '@lobechat/types';
import debug from 'debug';
import type { DeviceClientGetter } from './types';
@@ -191,6 +194,8 @@ export async function addGitWorktree(
params: {
branch: string;
deviceId: string;
+ /** Creation receipt the device writes into the worktree (app-created worktrees). */
+ ownerToken?: string;
path: string;
/** Fork the worktree's branch from this branch instead of HEAD. */
startPoint?: string;
@@ -204,6 +209,7 @@ export async function addGitWorktree(
userId,
deviceId,
branch,
+ ownerToken,
path,
startPoint,
worktreePath,
@@ -218,7 +224,13 @@ export async function addGitWorktree(
{ deviceId, timeout, userId, workspaceId },
{
method: 'addGitWorktree',
- params: { branch, path, worktreePath, ...(startPoint ? { startPoint } : {}) },
+ params: {
+ branch,
+ path,
+ worktreePath,
+ ...(ownerToken ? { ownerToken } : {}),
+ ...(startPoint ? { startPoint } : {}),
+ },
},
);
@@ -234,6 +246,135 @@ export async function addGitWorktree(
}
}
+/** A device client older than the owned-worktree RPCs rejects the method name. */
+const isUnsupportedMethod = (error: string | undefined) =>
+ !!error && error.includes(OWNED_WORKTREE_RPC_UNSUPPORTED);
+
+/**
+ * Remove (or keep, when it has uncommitted work) a worktree the app created
+ * for a conversation, via the `cleanupOwnedWorktree` device RPC. Every guard
+ * runs on the device. A device that cannot be reached or is too old for the
+ * RPC answers `unreachable`, which the caller keeps as pending.
+ */
+export async function cleanupOwnedWorktree(
+ getClient: DeviceClientGetter,
+ params: {
+ deviceId: string;
+ discard?: boolean;
+ /** The creation receipt the device checks before acting (see local-file-shell). */
+ ownerToken?: string;
+ sourcePath: string;
+ timeout?: number;
+ userId: string;
+ workspaceId?: string;
+ worktreePath: string;
+ },
+): Promise<OwnedWorktreeCleanupResult> {
+ const {
+ userId,
+ deviceId,
+ discard,
+ ownerToken,
+ sourcePath,
+ worktreePath,
+ workspaceId,
+ // Above the device's own 90s budget, so its answer (not ours) decides.
+ timeout = 100_000,
+ } = params;
+ const client = getClient();
+ if (!client) return { error: 'Device gateway not configured', outcome: 'unreachable' };
+
+ try {
+ const result = await client.invokeRpc<OwnedWorktreeCleanupResult>(
+ { deviceId, timeout, userId, workspaceId },
+ {
+ method: 'cleanupOwnedWorktree',
+ params: {
+ discard: discard === true,
+ ...(ownerToken && { ownerToken }),
+ sourcePath,
+ worktreePath,
+ },
+ },
+ );
+ if (!result.success || !result.data) {
+ log('cleanupOwnedWorktree: failed for deviceId=%s — %s', deviceId, result.error);
+ return {
+ error: result.error || 'Device unreachable',
+ outcome: 'unreachable',
+ ...(isUnsupportedMethod(result.error) && { outdated: true }),
+ };
+ }
+ return result.data;
+ } catch (error) {
+ const message = (error as Error)?.message || 'Device unreachable';
+ log('cleanupOwnedWorktree: error for deviceId=%s — %O', deviceId, error);
+ return {
+ error: message,
+ outcome: 'unreachable',
+ ...(isUnsupportedMethod(message) && { outdated: true }),
+ };
+ }
+}
+
+/**
+ * Check a cleaned-up worktree out again at its path via the
+ * `restoreOwnedWorktree` device RPC.
+ */
+export async function restoreOwnedWorktree(
+ getClient: DeviceClientGetter,
+ params: {
+ branch: string;
+ deviceId: string;
+ ownerToken?: string;
+ sourcePath: string;
+ timeout?: number;
+ userId: string;
+ workspaceId?: string;
+ worktreePath: string;
+ },
+): Promise<OwnedWorktreeRestoreResult> {
+ const {
+ userId,
+ deviceId,
+ branch,
+ ownerToken,
+ sourcePath,
+ worktreePath,
+ workspaceId,
+ timeout = 45_000,
+ } = params;
+ const client = getClient();
+ if (!client) return { error: 'Device gateway not configured', outcome: 'unreachable' };
+
+ try {
+ const result = await client.invokeRpc<OwnedWorktreeRestoreResult>(
+ { deviceId, timeout, userId, workspaceId },
+ {
+ method: 'restoreOwnedWorktree',
+ params: { branch, ...(ownerToken && { ownerToken }), sourcePath, worktreePath },
+ },
+ );
+ if (!result.success || !result.data) {
+ log('restoreOwnedWorktree: failed for deviceId=%s — %s', deviceId, result.error);
+ return {
+ error: result.error || 'Device unreachable',
+ outcome: 'unreachable',
+ ...(isUnsupportedMethod(result.error) && { outdated: true }),
+ };
+ }
+ return result.data;
+ } catch (error) {
+ const message = (error as Error)?.message || 'Device unreachable';
+ log('restoreOwnedWorktree: error for deviceId=%s — %O', deviceId, error);
+ return {
+ error: message,
+ outcome: 'unreachable',
+ ...(isUnsupportedMethod(message) && { outdated: true }),
+ };
+ }
+}
+
/**
* Pull (`--ff-only`) the current branch of a directory on a remote device via
* the `pullGitBranch` device RPC.
diff --git a/apps/server/src/services/deviceGateway/index.ownedWorktree.test.ts b/apps/server/src/services/deviceGateway/index.ownedWorktree.test.ts
new file mode 100644
index 00000000000..98cf204c6ab
--- /dev/null
+++ b/apps/server/src/services/deviceGateway/index.ownedWorktree.test.ts
@@ -0,0 +1,101 @@
+/**
+ * The owned-worktree RPCs answer with an `outcome`, and every way the device
+ * cannot be asked (no gateway, offline, a client too old for the method)
+ * folds to `unreachable` — the caller keeps those cleanups pending.
+ */
+import type * as DeviceGatewayClientModule from '@lobechat/device-gateway-client';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DeviceGateway } from '.';
+import { configureGateway, mockClient, resetGatewayMocks } from './testUtils';
+
+vi.mock('@/server/services/redis/client', () =>
+ import('./testUtils').then((m) => ({ getRedisServiceClient: m.getRedisServiceClient })),
+);
+
+vi.mock('@/envs/gateway', () => import('./testUtils').then((m) => ({ gatewayEnv: m.mockEnv })));
+
+vi.mock('@lobechat/device-gateway-client', async (importOriginal) => ({
+ ...(await importOriginal<typeof DeviceGatewayClientModule>()),
+ GatewayHttpClient: (await import('./testUtils')).MockGatewayHttpClient,
+}));
+
+const base = { deviceId: 'device-1', userId: 'user-1', workspaceId: 'ws-1' };
+const paths = { sourcePath: '/code/repo', worktreePath: '/home/.lobehub/worktrees/r/x' };
+
+describe('DeviceGateway owned-worktree RPCs', () => {
+ beforeEach(() => {
+ resetGatewayMocks();
+ });
+
+ it('relays cleanupOwnedWorktree with only the named params', async () => {
+ configureGateway();
+ mockClient.invokeRpc.mockResolvedValue({
+ data: { branch: 'lobehub/x', outcome: 'removed' },
+ success: true,
+ });
+
+ await expect(
+ new DeviceGateway().cleanupOwnedWorktree({
+ ...base,
+ ...paths,
+ discard: true,
+ ownerToken: 'receipt-0123456789abcdef',
+ }),
+ ).resolves.toEqual({ branch: 'lobehub/x', outcome: 'removed' });
+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(
+ { deviceId: 'device-1', timeout: 100_000, userId: 'user-1', workspaceId: 'ws-1' },
+ {
+ method: 'cleanupOwnedWorktree',
+ params: { discard: true, ownerToken: 'receipt-0123456789abcdef', ...paths },
+ },
+ );
+ });
+
+ it('relays restoreOwnedWorktree', async () => {
+ configureGateway();
+ mockClient.invokeRpc.mockResolvedValue({ data: { outcome: 'restored' }, success: true });
+
+ await expect(
+ new DeviceGateway().restoreOwnedWorktree({ ...base, ...paths, branch: 'lobehub/x' }),
+ ).resolves.toEqual({ outcome: 'restored' });
+ expect(mockClient.invokeRpc).toHaveBeenCalledWith(
+ { deviceId: 'device-1', timeout: 45_000, userId: 'user-1', workspaceId: 'ws-1' },
+ { method: 'restoreOwnedWorktree', params: { branch: 'lobehub/x', ...paths } },
+ );
+ });
+
+ it('is unreachable without a configured gateway', async () => {
+ await expect(
+ new DeviceGateway().cleanupOwnedWorktree({ ...base, ...paths }),
+ ).resolves.toMatchObject({ outcome: 'unreachable' });
+ expect(mockClient.invokeRpc).not.toHaveBeenCalled();
+ });
+
+ it('is unreachable when the device is offline', async () => {
+ configureGateway();
+ mockClient.invokeRpc.mockRejectedValue(new Error('Device is offline'));
+ await expect(new DeviceGateway().cleanupOwnedWorktree({ ...base, ...paths })).resolves.toEqual({
+ error: 'Device is offline',
+ outcome: 'unreachable',
+ });
+ });
+
+ it('flags a device client that predates the RPC as outdated', async () => {
+ configureGateway();
+ mockClient.invokeRpc.mockResolvedValue({
+ error: 'Unknown device RPC method: cleanupOwnedWorktree',
+ success: false,
+ });
+ await expect(
+ new DeviceGateway().cleanupOwnedWorktree({ ...base, ...paths }),
+ ).resolves.toMatchObject({ outcome: 'unreachable', outdated: true });
+
+ mockClient.invokeRpc.mockRejectedValue(
+ new Error('Unknown device RPC method: restoreOwnedWorktree'),
+ );
+ await expect(
+ new DeviceGateway().restoreOwnedWorktree({ ...base, ...paths, branch: 'b' }),
+ ).resolves.toMatchObject({ outcome: 'unreachable', outdated: true });
+ });
+});
diff --git a/apps/server/src/services/deviceGateway/index.ts b/apps/server/src/services/deviceGateway/index.ts
index 772db8165fa..49ea7e0b58c 100644
--- a/apps/server/src/services/deviceGateway/index.ts
+++ b/apps/server/src/services/deviceGateway/index.ts
@@ -347,6 +347,14 @@ export class DeviceGateway {
return gitWrite.addGitWorktree(this.clientGetter, ...args);
}
+ cleanupOwnedWorktree(...args: DeviceRpcArgs<typeof gitWrite.cleanupOwnedWorktree>) {
+ return gitWrite.cleanupOwnedWorktree(this.clientGetter, ...args);
+ }
+
+ restoreOwnedWorktree(...args: DeviceRpcArgs<typeof gitWrite.restoreOwnedWorktree>) {
+ return gitWrite.restoreOwnedWorktree(this.clientGetter, ...args);
+ }
+
pullGitBranch(...args: DeviceRpcArgs<typeof gitWrite.pullGitBranch>) {
return gitWrite.pullGitBranch(this.clientGetter, ...args);
}
diff --git a/apps/server/src/services/topicArchive/index.test.ts b/apps/server/src/services/topicArchive/index.test.ts
new file mode 100644
index 00000000000..a9878686c8b
--- /dev/null
+++ b/apps/server/src/services/topicArchive/index.test.ts
@@ -0,0 +1,67 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { topics, users } from '@/database/schemas';
+
+import { TopicArchiveService } from './index';
+
+const scheduleWorktreeCleanup = vi.hoisted(() => vi.fn());
+vi.mock('@/server/services/worktreeCleanup', () => ({ scheduleWorktreeCleanup }));
+
+const db = await getTestDB();
+const userId = 'topic-archive-user';
+
+const seed = async (id: string, status: 'active' | 'completed' | 'running') =>
+ db.insert(topics).values({ id, status, title: id, userId });
+
+beforeEach(async () => {
+ await db.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ scheduleWorktreeCleanup.mockReset();
+ await db.delete(topics).where(eq(topics.userId, userId));
+ await db.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('TopicArchiveService', () => {
+ it('fires the archive follow-up for every topic a batch archives, with its previous status', async () => {
+ await seed('a', 'active');
+ await seed('b', 'running');
+ await seed('c', 'completed');
+
+ const archived = await new TopicArchiveService(db, userId).archiveTopics(['a', 'b', 'c']);
+
+ expect(archived.map((row) => row.status)).toEqual(['completed', 'completed', 'completed']);
+ // `c` was already archived: nothing new to set off.
+ expect(scheduleWorktreeCleanup).toHaveBeenCalledTimes(2);
+ expect(scheduleWorktreeCleanup).toHaveBeenCalledWith(
+ expect.objectContaining({
+ previousStatus: { a: 'active' },
+ topicIds: ['a'],
+ trigger: 'archived',
+ }),
+ );
+ expect(scheduleWorktreeCleanup).toHaveBeenCalledWith(
+ expect.objectContaining({ previousStatus: { b: 'running' }, topicIds: ['b'] }),
+ );
+ });
+
+ it('treats the legacy archived status as an archive too', async () => {
+ await seed('legacy', 'active');
+ await new TopicArchiveService(db, userId).updateTopic('legacy', { status: 'archived' });
+ expect(scheduleWorktreeCleanup).toHaveBeenCalledTimes(1);
+ });
+
+ it('does nothing extra for other updates or a topic it cannot see', async () => {
+ await seed('t', 'active');
+ const service = new TopicArchiveService(db, userId);
+ await service.updateTopic('t', { title: 'renamed' });
+ await service.updateTopic('t', { status: 'unread' });
+ await service.archiveTopics(['missing']);
+ await new TopicArchiveService(db, 'someone-else').archiveTopics(['t']);
+ expect(scheduleWorktreeCleanup).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/topicArchive/index.ts b/apps/server/src/services/topicArchive/index.ts
new file mode 100644
index 00000000000..dceb6389eff
--- /dev/null
+++ b/apps/server/src/services/topicArchive/index.ts
@@ -0,0 +1,68 @@
+import { isRetiredTopicStatus } from '@lobechat/types';
+
+import { TopicModel } from '@/database/models/topic';
+import type { LobeChatDatabase } from '@/database/type';
+import { scheduleWorktreeCleanup } from '@/server/services/worktreeCleanup';
+
+/**
+ * The server-side write path for a topic's own fields, status included — and
+ * so the one place a topic becomes archived. "Archive" in the UI is
+ * `status: 'completed'` (`archived` is a legacy value treated the same), and
+ * every archive goes through here: the single and bulk actions, "archive
+ * merged PR topics", and any server-side cascade (archive child topics one by
+ * one with {@link TopicArchiveService.archiveTopics}).
+ *
+ * What archiving sets off rides on this path, so no entry point can skip it:
+ * today the cleanup of the worktree the app created for the topic. The
+ * recycle-bin counterpart is `TrashService.commit`.
+ *
+ * Authorization stays with the caller (the router checks General access and
+ * share-visitor guards before calling).
+ */
+/** The fields `TopicModel.update` writes. */
+type TopicUpdate = Parameters<TopicModel['update']>[1];
+
+export class TopicArchiveService {
+ private readonly topicModel: TopicModel;
+
+ constructor(
+ private readonly db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ ) {
+ this.topicModel = new TopicModel(db, userId, workspaceId);
+ }
+
+ /**
+ * Update a topic. When the update moves it into archived from any other
+ * status, the archive's follow-up work is scheduled after the write, with
+ * the status it replaced (a run that was still live holds the cleanup).
+ */
+ async updateTopic(id: string, value: TopicUpdate) {
+ const archiving = isRetiredTopicStatus(value.status);
+ const previous = archiving ? await this.topicModel.findById(id) : undefined;
+ const updated = await this.topicModel.update(id, value);
+
+ if (archiving && previous && !isRetiredTopicStatus(previous.status) && updated.length > 0)
+ scheduleWorktreeCleanup({
+ db: this.db,
+ previousStatus: { [id]: previous.status },
+ topicIds: [id],
+ trigger: 'archived',
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
+ return updated;
+ }
+
+ /** Archive topics, each through {@link updateTopic}. */
+ async archiveTopics(ids: string[]) {
+ const archived: Awaited<ReturnType<TopicModel['update']>> = [];
+ for (const id of ids) {
+ archived.push(
+ ...(await this.updateTopic(id, { completedAt: new Date(), status: 'completed' })),
+ );
+ }
+ return archived;
+ }
+}
diff --git a/apps/server/src/services/trash/__tests__/index.test.ts b/apps/server/src/services/trash/__tests__/index.test.ts
index d6972dd951b..2e616103402 100644
--- a/apps/server/src/services/trash/__tests__/index.test.ts
+++ b/apps/server/src/services/trash/__tests__/index.test.ts
@@ -27,6 +27,10 @@ import type { LobeChatDatabase } from '@/database/type';
import { TrashService } from '../index';
+// Trashing a topic starts the cleanup of the worktree the app created for it.
+const scheduleWorktreeCleanup = vi.hoisted(() => vi.fn());
+vi.mock('@/server/services/worktreeCleanup', () => ({ scheduleWorktreeCleanup }));
+
// Lets a test land a concurrent purge between a restore handler's reads and its
// write: the handlers check the owning agent right before restoring, inside the
// restore transaction (the hook receives that transaction).
@@ -157,12 +161,76 @@ describe('TrashService', () => {
expect(outcome.failed).toEqual([{ code: 'notFound', id: root.id }]);
});
+ it('keeps a topic in the bin while its worktree cleanup waits for an offline device', async () => {
+ const WT = '/Users/me/.lobehub/worktrees/repo-1a2b3c4d/quiet-hill';
+ const pending = (at: string) => ({
+ ownedWorktrees: [
+ {
+ branch: 'lobehub/quiet-hill',
+ cleanup: { at, state: 'pending' as const, trigger: 'trashed' as const },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ });
+ const topic = await topicModel.create({ title: 'Worktree topic' });
+ const [root] = await service.trashTopics([topic.id]);
+ await serverDB
+ .update(topics)
+ .set({ metadata: pending(new Date().toISOString()) })
+ .where(eq(topics.id, topic.id));
+
+ // Purging now would lose the only record of the folder to delete.
+ expect(await service.purge([root.id])).toEqual({ blocked: [root.id], purged: 0 });
+ expect(await serverDB.select().from(topics).where(eq(topics.id, topic.id))).toHaveLength(1);
+
+ // A device gone for longer than the hold no longer keeps it.
+ await serverDB
+ .update(topics)
+ .set({ metadata: pending(new Date(Date.now() - 31 * 24 * 3600 * 1000).toISOString()) })
+ .where(eq(topics.id, topic.id));
+ expect(await service.purge([root.id])).toEqual({ blocked: [], purged: 1 });
+ });
+
+ it("holds an agent's purge while one of its topics still has a worktree cleanup waiting", async () => {
+ const agent = await agentModel.create({ title: 'Bot' });
+ const topic = await topicModel.create({ agentId: agent.id, title: 'Worktree topic' });
+ const root = await service.trashAgent(agent.id);
+ await serverDB
+ .update(topics)
+ .set({
+ metadata: {
+ ownedWorktrees: [
+ {
+ cleanup: { at: new Date().toISOString(), state: 'pending', trigger: 'trashed' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: '/Users/me/.lobehub/worktrees/repo-1a2b3c4d/quiet-hill',
+ sourcePath: '/code/repo',
+ },
+ ],
+ },
+ })
+ .where(eq(topics.id, topic.id));
+
+ expect(await service.purge([root!.id])).toEqual({ blocked: [root!.id], purged: 0 });
+ expect(await serverDB.select().from(topics).where(eq(topics.id, topic.id))).toHaveLength(1);
+ });
+
it('bulk sweeps become one restorable root per topic', async () => {
const agent = await agentModel.create({ title: 'Bot' });
await topicModel.create({ agentId: agent.id, title: 'a' });
await topicModel.create({ agentId: agent.id, title: 'b' });
const roots = await service.trashTopicsByAgent(agent.id);
expect(roots).toHaveLength(2);
+ expect(scheduleWorktreeCleanup).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ topicIds: expect.arrayContaining(roots.map((root) => root.resourceId)),
+ trigger: 'trashed',
+ }),
+ );
expect((await topicModel.query({ agentId: agent.id })).items).toHaveLength(0);
expect((await service.list()).items).toHaveLength(2);
});
diff --git a/apps/server/src/services/trash/__tests__/task.test.ts b/apps/server/src/services/trash/__tests__/task.test.ts
index fad91f15aec..3df49247292 100644
--- a/apps/server/src/services/trash/__tests__/task.test.ts
+++ b/apps/server/src/services/trash/__tests__/task.test.ts
@@ -15,7 +15,10 @@ import { TaskBatchService } from '@/server/services/task/batch';
import { TrashService } from '../index';
-vi.mock('@/server/utils/scheduleAfterResponse', () => ({ after: vi.fn() }));
+vi.mock('@/server/utils/scheduleAfterResponse', () => ({
+ after: vi.fn(),
+ afterUnscoped: vi.fn(),
+}));
vi.mock('@/server/services/file', () => ({
FileService: vi.fn().mockImplementation(() => ({ deleteFile: vi.fn(), deleteFiles: vi.fn() })),
}));
diff --git a/apps/server/src/services/trash/handlers/agent.ts b/apps/server/src/services/trash/handlers/agent.ts
index b0983b78c98..0b849b53872 100644
--- a/apps/server/src/services/trash/handlers/agent.ts
+++ b/apps/server/src/services/trash/handlers/agent.ts
@@ -11,11 +11,12 @@ import type { LobeChatDatabase } from '@/database/type';
import type { SoftDeleteOptions } from '@/database/utils/softDelete';
import { MESSAGE_TITLE_LENGTH } from './message';
-import { topicEntry } from './topic';
+import { hasWaitingWorktreeCleanup, topicEntry, WORKTREE_CLEANUP_WAITING_MESSAGE } from './topic';
import {
type TrashCascade,
type TrashHandler,
type TrashHandlerContext,
+ TrashPurgeBlockedError,
TrashRestoreError,
} from './types';
@@ -102,6 +103,17 @@ export const agentHandler: TrashHandler = {
if (agentIds.length === 0) return;
const sessionIds = await agentModel.findSessionIdsByAgentIds(agentIds);
+ // The cascade below takes the agent's topics with it — including the
+ // only record of a worktree cleanup still waiting on an offline device.
+ // Hold the whole purge until those have run (see `./topic`).
+ const waiting = await new TopicModel(
+ db,
+ ctx.userId,
+ ctx.workspaceId,
+ ).findWaitingCleanupTopicsUnder({ agentIds, sessionIds });
+ if (hasWaitingWorktreeCleanup(waiting))
+ throw new TrashPurgeBlockedError(WORKTREE_CLEANUP_WAITING_MESSAGE);
+
// Topics / messages trashed on their own before this agent keep separate
// roots; the cascade below deletes them, so drop those rows first.
await new TrashModel(db, ctx.userId, ctx.workspaceId).removeRootsUnderAgents({
diff --git a/apps/server/src/services/trash/handlers/task.ts b/apps/server/src/services/trash/handlers/task.ts
index 78f66836cbc..d805d9e122a 100644
--- a/apps/server/src/services/trash/handlers/task.ts
+++ b/apps/server/src/services/trash/handlers/task.ts
@@ -5,11 +5,12 @@ import { TopicModel } from '@/database/models/topic';
import type { TrashRegisterEntry } from '@/database/models/trash';
import type { SoftDeleteOptions } from '@/database/utils/softDelete';
-import { topicEntry } from './topic';
+import { hasWaitingWorktreeCleanup, topicEntry, WORKTREE_CLEANUP_WAITING_MESSAGE } from './topic';
import {
type TrashCascade,
type TrashHandler,
type TrashHandlerContext,
+ TrashPurgeBlockedError,
TrashRestoreError,
} from './types';
@@ -76,6 +77,19 @@ export const taskHandler: TrashHandler = {
* a restore that won the race (nothing left stamped) keeps both.
*/
purge: async (ctx, root, children) => {
+ // Its topics go with it: hold while any still has a worktree cleanup
+ // waiting on its device (see `./topic`).
+ const childTopicIds = children
+ .filter((child) => child.resourceType === 'topic')
+ .map((child) => child.resourceId);
+ const childTopics = await new TopicModel(
+ ctx.db,
+ ctx.userId,
+ ctx.workspaceId,
+ ).findOwnedWorktreeTopics(childTopicIds);
+ if (hasWaitingWorktreeCleanup(childTopics))
+ throw new TrashPurgeBlockedError(WORKTREE_CLEANUP_WAITING_MESSAGE);
+
await ctx.db.transaction(async (tx) => {
const db = tx as unknown as typeof ctx.db;
// FK cascades take dependencies, comments, documents and `task_topics`;
diff --git a/apps/server/src/services/trash/handlers/topic.ts b/apps/server/src/services/trash/handlers/topic.ts
index 8f66b397d95..bd49808de9d 100644
--- a/apps/server/src/services/trash/handlers/topic.ts
+++ b/apps/server/src/services/trash/handlers/topic.ts
@@ -1,3 +1,5 @@
+import { resolveOwnedWorktrees } from '@lobechat/types';
+
import { serverDBEnv } from '@/config/db';
import { AgentModel } from '@/database/models/agent';
import { FileModel } from '@/database/models/file';
@@ -9,6 +11,7 @@ import {
type TrashCascade,
type TrashHandler,
type TrashHandlerContext,
+ TrashPurgeBlockedError,
TrashRestoreError,
} from './types';
@@ -29,8 +32,45 @@ export const topicEntry = (topic: TopicItem, removeFiles?: boolean): TrashRegist
export const topicCascades = (topics: TopicItem[], removeFiles?: boolean): TrashCascade[] =>
topics.map((topic) => ({ children: [], root: topicEntry(topic, removeFiles) }));
+/**
+ * How long a cleanup waiting on an offline device holds its topic in the
+ * recycle bin. Long enough for a machine that is merely off; a device that
+ * never returns must not keep the topic forever.
+ */
+export const PENDING_WORKTREE_PURGE_HOLD_MS = 30 * 24 * 60 * 60 * 1000;
+
+/** Whether any of these topics still has a worktree cleanup waiting on its device. */
+export const hasWaitingWorktreeCleanup = (
+ rows: { metadata?: Parameters<typeof resolveOwnedWorktrees>[0] }[],
+ now = Date.now(),
+) =>
+ rows.some((row) =>
+ resolveOwnedWorktrees(row.metadata).some(
+ (entry) =>
+ (entry.cleanup?.state === 'pending' || entry.cleanup?.state === 'running') &&
+ now - new Date(entry.cleanup.at).getTime() < PENDING_WORKTREE_PURGE_HOLD_MS,
+ ),
+ );
+
+export const WORKTREE_CLEANUP_WAITING_MESSAGE =
+ 'The worktree cleanup is waiting for its device to connect';
+
+/**
+ * The cleanup of the worktree the app created for a topic lives only in the
+ * topic's metadata. Purging the topic while that cleanup still waits on its
+ * device would leave the folder untracked for good, so the purge waits for it
+ * (the root stays in the bin and the next purge or sweep retries).
+ */
+const assertNoPendingWorktreeCleanup = async (topicModel: TopicModel, topicId: string) => {
+ if (hasWaitingWorktreeCleanup(await topicModel.findOwnedWorktreeTopics([topicId])))
+ throw new TrashPurgeBlockedError(WORKTREE_CLEANUP_WAITING_MESSAGE);
+};
+
export const topicHandler: TrashHandler = {
purge: async (ctx, root) => {
+ const topicModel = new TopicModel(ctx.db, ctx.userId, ctx.workspaceId);
+ await assertNoPendingWorktreeCleanup(topicModel, root.resourceId);
+
// `removeFiles` was requested at delete time: collect the attachments only
// this topic still references (same reference-safe set the hard delete
// used). Computed now, not at trash time, so a file that got attached
@@ -41,9 +81,7 @@ export const topicHandler: TrashHandler = {
? await fileModel.findDeletableFilesByTopicId(root.resourceId)
: [];
- const purged = await new TopicModel(ctx.db, ctx.userId, ctx.workspaceId).purge([
- root.resourceId,
- ]);
+ const purged = await topicModel.purge([root.resourceId]);
// Nothing deleted means the topic was restored in the meantime: leave its
// attachments alone too.
if (purged.length === 0 || fileIds.length === 0) return;
diff --git a/apps/server/src/services/trash/index.ts b/apps/server/src/services/trash/index.ts
index bee76533a7d..748675d4924 100644
--- a/apps/server/src/services/trash/index.ts
+++ b/apps/server/src/services/trash/index.ts
@@ -16,6 +16,7 @@ import type { LobeChatDatabase, Transaction } from '@/database/type';
import type { SoftDeleteOptions } from '@/database/utils/softDelete';
import { FileService } from '@/server/services/file';
import { removeByAgent, removeByTopics } from '@/server/services/inboundWebhook/lifecycle';
+import { scheduleWorktreeCleanup } from '@/server/services/worktreeCleanup';
import {
resolveTrashHandler,
@@ -171,6 +172,15 @@ export class TrashService {
});
// Do remote teardown after commit, for the actual rows stamped (including cascades).
// A rollback never removes live subscriptions; a missing remote cannot undo the trash operation.
+ // The worktrees the app created for these topics go with them; the branch
+ // stays, so a restore can check it out again.
+ scheduleWorktreeCleanup({
+ db: this.db,
+ topicIds: removedTopics,
+ trigger: 'trashed',
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ });
if (removedTopics.length || removedAgents.length) {
try {
const scope = { userId: this.userId, workspaceId: this.workspaceId };
diff --git a/apps/server/src/services/worktreeCleanup/index.test.ts b/apps/server/src/services/worktreeCleanup/index.test.ts
new file mode 100644
index 00000000000..37b52697451
--- /dev/null
+++ b/apps/server/src/services/worktreeCleanup/index.test.ts
@@ -0,0 +1,742 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import type { ChatTopicMetadata, OwnedWorktreeCleanupResult } from '@lobechat/types';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { topics, users, workspaces } from '@/database/schemas';
+
+import {
+ restoreOwnedWorktreeBeforeServerRun,
+ STALE_CLAIM_MS,
+ WorktreeCleanupService,
+} from './index';
+
+vi.mock('@/server/services/deviceGateway', () => ({ deviceGateway: {} }));
+
+const db = await getTestDB();
+const userId = 'worktree-cleanup-user';
+const WT = '/Users/me/.lobehub/worktrees/repo-1a2b3c4d/quiet-hill';
+const BRANCH = 'lobehub/quiet-hill';
+
+type Status = 'active' | 'completed' | 'running' | 'waitingForHuman';
+
+const autoCreated = (extra: Partial<ChatTopicMetadata> = {}): ChatTopicMetadata => ({
+ boundDeviceId: 'dev-1',
+ workingDirectory: WT,
+ workingDirectoryConfig: {
+ git: { activeWorktree: WT, autoCreated: true, branch: BRANCH, isWorktree: true },
+ path: '/code/repo',
+ repoType: 'github',
+ sessionPath: WT,
+ },
+ ...extra,
+});
+
+const insert = (
+ id: string,
+ metadata: ChatTopicMetadata,
+ extra: { isDeleted?: boolean; status?: Status; userId?: string; workspaceId?: string } = {},
+) =>
+ db.insert(topics).values({
+ deletedAt: extra.isDeleted ? new Date() : null,
+ id,
+ isDeleted: extra.isDeleted ?? null,
+ metadata,
+ status: extra.status ?? 'completed',
+ userId: extra.userId ?? userId,
+ workspaceId: extra.workspaceId ?? null,
+ });
+
+const entryOf = async (id: string) =>
+ (await db.select().from(topics).where(eq(topics.id, id)))[0]?.metadata?.ownedWorktrees?.[0];
+
+let gateway: {
+ cleanupOwnedWorktree: ReturnType<typeof vi.fn>;
+ restoreOwnedWorktree: ReturnType<typeof vi.fn>;
+};
+let now: Date;
+const service = () =>
+ new WorktreeCleanupService(db, userId, undefined, { gateway: gateway as any, now: () => now });
+
+const answers = (result: OwnedWorktreeCleanupResult) =>
+ gateway.cleanupOwnedWorktree.mockResolvedValue(result);
+
+beforeEach(async () => {
+ now = new Date('2026-11-17T00:00:00.000Z');
+ gateway = { cleanupOwnedWorktree: vi.fn(), restoreOwnedWorktree: vi.fn() };
+ await db.insert(users).values({ id: userId });
+});
+
+afterEach(async () => {
+ await db.delete(topics).where(eq(topics.userId, userId));
+ await db.delete(users).where(inArray(users.id, [userId]));
+});
+
+describe('retireTopics — cleaning up', () => {
+ it('removes a clean worktree of an archived topic on its device and records it', async () => {
+ await insert('t1', autoCreated());
+ answers({ branch: BRANCH, outcome: 'removed' });
+
+ const summary = await service().retireTopics(['t1'], 'archived', { t1: 'active' });
+
+ expect(gateway.cleanupOwnedWorktree).toHaveBeenCalledWith({
+ deviceId: 'dev-1',
+ discard: false,
+ sourcePath: '/code/repo',
+ userId,
+ workspaceId: undefined,
+ worktreePath: WT,
+ });
+ expect(summary.results).toEqual({ [`t1:${WT}`]: 'removed' });
+ expect(await entryOf('t1')).toMatchObject({
+ branch: BRANCH,
+ cleanup: { state: 'removed', trigger: 'archived' },
+ path: WT,
+ });
+ });
+
+ it('cleans up a trashed topic too', async () => {
+ await insert('t-trash', autoCreated(), { isDeleted: true, status: 'active' });
+ answers({ outcome: 'removed' });
+ await service().retireTopics(['t-trash'], 'trashed');
+ expect((await entryOf('t-trash'))?.cleanup).toMatchObject({
+ state: 'removed',
+ trigger: 'trashed',
+ });
+ });
+
+ it('keeps a dirty worktree and records the file count', async () => {
+ await insert('t-dirty', autoCreated());
+ answers({ branch: BRANCH, dirtyFiles: 3, outcome: 'dirty' });
+ await service().retireTopics(['t-dirty'], 'archived');
+ expect((await entryOf('t-dirty'))?.cleanup).toMatchObject({
+ dirtyFiles: 3,
+ state: 'keptDirty',
+ });
+ });
+
+ it("records a worktree kept for its submodules' unpushed commits", async () => {
+ await insert('t-sub', autoCreated());
+ answers({ branch: BRANCH, dirtyFiles: 0, outcome: 'dirty', unpushedSubmodules: 1 });
+ await service().retireTopics(['t-sub'], 'archived');
+ expect((await entryOf('t-sub'))?.cleanup).toMatchObject({
+ reason: 'submoduleCommits',
+ state: 'keptDirty',
+ });
+ });
+
+ it('leaves a locked worktree unmanaged', async () => {
+ await insert('t-lock', autoCreated());
+ answers({ outcome: 'locked' });
+ await service().retireTopics(['t-lock'], 'archived');
+ expect((await entryOf('t-lock'))?.cleanup).toBeUndefined();
+ });
+
+ it('records a refused guard as failed and never retries it automatically', async () => {
+ await insert('t-refused', autoCreated());
+ answers({ error: 'Not a worktree of the source repository', outcome: 'refused' });
+ await service().retireTopics(['t-refused'], 'archived');
+ expect((await entryOf('t-refused'))?.cleanup).toMatchObject({ state: 'failed' });
+
+ gateway.cleanupOwnedWorktree.mockClear();
+ await service().retireTopics(['t-refused'], 'archived');
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('does nothing for topics without an owned worktree', async () => {
+ await insert('t-plain', { workingDirectoryConfig: { path: '/code/repo' } });
+ expect((await service().retireTopics(['t-plain'], 'archived')).results).toEqual({});
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+});
+
+describe('retireTopics — not cleaning up', () => {
+ it.each<[string, Status, Status | undefined]>([
+ ['running when archived', 'completed', 'running'],
+ ['waiting on the user when archived', 'completed', 'waitingForHuman'],
+ ])('holds a topic that was %s', async (_, status, previous) => {
+ await insert('t-held', autoCreated(), { status });
+ const summary = await service().retireTopics(['t-held'], 'archived', { 't-held': previous });
+ expect(summary.results[`t-held:${WT}`]).toBe('held');
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('holds a trashed topic whose run is still live', async () => {
+ await insert('t-run', autoCreated({ runningOperation: { operationId: 'op' } as any }), {
+ isDeleted: true,
+ status: 'running',
+ });
+ await service().retireTopics(['t-run'], 'trashed');
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('holds a topic restored before the cleanup ran', async () => {
+ await insert('t-back', autoCreated(), { status: 'active' });
+ await service().retireTopics(['t-back'], 'archived');
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('skips a worktree the user chose to keep', async () => {
+ await insert(
+ 't-kept',
+ autoCreated({
+ ownedWorktrees: [
+ {
+ branch: BRANCH,
+ cleanup: { at: 'x', state: 'kept' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ }),
+ );
+ await service().retireTopics(['t-kept'], 'archived');
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('holds a worktree another live topic still works in, and cleans it once that one retires', async () => {
+ await insert('owner', autoCreated());
+ // A handoff that continues in the owner's worktree.
+ await insert(
+ 'follower',
+ { workingDirectoryConfig: { git: { activeWorktree: WT }, path: '/code/repo' } },
+ { status: 'active' },
+ );
+ answers({ outcome: 'removed' });
+
+ expect((await service().retireTopics(['owner'], 'archived')).results).toEqual({
+ [`owner:${WT}`]: 'held',
+ });
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+
+ await db.update(topics).set({ status: 'completed' }).where(eq(topics.id, 'follower'));
+ expect((await service().retireTopics(['follower'], 'archived')).results).toEqual({
+ [`owner:${WT}`]: 'removed',
+ });
+ });
+});
+
+describe('offline devices', () => {
+ it('marks the cleanup pending when the device is offline, and runs it when it connects', async () => {
+ await insert('t-off', autoCreated());
+ answers({ error: 'Device is offline', outcome: 'unreachable' });
+ await service().retireTopics(['t-off'], 'archived');
+ expect((await entryOf('t-off'))?.cleanup).toMatchObject({
+ reason: 'deviceOffline',
+ state: 'pending',
+ trigger: 'archived',
+ });
+
+ answers({ outcome: 'removed' });
+ const summary = await service().runPendingForDevice('dev-1');
+ expect(summary.results).toEqual({ [`t-off:${WT}`]: 'removed' });
+ expect((await entryOf('t-off'))?.cleanup?.state).toBe('removed');
+ });
+
+ it('flags a device too old for the RPC', async () => {
+ await insert('t-old', autoCreated());
+ answers({ error: 'Unknown device RPC method', outcome: 'unreachable', outdated: true });
+ await service().retireTopics(['t-old'], 'archived');
+ expect((await entryOf('t-old'))?.cleanup).toMatchObject({
+ reason: 'deviceOutdated',
+ state: 'pending',
+ });
+ });
+
+ it("only drains the connecting device's cleanups", async () => {
+ await insert('t-other', autoCreated({ boundDeviceId: 'dev-2' }));
+ answers({ outcome: 'unreachable' });
+ await service().retireTopics(['t-other'], 'archived');
+ gateway.cleanupOwnedWorktree.mockClear();
+
+ await service().runPendingForDevice('dev-1');
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('drops a pending cleanup of a topic restored meanwhile', async () => {
+ await insert('t-restored', autoCreated());
+ answers({ outcome: 'unreachable' });
+ await service().retireTopics(['t-restored'], 'archived');
+ await db.update(topics).set({ status: 'active' }).where(eq(topics.id, 't-restored'));
+ gateway.cleanupOwnedWorktree.mockClear();
+
+ await service().runPendingForDevice('dev-1');
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ expect((await entryOf('t-restored'))?.cleanup).toBeUndefined();
+ });
+
+ it('a desktop without a gateway device id claims its cleanups and reports them back', async () => {
+ await insert('t-anon', autoCreated({ boundDeviceId: undefined }));
+ await service().retireTopics(['t-anon'], 'archived');
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ expect((await entryOf('t-anon'))?.cleanup?.state).toBe('pending');
+
+ const claimed = await service().claimLocalCleanups(undefined);
+ expect(claimed).toEqual([expect.objectContaining({ discard: false, topicId: 't-anon' })]);
+ expect((await entryOf('t-anon'))?.cleanup?.state).toBe('running');
+ // A second executor gets nothing while the claim is fresh…
+ expect(await service().claimLocalCleanups(undefined)).toEqual([]);
+ // …but takes over a claim whose executor died.
+ now = new Date(now.getTime() + STALE_CLAIM_MS + 1);
+ expect(await service().claimLocalCleanups(undefined)).toHaveLength(1);
+
+ await service().recordCleanupResult('t-anon', WT, 'archived', { outcome: 'removed' });
+ expect((await entryOf('t-anon'))?.cleanup?.state).toBe('removed');
+ });
+});
+
+describe('discard / keep', () => {
+ const keptDirty = () =>
+ autoCreated({
+ ownedWorktrees: [
+ {
+ branch: BRANCH,
+ cleanup: { at: 'x', dirtyFiles: 2, state: 'keptDirty', trigger: 'archived' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ });
+
+ it('discards a kept-dirty worktree with force on its device', async () => {
+ await insert('t-discard', keptDirty());
+ answers({ outcome: 'removed' });
+ const written = await service().discard('t-discard', WT);
+ expect(gateway.cleanupOwnedWorktree).toHaveBeenCalledWith(
+ expect.objectContaining({ discard: true, worktreePath: WT }),
+ );
+ expect(written?.cleanup).toMatchObject({ state: 'removed', trigger: 'discarded' });
+ });
+
+ it('only claims a discard the desktop runs itself', async () => {
+ await insert('t-local', keptDirty());
+ const claimed = await service().discard('t-local', WT, { local: true });
+ expect(claimed?.cleanup).toMatchObject({ state: 'running', trigger: 'discarded' });
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('never discards a live worktree the cleanup has not set aside', async () => {
+ await insert('t-live-discard', autoCreated(), { status: 'active' });
+ await expect(service().discard('t-live-discard', WT)).resolves.toBeUndefined();
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ expect((await entryOf('t-live-discard'))?.cleanup).toBeUndefined();
+ });
+
+ it("refuses to discard under a live run, its own or another topic's in the folder", async () => {
+ await insert(
+ 't-run-discard',
+ { ...keptDirty(), runningOperation: { operationId: 'op' } as any },
+ {
+ status: 'running',
+ },
+ );
+ await expect(service().discard('t-run-discard', WT)).resolves.toBeUndefined();
+
+ await insert('t-quiet-discard', keptDirty());
+ await insert(
+ 't-neighbour',
+ { workingDirectoryConfig: { git: { activeWorktree: WT }, path: '/code/repo' } },
+ { status: 'active' },
+ );
+ await expect(service().discard('t-quiet-discard', WT)).resolves.toBeUndefined();
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('keep stops every later automatic cleanup', async () => {
+ await insert('t-keep', keptDirty());
+ expect((await service().keep('t-keep', WT))?.cleanup?.state).toBe('kept');
+ await service().retireTopics(['t-keep'], 'archived');
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+});
+
+describe('restore', () => {
+ const removed = (extra: Partial<ChatTopicMetadata> = {}) =>
+ autoCreated({
+ ownedWorktrees: [
+ {
+ branch: BRANCH,
+ cleanup: { at: 'x', state: 'removed', trigger: 'trashed' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ ...extra,
+ });
+
+ it('checks the branch out again at the same path and clears the record', async () => {
+ await insert('t-restore', removed(), { status: 'active' });
+ gateway.restoreOwnedWorktree.mockResolvedValue({ outcome: 'restored' });
+
+ await expect(service().restore('t-restore', WT)).resolves.toEqual({ outcome: 'restored' });
+ expect(gateway.restoreOwnedWorktree).toHaveBeenCalledWith(
+ expect.objectContaining({ branch: BRANCH, deviceId: 'dev-1', worktreePath: WT }),
+ );
+ expect((await entryOf('t-restore'))?.cleanup).toBeUndefined();
+ const [row] = await db.select().from(topics).where(eq(topics.id, 't-restore'));
+ expect(row.metadata?.workingDirectoryConfig?.sessionPath).toBe(WT);
+ });
+
+ it('records a restore the desktop ran over IPC without calling the device', async () => {
+ await insert('t-ipc', removed({ boundDeviceId: undefined }), { status: 'active' });
+ await expect(
+ service().restore('t-ipc', WT, { result: { outcome: 'restored' } }),
+ ).resolves.toEqual({
+ outcome: 'restored',
+ });
+ expect(gateway.restoreOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('falls back to the source repository when the branch is gone', async () => {
+ await insert('t-gone', removed(), { status: 'active' });
+ gateway.restoreOwnedWorktree.mockResolvedValue({ outcome: 'branchMissing' });
+
+ await expect(service().restore('t-gone', WT)).resolves.toEqual({ outcome: 'branchMissing' });
+ const [row] = await db.select().from(topics).where(eq(topics.id, 't-gone'));
+ expect(row.metadata?.workingDirectory).toBe('/code/repo');
+ expect(row.metadata?.workingDirectoryConfig).toEqual({
+ path: '/code/repo',
+ repoType: 'github',
+ });
+ expect(row.metadata?.ownedWorktrees?.[0]?.cleanup).toMatchObject({
+ reason: 'branchMissing',
+ state: 'removed',
+ });
+ });
+
+ it('makes a kept-dirty worktree live again when its topic comes back', async () => {
+ await insert(
+ 't-kept-back',
+ autoCreated({
+ ownedWorktrees: [
+ {
+ branch: BRANCH,
+ cleanup: { at: 'x', dirtyFiles: 1, state: 'keptDirty', trigger: 'archived' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ }),
+ { status: 'active' },
+ );
+ await expect(service().restore('t-kept-back', WT)).resolves.toEqual({ outcome: 'restored' });
+ expect((await entryOf('t-kept-back'))?.cleanup).toBeUndefined();
+ expect(gateway.restoreOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('asks the device after a failed cleanup instead of assuming the folder is there', async () => {
+ const failed = (branch?: string) =>
+ autoCreated({
+ ownedWorktrees: [
+ {
+ ...(branch && { branch }),
+ cleanup: { at: 'x', reason: 'Worktree cleanup timed out', state: 'failed' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ });
+ await insert('t-failed', failed(BRANCH), { status: 'active' });
+ gateway.restoreOwnedWorktree.mockResolvedValue({ outcome: 'restored' });
+ await expect(service().restore('t-failed', WT)).resolves.toEqual({ outcome: 'restored' });
+ expect(gateway.restoreOwnedWorktree).toHaveBeenCalledTimes(1);
+ expect((await entryOf('t-failed'))?.cleanup).toBeUndefined();
+
+ // Without a branch there is nothing to check out, but no reason to give
+ // the worktree up either.
+ await insert('t-failed-nobranch', failed(), { status: 'active' });
+ await expect(service().restore('t-failed-nobranch', WT)).resolves.toEqual({
+ outcome: 'restored',
+ });
+ const [row] = await db.select().from(topics).where(eq(topics.id, 't-failed-nobranch'));
+ expect(row.metadata?.workingDirectoryConfig?.sessionPath).toBe(WT);
+ });
+
+ it('is a no-op for a worktree that was never removed', async () => {
+ await insert('t-live', autoCreated(), { status: 'active' });
+ await expect(service().restore('t-live', WT)).resolves.toEqual({ outcome: 'restored' });
+ expect(gateway.restoreOwnedWorktree).not.toHaveBeenCalled();
+ });
+});
+
+describe('review follow-ups', () => {
+ const memberId = 'worktree-cleanup-member';
+ const workspaceId = 'worktree-cleanup-ws';
+ const removedOn = (extra: Partial<ChatTopicMetadata> = {}) =>
+ autoCreated({
+ ownedWorktrees: [
+ {
+ branch: BRANCH,
+ cleanup: { at: now.toISOString(), state: 'running', trigger: 'archived' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ ...extra,
+ });
+
+ it("presents the creation receipt only for its creator's own topic", async () => {
+ const previous = process.env.KEY_VAULTS_SECRET;
+ process.env.KEY_VAULTS_SECRET = 'test-secret';
+ try {
+ const { issueWorktreeReceipt } = await import('./receipt');
+ const receipt = issueWorktreeReceipt(userId)!;
+ const withReceipt = (extra: Partial<ChatTopicMetadata> = {}) =>
+ autoCreated({
+ workingDirectoryConfig: {
+ git: {
+ activeWorktree: WT,
+ autoCreated: true,
+ branch: BRANCH,
+ ownerNonce: receipt.nonce,
+ ownerToken: receipt.token,
+ },
+ path: '/code/repo',
+ sessionPath: WT,
+ },
+ ...extra,
+ });
+ await insert('t-receipt', withReceipt());
+ answers({ outcome: 'removed' });
+ await service().retireTopics(['t-receipt'], 'archived');
+ expect(gateway.cleanupOwnedWorktree).toHaveBeenLastCalledWith(
+ expect.objectContaining({ ownerToken: receipt.token }),
+ );
+
+ await db.update(topics).set({ status: 'active' }).where(eq(topics.id, 't-receipt'));
+ gateway.restoreOwnedWorktree.mockResolvedValue({ outcome: 'restored' });
+ await service().restore('t-receipt', WT);
+ expect(gateway.restoreOwnedWorktree).toHaveBeenCalledWith(
+ expect.objectContaining({ ownerToken: receipt.token }),
+ );
+
+ // The same receipt copied into another user's topic is never presented.
+ const otherId = 'worktree-cleanup-copier';
+ await db.insert(users).values({ id: otherId });
+ try {
+ await insert('t-copied', withReceipt(), { userId: otherId });
+ const copier = new WorktreeCleanupService(db, otherId, undefined, {
+ gateway: gateway as any,
+ now: () => now,
+ });
+ await copier.retireTopics(['t-copied'], 'archived');
+ expect(gateway.cleanupOwnedWorktree).toHaveBeenLastCalledWith(
+ expect.objectContaining({ ownerToken: undefined }),
+ );
+ } finally {
+ await db.delete(topics).where(eq(topics.userId, otherId));
+ await db.delete(users).where(eq(users.id, otherId));
+ }
+ } finally {
+ process.env.KEY_VAULTS_SECRET = previous;
+ }
+ });
+
+ it('only hands the desktop the jobs of topics the caller may act on', async () => {
+ const pending = autoCreated({
+ boundDeviceId: undefined,
+ ownedWorktrees: [
+ {
+ cleanup: { at: 'x', state: 'pending', trigger: 'archived' },
+ createdAt: 'y',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ });
+ await insert('t-allowed', pending);
+ await insert('t-denied', pending);
+ const claimed = await service().claimLocalCleanups(undefined, {
+ canClaim: async (row) => row.id === 't-allowed',
+ });
+ expect(claimed.map((job) => job.topicId)).toEqual(['t-allowed']);
+ expect((await entryOf('t-denied'))?.cleanup?.state).toBe('pending');
+ });
+
+ it('records the branch the device reports, not a stale one from creation', async () => {
+ await insert('t-renamed', autoCreated());
+ answers({ branch: 'lobehub/renamed', outcome: 'removed' });
+ await service().retireTopics(['t-renamed'], 'archived');
+ expect((await entryOf('t-renamed'))?.branch).toBe('lobehub/renamed');
+ });
+
+ it('makes a restore wait while a cleanup is still deleting the folder', async () => {
+ await insert('t-busy', removedOn(), { status: 'active' });
+ await expect(service().restore('t-busy', WT)).resolves.toEqual({ outcome: 'busy' });
+ expect(gateway.restoreOwnedWorktree).not.toHaveBeenCalled();
+
+ // The cleanup lands; the next ask checks the worktree out again.
+ await service().recordCleanupResult('t-busy', WT, 'archived', { outcome: 'removed' });
+ gateway.restoreOwnedWorktree.mockResolvedValue({ outcome: 'restored' });
+ await expect(service().restore('t-busy', WT)).resolves.toEqual({ outcome: 'restored' });
+ expect(gateway.restoreOwnedWorktree).toHaveBeenCalledTimes(1);
+ });
+
+ it('cancels a cleanup that never ran when the topic comes back', async () => {
+ await insert('t-cancel', autoCreated(), { status: 'active' });
+ await db
+ .update(topics)
+ .set({
+ metadata: autoCreated({
+ ownedWorktrees: [
+ {
+ branch: BRANCH,
+ cleanup: { at: 'x', state: 'pending', trigger: 'archived' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ }),
+ })
+ .where(eq(topics.id, 't-cancel'));
+ await expect(service().restore('t-cancel', WT)).resolves.toEqual({ outcome: 'restored' });
+ expect((await entryOf('t-cancel'))?.cleanup).toBeUndefined();
+ gateway.cleanupOwnedWorktree.mockClear();
+ await service().runPendingForDevice('dev-1');
+ expect(gateway.cleanupOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it('hands a removed worktree on this desktop back for an IPC re-checkout', async () => {
+ await insert(
+ 't-local',
+ autoCreated({
+ ownedWorktrees: [
+ {
+ branch: 'lobehub/renamed',
+ cleanup: { at: 'x', state: 'removed', trigger: 'trashed' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ }),
+ { status: 'active' },
+ );
+ // The receipt never travels back in the answer.
+ await expect(service().restore('t-local', WT, { local: true })).resolves.toEqual({
+ branch: 'lobehub/renamed',
+ outcome: 'needsLocal',
+ });
+ expect(gateway.restoreOwnedWorktree).not.toHaveBeenCalled();
+ });
+
+ it("drains a workspace device's pending cleanups for every member's topics", async () => {
+ await db.insert(users).values({ id: memberId });
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+ try {
+ const pending = (deviceId?: string) =>
+ autoCreated({
+ ownedWorktrees: [
+ {
+ branch: BRANCH,
+ cleanup: { at: 'x', state: 'pending', trigger: 'archived' },
+ createdAt: 'y',
+ ...(deviceId && { deviceId }),
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ });
+ // A teammate archived a topic on the shared device while it was offline.
+ await insert('t-member', pending('dev-ws'), { userId: memberId, workspaceId });
+ // A teammate's desktop-only record never runs on this machine.
+ await insert('t-member-local', pending(), { userId: memberId, workspaceId });
+ answers({ outcome: 'removed' });
+
+ const enroller = new WorktreeCleanupService(db, userId, workspaceId, {
+ gateway: gateway as any,
+ now: () => now,
+ });
+ expect((await enroller.runPendingForDevice('dev-ws')).results).toEqual({
+ [`t-member:${WT}`]: 'removed',
+ });
+ expect(await enroller.claimLocalCleanups(undefined)).toEqual([]);
+ } finally {
+ await db.delete(topics).where(eq(topics.workspaceId, workspaceId));
+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));
+ await db.delete(users).where(eq(users.id, memberId));
+ }
+ });
+});
+
+describe('restoreOwnedWorktreeBeforeServerRun', () => {
+ const removed = () =>
+ autoCreated({
+ ownedWorktrees: [
+ {
+ branch: BRANCH,
+ cleanup: { at: 'x', state: 'removed', trigger: 'archived' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ });
+
+ it('brings the worktree back before a turn the server starts on its own', async () => {
+ await insert('t-server-run', removed(), { status: 'completed' });
+ gateway.restoreOwnedWorktree.mockResolvedValue({ outcome: 'restored' });
+ // The default gateway is the module singleton; route it through the mock.
+ const { deviceGateway } = await import('@/server/services/deviceGateway');
+ Object.assign(deviceGateway, gateway);
+
+ const metadata = (await db.select().from(topics).where(eq(topics.id, 't-server-run')))[0]
+ .metadata;
+ await expect(
+ restoreOwnedWorktreeBeforeServerRun({ db, metadata, topicId: 't-server-run', userId }),
+ ).resolves.toBeUndefined();
+ expect(gateway.restoreOwnedWorktree).toHaveBeenCalledWith(
+ expect.objectContaining({ branch: BRANCH, worktreePath: WT }),
+ );
+ expect((await entryOf('t-server-run'))?.cleanup).toBeUndefined();
+ });
+
+ it('hands back the source-repo directory when the branch is gone', async () => {
+ const { deviceGateway } = await import('@/server/services/deviceGateway');
+ Object.assign(deviceGateway, gateway);
+ await insert('t-server-gone', removed(), { status: 'completed' });
+ gateway.restoreOwnedWorktree.mockResolvedValue({ outcome: 'branchMissing' });
+ const metadata = (await db.select().from(topics).where(eq(topics.id, 't-server-gone')))[0]
+ .metadata;
+ const next = await restoreOwnedWorktreeBeforeServerRun({
+ db,
+ metadata,
+ topicId: 't-server-gone',
+ userId,
+ });
+ expect(next?.metadata?.workingDirectoryConfig).toEqual({
+ path: '/code/repo',
+ repoType: 'github',
+ });
+ });
+
+ it('does nothing for a topic without an app-created worktree', async () => {
+ await expect(
+ restoreOwnedWorktreeBeforeServerRun({
+ db,
+ metadata: { workingDirectoryConfig: { path: '/code/repo' } },
+ topicId: 'none',
+ userId,
+ }),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/worktreeCleanup/index.ts b/apps/server/src/services/worktreeCleanup/index.ts
new file mode 100644
index 00000000000..368e9cc2c17
--- /dev/null
+++ b/apps/server/src/services/worktreeCleanup/index.ts
@@ -0,0 +1,618 @@
+import type {
+ ChatTopicMetadata,
+ OwnedWorktree,
+ OwnedWorktreeCleanup,
+ OwnedWorktreeCleanupResult,
+ OwnedWorktreeCleanupTrigger,
+ OwnedWorktreeRestoreResult,
+ OwnedWorktreeTopicRow,
+} from '@lobechat/types';
+import {
+ getTopicWorktreePaths,
+ isRetiredTopicStatus,
+ OWNED_WORKTREE_HOLD_STATUSES,
+ resolveOwnedWorktrees,
+ SUBMODULE_COMMITS_REASON,
+} from '@lobechat/types';
+import debug from 'debug';
+
+import { TopicModel } from '@/database/models/topic';
+import type { LobeChatDatabase } from '@/database/type';
+import { deviceGateway as defaultGateway } from '@/server/services/deviceGateway';
+import { afterUnscoped } from '@/server/utils/scheduleAfterResponse';
+
+import { attestedOwnerToken } from './receipt';
+
+const log = debug('lobe-server:worktree-cleanup');
+
+/**
+ * Automatic cleanup of the worktrees the app created for a conversation
+ * (Better Coding Experience "New worktree"), mirroring how Claude Desktop
+ * tidies a session's worktree when it is archived:
+ *
+ * - archiving a topic (status `completed`) or moving it to the recycle bin
+ * removes its worktree's folder, silently; the branch is always kept;
+ * - a worktree with uncommitted work is kept (`keptDirty`) and surfaced in
+ * the topic's Overview, where the user can discard it or keep it for good;
+ * - nothing is cleaned while the topic runs or waits on the user, while
+ * another live topic still works in the folder, after the user chose to
+ * keep it, or when git has the worktree locked;
+ * - a device that cannot be reached keeps the cleanup `pending` until it
+ * next connects (or the desktop next starts) — no periodic polling;
+ * - a topic brought back runs `restore` before its next turn, checking the
+ * branch out again at the same path.
+ *
+ * The device runs every check that decides whether a folder may go
+ * (`cleanupOwnedWorktree` in local-file-shell); this service only decides
+ * WHEN, and records what happened in `metadata.ownedWorktrees`.
+ */
+
+/** A claim older than this is an executor that died; it is retried. */
+export const STALE_CLAIM_MS = 10 * 60 * 1000;
+
+type Gateway = Pick<typeof defaultGateway, 'cleanupOwnedWorktree' | 'restoreOwnedWorktree'>;
+
+export interface WorktreeCleanupDeps {
+ gateway?: Gateway;
+ now?: () => Date;
+}
+
+/** One cleanup the desktop runs itself over IPC (no gateway to reach it). */
+export interface LocalWorktreeCleanup {
+ discard: boolean;
+ entry: OwnedWorktree;
+ topicId: string;
+}
+
+export interface WorktreeCleanupSummary {
+ /** `${topicId}:${path}` → state written, for logs and tests. */
+ results: Record<string, OwnedWorktreeCleanup['state'] | 'held' | 'skipped'>;
+}
+
+const key = (topicId: string, path: string) => `${topicId}:${path}`;
+
+/** The record as handed to an executor: its receipt only if this topic's creator holds it. */
+const withAttestedToken = (topicUserId: string, entry: OwnedWorktree): OwnedWorktree => {
+ const { ownerNonce: _nonce, ownerToken: _token, ...rest } = entry;
+ const ownerToken = attestedOwnerToken(topicUserId, entry);
+ return ownerToken ? { ...rest, ownerToken } : rest;
+};
+
+const isHeld = (row: OwnedWorktreeTopicRow, previousStatus?: string | null) =>
+ [row.status, previousStatus].some(
+ (status) => !!status && (OWNED_WORKTREE_HOLD_STATUSES as readonly string[]).includes(status),
+ ) || !!row.metadata?.runningOperation;
+
+/** Archived or in the recycle bin — the only topics whose worktrees may go. */
+const isRetired = (row: OwnedWorktreeTopicRow) =>
+ !!row.isDeleted || isRetiredTopicStatus(row.status);
+
+export class WorktreeCleanupService {
+ private readonly topicModel: TopicModel;
+ private readonly gateway: Gateway;
+ private readonly now: () => Date;
+
+ constructor(
+ db: LobeChatDatabase,
+ private readonly userId: string,
+ private readonly workspaceId?: string,
+ deps: WorktreeCleanupDeps = {},
+ ) {
+ this.topicModel = new TopicModel(db, userId, workspaceId);
+ this.gateway = deps.gateway ?? defaultGateway;
+ this.now = deps.now ?? (() => new Date());
+ }
+
+ private stamp(cleanup: Omit<OwnedWorktreeCleanup, 'at'>): OwnedWorktreeCleanup {
+ return { ...cleanup, at: this.now().toISOString() };
+ }
+
+ private isStaleClaim(cleanup: OwnedWorktreeCleanup | undefined) {
+ return (
+ cleanup?.state === 'running' &&
+ this.now().getTime() - new Date(cleanup.at).getTime() > STALE_CLAIM_MS
+ );
+ }
+
+ /** States an automatic cleanup may start from. */
+ private canAutoStart(cleanup: OwnedWorktreeCleanup | undefined) {
+ return !cleanup || cleanup.state === 'pending' || this.isStaleClaim(cleanup);
+ }
+
+ /**
+ * Compare-and-set the record to `running`, so concurrent executors (the
+ * archive hook, a device reconnect, a desktop on startup) never run the
+ * same cleanup twice. Returns the claimed record, or undefined.
+ */
+ private claim(
+ topicId: string,
+ path: string,
+ trigger: OwnedWorktreeCleanupTrigger,
+ allowed: (entry: OwnedWorktree, row: OwnedWorktreeTopicRow) => boolean,
+ ) {
+ return this.topicModel.updateOwnedWorktree(topicId, path, (entry, row) =>
+ allowed(entry, row)
+ ? { ...entry, cleanup: this.stamp({ state: 'running', trigger }) }
+ : undefined,
+ );
+ }
+
+ /** Write a device's answer to a claimed cleanup. */
+ async recordCleanupResult(
+ topicId: string,
+ path: string,
+ trigger: OwnedWorktreeCleanupTrigger,
+ result: OwnedWorktreeCleanupResult,
+ ): Promise<OwnedWorktree | undefined> {
+ return this.topicModel.updateOwnedWorktree(topicId, path, (entry) => {
+ // The device reads the branch the worktree is on now: it wins over the
+ // one recorded at creation, which a later rename leaves stale.
+ const branch = result.branch ?? entry.branch;
+ const next = { ...entry, ...(branch && { branch }) };
+ switch (result.outcome) {
+ case 'removed': {
+ return { ...next, cleanup: this.stamp({ state: 'removed', trigger }) };
+ }
+ case 'dirty': {
+ return {
+ ...next,
+ cleanup: this.stamp({
+ dirtyFiles: result.dirtyFiles,
+ ...(result.unpushedSubmodules && { reason: SUBMODULE_COMMITS_REASON }),
+ state: 'keptDirty',
+ trigger,
+ }),
+ };
+ }
+ case 'locked': {
+ // `git worktree lock` is the user's own "keep": leave it unmanaged.
+ const { cleanup: _drop, ...rest } = next;
+ return rest;
+ }
+ case 'unreachable': {
+ return {
+ ...next,
+ cleanup: this.stamp({
+ reason: result.outdated ? 'deviceOutdated' : 'deviceOffline',
+ state: 'pending',
+ trigger,
+ }),
+ };
+ }
+ default: {
+ return {
+ ...next,
+ cleanup: this.stamp({ reason: result.error, state: 'failed', trigger }),
+ };
+ }
+ }
+ });
+ }
+
+ /**
+ * Run one claimed cleanup on its device over the gateway. A record without
+ * a device (a desktop that never registered with the gateway) waits as
+ * `pending` for that desktop to run it.
+ */
+ private async execute(
+ topicId: string,
+ entry: OwnedWorktree,
+ trigger: OwnedWorktreeCleanupTrigger,
+ topicUserId: string,
+ ): Promise<OwnedWorktree | undefined> {
+ if (!entry.deviceId)
+ return this.recordCleanupResult(topicId, entry.path, trigger, {
+ error: 'Waiting for the desktop app',
+ outcome: 'unreachable',
+ });
+
+ const result = await this.gateway.cleanupOwnedWorktree({
+ deviceId: entry.deviceId,
+ discard: trigger === 'discarded',
+ // Presented only when issued to this topic's creator (see `./receipt`).
+ ownerToken: attestedOwnerToken(topicUserId, entry),
+ sourcePath: entry.sourcePath,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ worktreePath: entry.path,
+ });
+ log('cleanup %s on %s → %o', entry.path, entry.deviceId, result);
+ return this.recordCleanupResult(topicId, entry.path, trigger, result);
+ }
+
+ /** Whether a run is going on in this folder: this topic's own, or another live topic's. */
+ private async inUse(topicId: string, path: string) {
+ const [row] = await this.topicModel.findOwnedWorktreeTopics([topicId]);
+ return (!!row && isHeld(row)) || this.inUseElsewhere(topicId, path);
+ }
+
+ /** Whether another live topic still works in this folder. */
+ private async inUseElsewhere(topicId: string, path: string) {
+ return (
+ (await this.topicModel.countLiveTopicsUsingWorktree({ excludeIds: [topicId], path })) > 0
+ );
+ }
+
+ /**
+ * Try the automatic cleanup of every worktree one retired topic owns.
+ * Re-reads the row, so a topic restored meanwhile is left alone.
+ */
+ private async cleanupTopic(
+ row: OwnedWorktreeTopicRow,
+ trigger: OwnedWorktreeCleanupTrigger,
+ summary: WorktreeCleanupSummary,
+ previousStatus?: string | null,
+ ) {
+ for (const entry of resolveOwnedWorktrees(row.metadata)) {
+ const id = key(row.id, entry.path);
+ if (!isRetired(row) || isHeld(row, previousStatus)) {
+ summary.results[id] = 'held';
+ continue;
+ }
+ if (!this.canAutoStart(entry.cleanup)) {
+ summary.results[id] = 'skipped';
+ continue;
+ }
+ if (await this.inUseElsewhere(row.id, entry.path)) {
+ summary.results[id] = 'held';
+ continue;
+ }
+ const claimed = await this.claim(
+ row.id,
+ entry.path,
+ trigger,
+ (current, fresh) => this.canAutoStart(current.cleanup) && isRetired(fresh),
+ );
+ if (!claimed) {
+ summary.results[id] = 'skipped';
+ continue;
+ }
+ const written = await this.execute(row.id, claimed, trigger, row.userId).catch((error) => {
+ log('cleanup of %s failed: %O', entry.path, error);
+ return this.recordCleanupResult(row.id, entry.path, trigger, {
+ error: (error as Error)?.message,
+ outcome: 'error',
+ });
+ });
+ summary.results[id] = written?.cleanup?.state ?? 'skipped';
+ }
+ }
+
+ /**
+ * Topics were archived or moved to the recycle bin: clean up the worktrees
+ * they own, and those of already-retired topics that waited only because one
+ * of these was still working in their folder. `previousStatus` is the status
+ * before an archive overwrote it, so a run that was live is still held.
+ */
+ async retireTopics(
+ topicIds: string[],
+ trigger: 'archived' | 'trashed',
+ previousStatus: Record<string, string | null | undefined> = {},
+ ): Promise<WorktreeCleanupSummary> {
+ const summary: WorktreeCleanupSummary = { results: {} };
+ const rows = await this.topicModel.findOwnedWorktreeTopics(topicIds);
+
+ for (const row of rows) {
+ await this.cleanupTopic(row, trigger, summary, previousStatus[row.id]);
+ }
+
+ // A worktree another topic was still using waited (`held`); now that this
+ // topic is retired too, its owner may be cleaned up.
+ const paths = new Set(rows.flatMap((row) => getTopicWorktreePaths(row.metadata)));
+ const seen = new Set(topicIds);
+ for (const path of paths) {
+ for (const owner of await this.topicModel.findOwnersOfWorktree(path)) {
+ if (seen.has(owner.id) || !isRetired(owner)) continue;
+ seen.add(owner.id);
+ await this.cleanupTopic(owner, owner.isDeleted ? 'trashed' : 'archived', summary);
+ }
+ }
+ return summary;
+ }
+
+ /**
+ * Take one waiting cleanup for an executor: claim it, or clear it when the
+ * topic was restored (or another live topic took the folder) meanwhile —
+ * the next archive or trash starts it afresh.
+ */
+ private async takePending(
+ row: OwnedWorktreeTopicRow,
+ entry: OwnedWorktree,
+ ): Promise<{ claimed: OwnedWorktree; trigger: OwnedWorktreeCleanupTrigger } | undefined> {
+ if (entry.cleanup?.state !== 'pending' && !this.isStaleClaim(entry.cleanup)) return;
+ const trigger = entry.cleanup?.trigger ?? (row.isDeleted ? 'trashed' : 'archived');
+ if (
+ trigger !== 'discarded' &&
+ (!isRetired(row) || (await this.inUseElsewhere(row.id, entry.path)))
+ ) {
+ await this.clearCleanup(row.id, entry.path);
+ return;
+ }
+ // A discard waiting on its device still never runs under a live run.
+ if (trigger === 'discarded' && (await this.inUse(row.id, entry.path))) return;
+ const claimed = await this.claim(
+ row.id,
+ entry.path,
+ trigger,
+ (current) => current.cleanup?.state === 'pending' || this.isStaleClaim(current.cleanup),
+ );
+ return claimed && { claimed, trigger };
+ }
+
+ /**
+ * A device connected to the gateway: run the cleanups that waited for it.
+ */
+ async runPendingForDevice(deviceId: string): Promise<WorktreeCleanupSummary> {
+ const summary: WorktreeCleanupSummary = { results: {} };
+ for (const row of await this.topicModel.findPendingOwnedWorktreeTopics(deviceId)) {
+ for (const entry of resolveOwnedWorktrees(row.metadata)) {
+ if (entry.deviceId !== deviceId) continue;
+ const taken = await this.takePending(row, entry);
+ if (!taken) continue;
+ const written = await this.execute(row.id, taken.claimed, taken.trigger, row.userId);
+ summary.results[key(row.id, entry.path)] = written?.cleanup?.state ?? 'skipped';
+ }
+ }
+ return summary;
+ }
+
+ /**
+ * The desktop runs over IPC the cleanups that wait on it — its own device
+ * id's (gateway off) and those recorded without one (never registered).
+ * Claims each before handing it out; the desktop reports every result back
+ * with {@link recordCleanupResult}.
+ */
+ async claimLocalCleanups(
+ deviceId: string | undefined,
+ {
+ canClaim = async () => true,
+ }: {
+ /** The caller's access to the topic; a job it may not act on is left alone. */
+ canClaim?: (row: OwnedWorktreeTopicRow) => Promise<boolean>;
+ } = {},
+ ): Promise<LocalWorktreeCleanup[]> {
+ const claimed: LocalWorktreeCleanup[] = [];
+ const rows = [
+ ...(deviceId ? await this.topicModel.findPendingOwnedWorktreeTopics(deviceId) : []),
+ ...(await this.topicModel.findPendingOwnedWorktreeTopics(undefined)),
+ ];
+ const seen = new Set<string>();
+ for (const row of rows) {
+ for (const entry of resolveOwnedWorktrees(row.metadata)) {
+ if (entry.deviceId && entry.deviceId !== deviceId) continue;
+ const id = key(row.id, entry.path);
+ if (seen.has(id)) continue;
+ seen.add(id);
+ if (!(await canClaim(row))) continue;
+ const taken = await this.takePending(row, entry);
+ if (taken)
+ claimed.push({
+ discard: taken.trigger === 'discarded',
+ entry: withAttestedToken(row.userId, taken.claimed),
+ topicId: row.id,
+ });
+ }
+ }
+ return claimed;
+ }
+
+ private clearCleanup(topicId: string, path: string) {
+ return this.topicModel.updateOwnedWorktree(topicId, path, (entry) => {
+ if (!entry.cleanup) return undefined;
+ const { cleanup: _drop, ...rest } = entry;
+ return rest;
+ });
+ }
+
+ /**
+ * "Discard changes and delete" on a kept worktree. With `local`, only the
+ * claim is taken and the desktop runs it over IPC; otherwise it runs on the
+ * device now, staying pending if the device cannot be reached.
+ */
+ async discard(
+ topicId: string,
+ path: string,
+ { local }: { local?: boolean } = {},
+ ): Promise<OwnedWorktree | undefined> {
+ // Never under a live run: neither this topic's nor another topic's that
+ // works in the same folder.
+ if (await this.inUse(topicId, path)) return undefined;
+ const [row] = await this.topicModel.findOwnedWorktreeTopics([topicId]);
+ if (!row) return undefined;
+ const claimed = await this.claim(
+ topicId,
+ path,
+ 'discarded',
+ // Only a worktree the cleanup already set aside (kept, kept dirty,
+ // failed) or a discard still waiting on its device: never a live one.
+ (entry) =>
+ ['failed', 'kept', 'keptDirty'].includes(entry.cleanup?.state ?? '') ||
+ (entry.cleanup?.state === 'pending' && entry.cleanup.trigger === 'discarded') ||
+ this.isStaleClaim(entry.cleanup),
+ );
+ if (!claimed) return undefined;
+ // The desktop runs it over IPC with the receipt, if this topic's creator holds one.
+ if (local) return withAttestedToken(row.userId, claimed);
+ return this.execute(topicId, claimed, 'discarded', row.userId);
+ }
+
+ /** "Keep": never clean this worktree automatically again. */
+ keep(topicId: string, path: string) {
+ return this.topicModel.updateOwnedWorktree(topicId, path, (entry) => ({
+ ...entry,
+ cleanup: this.stamp({ state: 'kept', trigger: entry.cleanup?.trigger }),
+ }));
+ }
+
+ /**
+ * Make a restored topic's worktree usable before its next turn. The record
+ * decides, never the folder alone (a running cleanup may not have deleted
+ * it yet):
+ *
+ * - `running`: a cleanup is deleting it now → `busy`; the caller waits.
+ * - `pending`: it never ran → cancelled, the folder is still there.
+ * - `keptDirty`: the folder is intact → live again, `restored`.
+ * - `removed` / `failed`: run the device's `git worktree add <path> <branch>`
+ * (a no-op for a folder still there; the device first waits out a
+ * deletion in flight); with `local`, answer `needsLocal` so the desktop
+ * runs it over IPC and reports its `result`. A branch that is gone sends
+ * the topic back to its source.
+ * - otherwise the folder is there → `restored`.
+ */
+ async restore(
+ topicId: string,
+ path: string,
+ { local, result }: { local?: boolean; result?: OwnedWorktreeRestoreResult } = {},
+ ): Promise<OwnedWorktreeRestoreResult> {
+ const [row] = await this.topicModel.findOwnedWorktreeTopics([topicId]);
+ const entry = resolveOwnedWorktrees(row?.metadata).find((item) => item.path === path);
+ if (!row || !entry) return { error: 'Unknown worktree', outcome: 'refused' };
+
+ if (!result) {
+ const state = entry.cleanup?.state;
+ if (state === 'running' && !this.isStaleClaim(entry.cleanup)) return { outcome: 'busy' };
+ if (state === 'pending' || state === 'running') {
+ // Cancel only what is still waiting: a claim taken meanwhile wins.
+ const cancelled = await this.topicModel.updateOwnedWorktree(topicId, path, (current) => {
+ if (current.cleanup?.state !== state) return undefined;
+ const { cleanup: _drop, ...rest } = current;
+ return rest;
+ });
+ return cancelled ? { outcome: 'restored' } : { outcome: 'busy' };
+ }
+ // Kept for its uncommitted work: the folder is intact, and the topic
+ // coming back makes it live again (no longer awaiting a choice).
+ if (state === 'keptDirty') {
+ await this.clearCleanup(topicId, path);
+ return { outcome: 'restored' };
+ }
+ // A failed cleanup may have stopped half-way, or still be deleting after
+ // a timeout: ask the device (it waits for a deletion in flight) instead
+ // of assuming the folder is there.
+ if (state !== 'removed' && state !== 'failed') return { outcome: 'restored' };
+ }
+
+ let answer = result;
+ if (!answer) {
+ // Without a branch nothing can be checked out again; a failed cleanup
+ // most likely left the folder, so only a removed one falls back.
+ if (!entry.branch)
+ answer =
+ entry.cleanup?.state === 'failed'
+ ? { outcome: 'restored' }
+ : { outcome: 'branchMissing' };
+ // The desktop holds the receipt in its own copy of the topic; it never
+ // travels back in an answer.
+ else if (local) return { branch: entry.branch, outcome: 'needsLocal' };
+ else if (!entry.deviceId)
+ return { error: 'Restore it from the desktop app', outcome: 'unreachable' };
+ else
+ answer = await this.gateway.restoreOwnedWorktree({
+ branch: entry.branch,
+ deviceId: entry.deviceId,
+ ownerToken: attestedOwnerToken(row.userId, entry),
+ sourcePath: entry.sourcePath,
+ userId: this.userId,
+ workspaceId: this.workspaceId,
+ worktreePath: entry.path,
+ });
+ }
+
+ if (answer.outcome === 'restored') await this.clearCleanup(topicId, path);
+ if (answer.outcome === 'branchMissing') await this.fallBackToSource(row, entry);
+ return answer;
+ }
+
+ /**
+ * The branch is gone, so the worktree cannot come back: the topic continues
+ * in its source repository. The record stays `removed` and no longer matches
+ * the topic's directory, so nothing tries to restore it again.
+ */
+ private async fallBackToSource(row: OwnedWorktreeTopicRow, entry: OwnedWorktree) {
+ const config = row.metadata?.workingDirectoryConfig;
+ const patch: Partial<ChatTopicMetadata> = {
+ workingDirectory: entry.sourcePath,
+ workingDirectoryConfig: {
+ ...(config?.environmentId && { environmentId: config.environmentId }),
+ path: entry.sourcePath,
+ ...(config?.repoType && { repoType: config.repoType }),
+ },
+ };
+ await this.topicModel.updateMetadata(row.id, patch);
+ await this.topicModel.updateOwnedWorktree(row.id, entry.path, (current) => ({
+ ...current,
+ cleanup: this.stamp({
+ reason: 'branchMissing',
+ state: 'removed',
+ trigger: current.cleanup?.trigger,
+ }),
+ }));
+ }
+}
+
+/**
+ * Run {@link WorktreeCleanupService.retireTopics} after the response: archiving
+ * or trashing never waits on a device (a large worktree can take a while).
+ * Unscoped, so it never stalls a step's settlement flush.
+ */
+export const scheduleWorktreeCleanup = (
+ params: {
+ db: LobeChatDatabase;
+ previousStatus?: Record<string, string | null | undefined>;
+ topicIds: string[];
+ trigger: 'archived' | 'trashed';
+ userId: string;
+ workspaceId?: string;
+ },
+ deps?: WorktreeCleanupDeps,
+) => {
+ const { db, previousStatus, topicIds, trigger, userId, workspaceId } = params;
+ if (topicIds.length === 0) return;
+ afterUnscoped(async () => {
+ const summary = await new WorktreeCleanupService(db, userId, workspaceId, deps).retireTopics(
+ topicIds,
+ trigger,
+ previousStatus,
+ );
+ if (Object.keys(summary.results).length > 0) log('%s cleanup: %o', trigger, summary.results);
+ });
+};
+
+const RESTORE_BUSY_WAIT_MS = 120_000;
+const RESTORE_BUSY_POLL_MS = 2000;
+
+/**
+ * Before the server starts a turn on its own (a delegated task reporting back,
+ * a scheduled continuation), bring back the worktree the app created for the
+ * topic if a cleanup removed it — the same step the composer runs before a
+ * send. Waits while a cleanup is still deleting it. Returns the topic as it
+ * now is (a gone branch moves it to its source), or `undefined` when nothing
+ * needed doing.
+ */
+export const restoreOwnedWorktreeBeforeServerRun = async (params: {
+ db: LobeChatDatabase;
+ metadata: ChatTopicMetadata | null | undefined;
+ topicId: string;
+ userId: string;
+ workspaceId?: string;
+}): Promise<{ metadata: ChatTopicMetadata | null | undefined } | undefined> => {
+ const { db, metadata, topicId, userId, workspaceId } = params;
+ const paths = getTopicWorktreePaths(metadata);
+ const entry = resolveOwnedWorktrees(metadata).find((item) => paths.includes(item.path));
+ // The server read this metadata just now: a worktree no cleanup has touched
+ // (or one the user keeps) is simply there, with nothing to ask anyone.
+ if (!entry?.cleanup || entry.cleanup.state === 'kept') return;
+
+ const service = new WorktreeCleanupService(db, userId, workspaceId);
+ const deadline = Date.now() + RESTORE_BUSY_WAIT_MS;
+ let result = await service.restore(topicId, entry.path);
+ while (result.outcome === 'busy' && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, RESTORE_BUSY_POLL_MS));
+ result = await service.restore(topicId, entry.path);
+ }
+ log('server-run restore of %s → %s', entry.path, result.outcome);
+ if (result.outcome !== 'branchMissing') return;
+ // The topic now continues in its source repository.
+ const [row] = await new TopicModel(db, userId, workspaceId).findOwnedWorktreeTopics([topicId]);
+ return { metadata: row?.metadata };
+};
diff --git a/apps/server/src/services/worktreeCleanup/receipt.test.ts b/apps/server/src/services/worktreeCleanup/receipt.test.ts
new file mode 100644
index 00000000000..d34a3c8bb70
--- /dev/null
+++ b/apps/server/src/services/worktreeCleanup/receipt.test.ts
@@ -0,0 +1,35 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { attestedOwnerToken, issueWorktreeReceipt } from './receipt';
+
+describe('worktree creation receipts', () => {
+ const previous = process.env.KEY_VAULTS_SECRET;
+ beforeEach(() => {
+ process.env.KEY_VAULTS_SECRET = 'test-secret';
+ });
+ afterEach(() => {
+ process.env.KEY_VAULTS_SECRET = previous;
+ });
+
+ it('verifies only for the creator it was issued to', () => {
+ const receipt = issueWorktreeReceipt('user-a')!;
+ expect(receipt.token).toMatch(/^[\w-]{16,128}$/);
+ const entry = { ownerNonce: receipt.nonce, ownerToken: receipt.token };
+
+ expect(attestedOwnerToken('user-a', entry)).toBe(receipt.token);
+ // Copied into another member's topic, it proves nothing.
+ expect(attestedOwnerToken('user-b', entry)).toBeUndefined();
+ expect(attestedOwnerToken('user-a', { ...entry, ownerNonce: 'other-nonce' })).toBeUndefined();
+ expect(attestedOwnerToken('user-a', { ownerToken: receipt.token })).toBeUndefined();
+ });
+
+ it('issues and verifies nothing without a server secret', () => {
+ const receipt = issueWorktreeReceipt('user-a')!;
+ delete process.env.KEY_VAULTS_SECRET;
+ expect(issueWorktreeReceipt('user-a')).toBeUndefined();
+ expect(
+ attestedOwnerToken('user-a', { ownerNonce: receipt.nonce, ownerToken: receipt.token }),
+ ).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/worktreeCleanup/receipt.ts b/apps/server/src/services/worktreeCleanup/receipt.ts
new file mode 100644
index 00000000000..2098e045071
--- /dev/null
+++ b/apps/server/src/services/worktreeCleanup/receipt.ts
@@ -0,0 +1,53 @@
+import { createHmac, randomUUID, timingSafeEqual } from 'node:crypto';
+
+import type { OwnedWorktree } from '@lobechat/types';
+
+/**
+ * Creation receipts for the worktrees the app makes for a conversation.
+ *
+ * The device stores a token in the worktree's git admin dir and acts on the
+ * worktree only for a matching token (`ownerMarker.ts` in local-file-shell).
+ * Topic metadata is readable by everyone who can open the topic, so the token
+ * alone proves nothing: the server issues it as an HMAC over the creator's
+ * user id and a nonce, and presents a record's token to a device only when it
+ * re-derives from the claiming topic's own creator. A token copied into
+ * another member's topic never verifies there.
+ */
+
+const DOMAIN = 'lobehub:owned-worktree:v1';
+
+const secret = () => process.env.KEY_VAULTS_SECRET?.trim() || undefined;
+
+const sign = (key: string, userId: string, nonce: string) =>
+ createHmac('sha256', key).update(`${DOMAIN}:${userId}:${nonce}`).digest('base64url');
+
+export interface WorktreeReceipt {
+ nonce: string;
+ token: string;
+}
+
+/** A receipt for a worktree `userId` is about to create; `undefined` without a server secret. */
+export const issueWorktreeReceipt = (userId: string): WorktreeReceipt | undefined => {
+ const key = secret();
+ if (!key) return undefined;
+ const nonce = randomUUID();
+ return { nonce, token: sign(key, userId, nonce) };
+};
+
+/**
+ * The record's token, when it was issued to the topic's creator; otherwise
+ * `undefined`, so a device holding a receipt refuses the request.
+ */
+export const attestedOwnerToken = (
+ topicUserId: string,
+ entry: Pick<OwnedWorktree, 'ownerNonce' | 'ownerToken'>,
+): string | undefined => {
+ const key = secret();
+ const { ownerNonce, ownerToken } = entry;
+ if (!key || !ownerNonce || !ownerToken) return undefined;
+ const expected = Buffer.from(sign(key, topicUserId, ownerNonce));
+ const actual = Buffer.from(ownerToken);
+ return expected.length === actual.length && timingSafeEqual(expected, actual)
+ ? ownerToken
+ : undefined;
+};
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 60d65e0deb6..0db0963c659 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -3703,6 +3703,24 @@
"workingPanel.overview.execution.device": "Connected device",
"workingPanel.overview.execution.local": "This device",
"workingPanel.overview.files": "Files",
+ "workingPanel.overview.keptWorktree.details": "Details",
+ "workingPanel.overview.keptWorktree.discard": "Discard changes and delete",
+ "workingPanel.overview.keptWorktree.discardConfirm": "This deletes the worktree and everything uncommitted in it, including ignored files. This can't be undone. Commits on its branch are kept.",
+ "workingPanel.overview.keptWorktree.discardConfirmTitle": "Discard changes and delete the worktree?",
+ "workingPanel.overview.keptWorktree.discardFailed": "Could not delete the worktree",
+ "workingPanel.overview.keptWorktree.discardPending": "The device is offline. The worktree will be deleted when it's back online.",
+ "workingPanel.overview.keptWorktree.discarded": "Worktree deleted. Its branch was kept.",
+ "workingPanel.overview.keptWorktree.discarding": "Deleting the worktree…",
+ "workingPanel.overview.keptWorktree.failedTitle": "Worktree couldn't be cleaned up",
+ "workingPanel.overview.keptWorktree.hideDetails": "Hide details",
+ "workingPanel.overview.keptWorktree.keep": "Keep",
+ "workingPanel.overview.keptWorktree.keepFailed": "Could not keep the worktree",
+ "workingPanel.overview.keptWorktree.keptToast": "Worktree kept. It won't be cleaned up automatically.",
+ "workingPanel.overview.keptWorktree.removed": "Worktree cleaned up · branch {{branch}} kept",
+ "workingPanel.overview.keptWorktree.removedHint": "It was removed when this topic was archived or moved to the recycle bin. Sending a message checks the branch out again at the same path.",
+ "workingPanel.overview.keptWorktree.submoduleTitle": "Worktree kept: a submodule has commits no remote holds",
+ "workingPanel.overview.keptWorktree.title_one": "Worktree kept: {{count}} uncommitted file",
+ "workingPanel.overview.keptWorktree.title_other": "Worktree kept: {{count}} uncommitted files",
"workingPanel.overview.outputs": "Outputs",
"workingPanel.overview.ports.copied": "Link copied",
"workingPanel.overview.ports.copy": "Copy link",
@@ -4004,5 +4022,10 @@
"workingPanel.works.versionError": "Failed to load versions",
"workingPanel.works.viewMode.history": "Version history",
"workingPanel.works.viewMode.summary": "Summary cards",
+ "worktreeRestore.branchMissing": "Can't restore the worktree",
+ "worktreeRestore.branchMissingDesc": "The branch {{branch}} no longer exists, so this conversation continues in the source repository.",
+ "worktreeRestore.failed": "Couldn't restore the worktree",
+ "worktreeRestore.stillCleaning": "The worktree is still being cleaned up. Try sending again in a moment.",
+ "worktreeRestore.waiting": "Waiting for the worktree cleanup to finish before restoring it…",
"you": "You"
}
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 4a3b9aa8a29..05102dc1d37 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -3703,6 +3703,24 @@
"workingPanel.overview.execution.device": "已连接设备",
"workingPanel.overview.execution.local": "此设备",
"workingPanel.overview.files": "文件",
+ "workingPanel.overview.keptWorktree.details": "详情",
+ "workingPanel.overview.keptWorktree.discard": "丢弃改动并删除",
+ "workingPanel.overview.keptWorktree.discardConfirm": "这会删除 worktree 以及其中所有未提交的内容,包括 ignored 文件,无法撤销。分支上的提交会保留。",
+ "workingPanel.overview.keptWorktree.discardConfirmTitle": "丢弃改动并删除 worktree?",
+ "workingPanel.overview.keptWorktree.discardFailed": "无法删除 worktree",
+ "workingPanel.overview.keptWorktree.discardPending": "设备当前离线,重新上线后会删除这个 worktree。",
+ "workingPanel.overview.keptWorktree.discarded": "worktree 已删除,分支已保留",
+ "workingPanel.overview.keptWorktree.discarding": "正在删除 worktree…",
+ "workingPanel.overview.keptWorktree.failedTitle": "worktree 未能清理",
+ "workingPanel.overview.keptWorktree.hideDetails": "收起详情",
+ "workingPanel.overview.keptWorktree.keep": "保留",
+ "workingPanel.overview.keptWorktree.keepFailed": "无法保留 worktree",
+ "workingPanel.overview.keptWorktree.keptToast": "worktree 已保留,之后不会再自动清理",
+ "workingPanel.overview.keptWorktree.removed": "worktree 已清理 · 分支 {{branch}} 已保留",
+ "workingPanel.overview.keptWorktree.removedHint": "话题归档或移入回收站时已删除这个 worktree。发送消息时会在原路径重新检出该分支。",
+ "workingPanel.overview.keptWorktree.submoduleTitle": "worktree 已保留:子模块中有未推送的提交",
+ "workingPanel.overview.keptWorktree.title_one": "worktree 已保留:{{count}} 个未提交的文件",
+ "workingPanel.overview.keptWorktree.title_other": "worktree 已保留:{{count}} 个未提交的文件",
"workingPanel.overview.outputs": "产物",
"workingPanel.overview.ports.copied": "链接已复制",
"workingPanel.overview.ports.copy": "复制链接",
@@ -4004,5 +4022,10 @@
"workingPanel.works.versionError": "版本加载失败",
"workingPanel.works.viewMode.history": "版本历史",
"workingPanel.works.viewMode.summary": "摘要卡片",
+ "worktreeRestore.branchMissing": "无法恢复 worktree",
+ "worktreeRestore.branchMissingDesc": "分支 {{branch}} 已不存在,这个对话改在源仓库目录中继续。",
+ "worktreeRestore.failed": "无法恢复 worktree",
+ "worktreeRestore.stillCleaning": "worktree 仍在清理中,请稍后再发送。",
+ "worktreeRestore.waiting": "正在等待 worktree 清理完成后再恢复…",
"you": "你"
}
diff --git a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts b/packages/database/src/models/__tests__/topics/topic.characterization.test.ts
index d7c5da79434..a0cf8b4fdf4 100644
--- a/packages/database/src/models/__tests__/topics/topic.characterization.test.ts
+++ b/packages/database/src/models/__tests__/topics/topic.characterization.test.ts
@@ -54,6 +54,7 @@ const PUBLIC_METHODS = [
'count',
'countBySender',
'countInFlightInDirectory',
+ 'countLiveTopicsUsingWorktree',
'countShareVisitors',
'countTopicsForMemoryExtractor',
'create',
@@ -65,11 +66,15 @@ const PUBLIC_METHODS = [
'findByWebhookThread',
'findOwnTopicById',
'findOwnTopicsByIds',
+ 'findOwnedWorktreeTopics',
'findOwnersByIds',
+ 'findOwnersOfWorktree',
+ 'findPendingOwnedWorktreeTopics',
'findRecentByBotThread',
'findRunInitiators',
'findShareVisitorTopicIds',
'findTrashedByIds',
+ 'findWaitingCleanupTopicsUnder',
'getCronTopicsGroupedByCronJob',
'isRunningOperationAlive',
'listTopicsForMemoryExtractor',
@@ -101,6 +106,7 @@ const PUBLIC_METHODS = [
'update',
'updateMetadata',
'updateModelPin',
+ 'updateOwnedWorktree',
'updateRunningOperationAssistantMessage',
];
diff --git a/packages/database/src/models/__tests__/topics/topic.ownedWorktree.test.ts b/packages/database/src/models/__tests__/topics/topic.ownedWorktree.test.ts
new file mode 100644
index 00000000000..910a83cfe1c
--- /dev/null
+++ b/packages/database/src/models/__tests__/topics/topic.ownedWorktree.test.ts
@@ -0,0 +1,257 @@
+// @vitest-environment node
+import type { ChatTopicMetadata } from '@lobechat/types';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { topics, users } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { TopicModel } from '../../topic';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+
+const userId = 'topic-owned-wt-user';
+const otherId = 'topic-owned-wt-other';
+const WT = '/Users/me/.lobehub/worktrees/repo-1a2b3c4d/quiet-hill';
+
+const autoCreated = (extra: Partial<ChatTopicMetadata> = {}): ChatTopicMetadata => ({
+ boundDeviceId: 'dev-1',
+ workingDirectory: WT,
+ workingDirectoryConfig: {
+ git: {
+ activeWorktree: WT,
+ autoCreated: true,
+ autoCreatedAt: '2026-11-16T00:00:00.000Z',
+ branch: 'lobehub/quiet-hill',
+ isWorktree: true,
+ },
+ path: '/code/repo',
+ sessionPath: WT,
+ },
+ ...extra,
+});
+
+const insert = (
+ id: string,
+ metadata: ChatTopicMetadata,
+ extra: { isDeleted?: boolean; status?: 'active' | 'completed'; userId?: string } = {},
+) =>
+ serverDB.insert(topics).values({
+ id,
+ isDeleted: extra.isDeleted ?? null,
+ deletedAt: extra.isDeleted ? new Date() : null,
+ metadata,
+ status: extra.status ?? 'active',
+ userId: extra.userId ?? userId,
+ });
+
+const readMetadata = async (id: string) =>
+ (await serverDB.select().from(topics).where(eq(topics.id, id)))[0]?.metadata;
+
+beforeEach(async () => {
+ await serverDB.insert(users).values([{ id: userId }, { id: otherId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users).where(inArray(users.id, [userId, otherId]));
+});
+
+const model = () => new TopicModel(serverDB, userId);
+
+describe('ownedWorktrees claim', () => {
+ it('is recorded when a topic is created on a worktree the app made', async () => {
+ const topic = await model().create({ metadata: autoCreated(), title: 't' });
+ expect(topic.metadata?.ownedWorktrees).toEqual([
+ {
+ branch: 'lobehub/quiet-hill',
+ createdAt: '2026-11-16T00:00:00.000Z',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ]);
+ });
+
+ it('is recorded when the client patches the working directory in, and survives a later move', async () => {
+ await insert('t-patch', { boundDeviceId: 'dev-1' });
+ await model().updateMetadata('t-patch', {
+ workingDirectoryConfig: autoCreated().workingDirectoryConfig,
+ });
+ expect((await readMetadata('t-patch'))?.ownedWorktrees?.[0]?.path).toBe(WT);
+
+ // The agent moves to another worktree: the marker goes, the claim stays.
+ await model().updateMetadata('t-patch', {
+ workingDirectoryConfig: {
+ git: { activeWorktree: '/elsewhere', branch: 'feat/x' },
+ path: '/code/repo',
+ sessionPath: WT,
+ },
+ });
+ const metadata = await readMetadata('t-patch');
+ expect(metadata?.workingDirectoryConfig?.git?.autoCreated).toBeUndefined();
+ expect(metadata?.ownedWorktrees?.map((entry) => entry.path)).toEqual([WT]);
+ });
+
+ it('a metadata patch or snapshot never overwrites the recorded cleanup state', async () => {
+ await insert('t-keep', {
+ ...autoCreated(),
+ ownedWorktrees: [
+ {
+ cleanup: { at: 'x', state: 'kept' },
+ createdAt: 'y',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ });
+ await model().updateMetadata('t-keep', { ownedWorktrees: [] } as any);
+ expect((await readMetadata('t-keep'))?.ownedWorktrees?.[0]?.cleanup?.state).toBe('kept');
+
+ await model().update('t-keep', { metadata: { workingDirectory: '/x' } });
+ const metadata = await readMetadata('t-keep');
+ expect(metadata?.workingDirectory).toBe('/x');
+ expect(metadata?.ownedWorktrees?.[0]?.cleanup?.state).toBe('kept');
+ });
+});
+
+describe('legacy claims survive a directory change', () => {
+ // Created before `ownedWorktrees`: only the old markers say the app made it.
+ const legacy = () =>
+ serverDB.insert(topics).values({ id: 't-legacy-move', metadata: autoCreated(), userId });
+ const moved = {
+ workingDirectoryConfig: { git: { activeWorktree: '/elsewhere' }, path: '/code/repo' },
+ };
+
+ it('is resolved before a metadata patch replaces the markers', async () => {
+ await legacy();
+ await model().updateMetadata('t-legacy-move', moved);
+ expect((await readMetadata('t-legacy-move'))?.ownedWorktrees?.map((e) => e.path)).toEqual([WT]);
+ });
+
+ it('is resolved before a metadata snapshot replaces the markers', async () => {
+ await legacy();
+ await model().update('t-legacy-move', { metadata: moved });
+ expect((await readMetadata('t-legacy-move'))?.ownedWorktrees?.map((e) => e.path)).toEqual([WT]);
+ });
+});
+
+describe('updateOwnedWorktree', () => {
+ it('backfills a topic that predates the record and writes the new state', async () => {
+ // Created before `ownedWorktrees` existed: only the PR B markers are there.
+ await serverDB
+ .insert(topics)
+ .values({ id: 't-legacy', metadata: autoCreated(), status: 'completed', userId });
+
+ const written = await model().updateOwnedWorktree('t-legacy', WT, (entry) => ({
+ ...entry,
+ cleanup: { at: 'now', state: 'removed', trigger: 'archived' },
+ }));
+ expect(written).toMatchObject({ branch: 'lobehub/quiet-hill', deviceId: 'dev-1', path: WT });
+ expect((await readMetadata('t-legacy'))?.ownedWorktrees).toEqual([
+ expect.objectContaining({ cleanup: { at: 'now', state: 'removed', trigger: 'archived' } }),
+ ]);
+ });
+
+ it('reaches trashed topics, and a declined update writes nothing', async () => {
+ await insert('t-trash', autoCreated(), { isDeleted: true });
+ expect(await model().updateOwnedWorktree('t-trash', WT, () => undefined)).toBeUndefined();
+ const written = await model().updateOwnedWorktree('t-trash', WT, (entry) => ({
+ ...entry,
+ cleanup: { at: 'now', state: 'pending' },
+ }));
+ expect(written?.cleanup?.state).toBe('pending');
+ });
+
+ it("does not touch another user's topic", async () => {
+ await insert('t-other', autoCreated(), { userId: otherId });
+ expect(
+ await model().updateOwnedWorktree('t-other', WT, (entry) => ({
+ ...entry,
+ cleanup: { at: 'now', state: 'removed' },
+ })),
+ ).toBeUndefined();
+ });
+});
+
+describe('cleanup lookups', () => {
+ const pending = (deviceId?: string): ChatTopicMetadata => ({
+ ownedWorktrees: [
+ {
+ cleanup: { at: 'x', state: 'pending' },
+ createdAt: 'y',
+ ...(deviceId && { deviceId }),
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ });
+
+ it('finds pending cleanups per device, and the anonymous-desktop ones', async () => {
+ await insert('p-dev1', pending('dev-1'), { isDeleted: true, status: 'completed' });
+ await insert('p-dev2', pending('dev-2'), { status: 'completed' });
+ await insert('p-anon', pending(), { status: 'completed' });
+ await insert('p-done', autoCreated());
+
+ expect((await model().findPendingOwnedWorktreeTopics('dev-1')).map((r) => r.id)).toEqual([
+ 'p-dev1',
+ ]);
+ expect((await model().findPendingOwnedWorktreeTopics(undefined)).map((r) => r.id)).toEqual([
+ 'p-anon',
+ ]);
+ });
+
+ it('counts live topics still using the worktree, not archived or trashed ones', async () => {
+ await insert('owner', autoCreated(), { status: 'completed' });
+ await insert('archived-user', autoCreated(), { status: 'completed' });
+ await insert('trashed-user', autoCreated(), { isDeleted: true });
+ expect(await model().countLiveTopicsUsingWorktree({ excludeIds: ['owner'], path: WT })).toBe(0);
+
+ await insert('live-user', {
+ workingDirectoryConfig: { path: '/code/repo', sessionPath: `${WT}/` },
+ });
+ await insert('live-active', {
+ workingDirectoryConfig: { git: { activeWorktree: WT }, path: '/code/repo' },
+ });
+ // The same folder however its path ends.
+ expect(await model().countLiveTopicsUsingWorktree({ excludeIds: ['owner'], path: WT })).toBe(2);
+ expect(
+ await model().countLiveTopicsUsingWorktree({ excludeIds: ['owner'], path: `${WT}/` }),
+ ).toBe(2);
+ });
+
+ it('still counts an archived or trashed topic whose run is going on in the folder', async () => {
+ const running = {
+ runningOperation: { assistantMessageId: 'm', operationId: 'op', startedAt: 'x' },
+ workingDirectoryConfig: { git: { activeWorktree: WT }, path: '/code/repo' },
+ } as ChatTopicMetadata;
+ await insert('archived-running', running, { status: 'completed' });
+ await insert('trashed-running', running, { isDeleted: true });
+ await insert(
+ 'archived-idle',
+ {
+ workingDirectoryConfig: { git: { activeWorktree: WT }, path: '/code/repo' },
+ },
+ { status: 'completed' },
+ );
+ expect(await model().countLiveTopicsUsingWorktree({ excludeIds: ['owner'], path: WT })).toBe(2);
+ });
+
+ it('counts a live topic that picked the worktree folder itself as its directory', async () => {
+ await insert('picked-config', { workingDirectoryConfig: { path: WT } });
+ await insert('picked-legacy', { workingDirectory: WT });
+ expect(await model().countLiveTopicsUsingWorktree({ excludeIds: ['owner'], path: WT })).toBe(2);
+ });
+
+ it('counts a topic working in a folder below the worktree, not in a look-alike sibling', async () => {
+ await insert('below', { workingDirectoryConfig: { path: `${WT}/packages/foo` } });
+ await insert('sibling', { workingDirectoryConfig: { path: `${WT}-other/packages/foo` } });
+ await insert('underscore', { workingDirectory: `${WT.slice(0, -1)}_/x` });
+ expect(await model().countLiveTopicsUsingWorktree({ excludeIds: ['owner'], path: WT })).toBe(1);
+ });
+
+ it('finds the owners of a worktree path, trashed ones included', async () => {
+ await insert('o-1', { ...autoCreated(), ...pending('dev-1') }, { isDeleted: true });
+ await insert('o-2', { workingDirectoryConfig: { path: '/code/repo' } });
+ expect((await model().findOwnersOfWorktree(WT)).map((r) => r.id)).toEqual(['o-1']);
+ });
+});
diff --git a/packages/database/src/models/topic/create.ts b/packages/database/src/models/topic/create.ts
index 2f3348ca7b7..3a3d3961b0e 100644
--- a/packages/database/src/models/topic/create.ts
+++ b/packages/database/src/models/topic/create.ts
@@ -4,6 +4,7 @@ import { type TopicItem, topics } from '../../schemas';
import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';
import { buildWorkspacePayload } from '../../utils/workspace';
import type { TopicModelContext } from './context';
+import { withOwnedWorktreeClaim } from './ownedWorktree';
import type { CreateTopicParams, ModelTimingContext } from './types';
/**
@@ -31,6 +32,7 @@ export const create = async (
{ userId: ctx.userId, workspaceId: ctx.workspaceId },
{
...params,
+ ...(params.metadata && { metadata: withOwnedWorktreeClaim(params.metadata) }),
agentId: params.agentId || null,
groupId: params.groupId || null,
id,
diff --git a/packages/database/src/models/topic/inFlight.ts b/packages/database/src/models/topic/inFlight.ts
index b3fc2126443..0be5c0a6689 100644
--- a/packages/database/src/models/topic/inFlight.ts
+++ b/packages/database/src/models/topic/inFlight.ts
@@ -31,7 +31,10 @@ export const getTopicRunDirectories = (
* Same test as the project-directory guards (`isTopicInFlight`): a running
* status, a live run marker, or a turn start that holds the short reservation.
*/
-const isInFlight = (topic: { metadata: ChatTopicMetadata | null; status: string | null }) =>
+export const isInFlight = (topic: {
+ metadata: ChatTopicMetadata | null | undefined;
+ status: string | null;
+}) =>
topic.status === 'running' ||
!!topic.metadata?.runningOperation ||
hasLiveTaskCallbackReservation(topic.metadata);
diff --git a/packages/database/src/models/topic/index.ts b/packages/database/src/models/topic/index.ts
index d77280ea7f9..bd6d14ce9b6 100644
--- a/packages/database/src/models/topic/index.ts
+++ b/packages/database/src/models/topic/index.ts
@@ -8,6 +8,7 @@ import * as find from './find';
import * as inFlight from './inFlight';
import * as list from './list';
import * as memoryExtractor from './memoryExtractor';
+import * as ownedWorktree from './ownedWorktree';
import * as runningOperation from './runningOperation';
import * as scheduledRun from './scheduledRun';
import * as shareVisitor from './shareVisitor';
@@ -15,6 +16,7 @@ import * as taskCallback from './taskCallback';
import * as trash from './trash';
import * as update from './update';
+export type { OwnedWorktreeTopicRow } from './ownedWorktree';
export { getTopicDeviceId } from './runningOperation';
export { hasLiveTaskCallbackReservation } from './taskCallback';
export type {
@@ -138,6 +140,12 @@ export class TopicModel {
queryRecent = this.withContext(find.queryRecent);
getCronTopicsGroupedByCronJob = this.withContext(find.getCronTopicsGroupedByCronJob);
countInFlightInDirectory = this.withContext(inFlight.countInFlightInDirectory);
+ findOwnedWorktreeTopics = this.withContext(ownedWorktree.findOwnedWorktreeTopics);
+ findPendingOwnedWorktreeTopics = this.withContext(ownedWorktree.findPendingOwnedWorktreeTopics);
+ findOwnersOfWorktree = this.withContext(ownedWorktree.findOwnersOfWorktree);
+ findWaitingCleanupTopicsUnder = this.withContext(ownedWorktree.findWaitingCleanupTopicsUnder);
+ countLiveTopicsUsingWorktree = this.withContext(ownedWorktree.countLiveTopicsUsingWorktree);
+ updateOwnedWorktree = this.withContext(ownedWorktree.updateOwnedWorktree);
// **************** Agent Share (visitor-scoped) *************** //
diff --git a/packages/database/src/models/topic/ownedWorktree.ts b/packages/database/src/models/topic/ownedWorktree.ts
new file mode 100644
index 00000000000..b64169ed15f
--- /dev/null
+++ b/packages/database/src/models/topic/ownedWorktree.ts
@@ -0,0 +1,244 @@
+import type { ChatTopicMetadata, OwnedWorktree, OwnedWorktreeTopicRow } from '@lobechat/types';
+import { claimAutoCreatedWorktree, resolveOwnedWorktrees } from '@lobechat/types';
+import { and, eq, inArray, notInArray, or, type SQL, sql } from 'drizzle-orm';
+
+import { topics } from '../../schemas';
+import type { TopicModelContext } from './context';
+import { isInFlight } from './inFlight';
+
+/**
+ * Persistence for `metadata.ownedWorktrees` — the worktrees the app created for
+ * a topic and the state of their cleanup (see `@lobechat/types` ownedWorktree).
+ *
+ * Every read and write here spans the recycle bin (`trashScope`): a trashed
+ * topic's worktree is exactly what gets cleaned up. Predicates over the jsonb
+ * use containment (`@>`) and equality only — never a null test on an
+ * extracted value, which crashes the pg_search planner (see `./index.ts`).
+ */
+
+export type { OwnedWorktreeTopicRow } from '@lobechat/types';
+
+const rowColumns = {
+ id: topics.id,
+ isDeleted: topics.isDeleted,
+ metadata: topics.metadata,
+ status: topics.status,
+ userId: topics.userId,
+};
+
+/**
+ * Claim the worktree the app created for this topic into `ownedWorktrees`
+ * whenever metadata carrying `workingDirectoryConfig.git.autoCreated` is
+ * written. Applied on the create and merge paths of the model, so every writer
+ * (server pipeline, desktop client) records it without knowing about it.
+ */
+export const withOwnedWorktreeClaim = <T extends ChatTopicMetadata | null | undefined>(
+ metadata: T,
+): T => (metadata ? (claimAutoCreatedWorktree(metadata) as T) : metadata);
+
+/**
+ * The record a write must carry forward from the row it replaces: the
+ * persisted `ownedWorktrees`, or — for a topic that predates it — the claim
+ * backfilled from its old markers, resolved BEFORE a new working-directory
+ * config replaces (and so erases) those markers.
+ */
+export const carriedOwnedWorktrees = (
+ existing: ChatTopicMetadata | null | undefined,
+): Pick<ChatTopicMetadata, 'ownedWorktrees'> => {
+ const owned = resolveOwnedWorktrees(existing);
+ return owned.length > 0 ? { ownedWorktrees: owned } : {};
+};
+
+/** Topics by id with their owned-worktree data, trashed ones included. */
+export const findOwnedWorktreeTopics = async (
+ ctx: TopicModelContext,
+ ids: string[],
+): Promise<OwnedWorktreeTopicRow[]> => {
+ if (ids.length === 0) return [];
+ return ctx.db
+ .select(rowColumns)
+ .from(topics)
+ .where(and(inArray(topics.id, ids), ctx.trashScope()));
+};
+
+const containsEntry = (entry: Record<string, unknown>) =>
+ sql`COALESCE(${topics.metadata} -> 'ownedWorktrees' @> ${JSON.stringify([entry])}::jsonb, false)`;
+
+/**
+ * Topics with a cleanup waiting on `deviceId` — or, with `deviceId` undefined,
+ * on a desktop that never registered with the gateway (records without one,
+ * the caller's own only). Trashed topics included; the caller re-checks each before running it.
+ */
+export const findPendingOwnedWorktreeTopics = async (
+ ctx: TopicModelContext,
+ deviceId: string | undefined,
+): Promise<OwnedWorktreeTopicRow[]> => {
+ const rows = await ctx.db
+ .select(rowColumns)
+ .from(topics)
+ .where(
+ and(
+ ctx.trashScope(),
+ // A device-bound cleanup belongs to whoever may operate that device —
+ // every member of a workspace that shares it. One without a device
+ // only ever ran on its creator's own desktop.
+ deviceId ? undefined : eq(topics.userId, ctx.userId),
+ or(
+ containsEntry({
+ cleanup: { state: 'pending' },
+ ...(deviceId && { deviceId }),
+ }),
+ // A claim whose executor died (closed app, crashed request): the
+ // caller decides from `cleanup.at` whether it is stale.
+ containsEntry({ cleanup: { state: 'running' }, ...(deviceId && { deviceId }) }),
+ ),
+ ),
+ );
+ if (deviceId) return rows;
+ return rows.filter((row) =>
+ row.metadata?.ownedWorktrees?.some(
+ (entry) =>
+ !entry.deviceId &&
+ (entry.cleanup?.state === 'pending' || entry.cleanup?.state === 'running'),
+ ),
+ );
+};
+
+/**
+ * Topics under these agents / legacy sessions whose worktree cleanup is still
+ * waiting (`pending` / `running`), trashed ones included: purging the parent
+ * would cascade them away with the only record of the folder to delete.
+ */
+export const findWaitingCleanupTopicsUnder = async (
+ ctx: TopicModelContext,
+ { agentIds, sessionIds }: { agentIds: string[]; sessionIds: string[] },
+): Promise<OwnedWorktreeTopicRow[]> => {
+ if (agentIds.length === 0 && sessionIds.length === 0) return [];
+ return ctx.db
+ .select(rowColumns)
+ .from(topics)
+ .where(
+ and(
+ ctx.trashScope(),
+ or(
+ agentIds.length > 0 ? inArray(topics.agentId, agentIds) : undefined,
+ sessionIds.length > 0 ? inArray(topics.sessionId, sessionIds) : undefined,
+ ),
+ or(
+ containsEntry({ cleanup: { state: 'pending' } }),
+ containsEntry({ cleanup: { state: 'running' } }),
+ ),
+ ),
+ );
+};
+
+/**
+ * Topics that own the worktree at `path` — by their record, or (for topics
+ * that predate it) by the markers `resolveOwnedWorktrees` backfills from.
+ * Trashed ones included; the caller filters for retired topics.
+ */
+export const findOwnersOfWorktree = async (
+ ctx: TopicModelContext,
+ path: string,
+): Promise<OwnedWorktreeTopicRow[]> => {
+ const rows = await ctx.db
+ .select(rowColumns)
+ .from(topics)
+ .where(
+ and(
+ ctx.trashScope(),
+ or(
+ containsEntry({ path }),
+ eq(sql<string>`${topics.metadata} -> 'workingDirectoryConfig' ->> 'sessionPath'`, path),
+ sql`COALESCE(${topics.metadata} -> 'workingDirectoryConfig' -> 'git' @> ${JSON.stringify({ activeWorktree: path, autoCreated: true })}::jsonb, false)`,
+ ),
+ ),
+ );
+ return rows.filter((row) =>
+ resolveOwnedWorktrees(row.metadata).some((entry) => entry.path === path),
+ );
+};
+
+/**
+ * How many other topics still use `path` as their working directory or CLI
+ * start folder. A worktree shared like that (a handoff continuing in it) is
+ * not cleaned up yet. "Still" means not archived and not in the recycle bin —
+ * or archived or trashed with a run still going there, since retiring a topic
+ * does not stop its run. Spans every member's topics in a workspace, which
+ * share its devices.
+ */
+export const countLiveTopicsUsingWorktree = async (
+ ctx: TopicModelContext,
+ { excludeIds, path }: { excludeIds: string[]; path: string },
+): Promise<number> => {
+ const base = path.replace(/[/\\]+$/, '');
+ const variants = [...new Set([path, base])];
+ // Below the folder too (a topic working in `<worktree>/packages/foo`), cut at
+ // a separator so `<worktree>-other` never matches. LIKE wildcards escaped.
+ const escaped = base.replaceAll('\\', '\\\\').replaceAll('%', '\\%').replaceAll('_', '\\_');
+ const descendants = [`${escaped}/%`, `${escaped}\\\\%`];
+ const pointsInto = (expr: SQL<string>) =>
+ or(
+ inArray(expr, variants),
+ ...descendants.map((pattern) => sql`${expr} LIKE ${pattern} ESCAPE '\\'`),
+ );
+ const rows = await ctx.db
+ .select({ isDeleted: topics.isDeleted, metadata: topics.metadata, status: topics.status })
+ .from(topics)
+ .where(
+ and(
+ // Recycle bin included: a trashed topic may still be running there.
+ ctx.trashScope(),
+ excludeIds.length > 0 ? notInArray(topics.id, excludeIds) : undefined,
+ // Every way a topic can point at the folder: its current worktree, its
+ // CLI start folder, or the folder itself picked as its directory.
+ or(
+ pointsInto(
+ sql<string>`${topics.metadata} -> 'workingDirectoryConfig' -> 'git' ->> 'activeWorktree'`,
+ ),
+ pointsInto(sql<string>`${topics.metadata} -> 'workingDirectoryConfig' ->> 'sessionPath'`),
+ pointsInto(sql<string>`${topics.metadata} -> 'workingDirectoryConfig' ->> 'path'`),
+ pointsInto(sql<string>`${topics.metadata} ->> 'workingDirectory'`),
+ ),
+ ),
+ );
+ return rows.filter((row) => {
+ const retired = !!row.isDeleted || row.status === 'completed' || row.status === 'archived';
+ return !retired || isInFlight(row);
+ }).length;
+};
+
+/**
+ * Rewrite one owned-worktree record under a row lock. `update` receives the
+ * current record (backfilled from the legacy markers when the topic predates
+ * `ownedWorktrees`) and returns the replacement, or `undefined` to leave the
+ * row untouched — which is how a compare-and-set claim declines. Returns the
+ * written record, or `undefined` when nothing was written.
+ */
+export const updateOwnedWorktree = async (
+ ctx: TopicModelContext,
+ topicId: string,
+ path: string,
+ update: (entry: OwnedWorktree, row: OwnedWorktreeTopicRow) => OwnedWorktree | undefined,
+): Promise<OwnedWorktree | undefined> =>
+ ctx.db.transaction(async (tx) => {
+ const [row] = await tx
+ .select(rowColumns)
+ .from(topics)
+ .where(and(eq(topics.id, topicId), ctx.trashScope()))
+ .for('update');
+ if (!row) return undefined;
+
+ const owned = resolveOwnedWorktrees(row.metadata);
+ const index = owned.findIndex((entry) => entry.path === path);
+ if (index < 0) return undefined;
+ const next = update(owned[index], row);
+ if (!next) return undefined;
+
+ const ownedWorktrees = owned.map((entry, i) => (i === index ? next : entry));
+ await tx
+ .update(topics)
+ .set({ metadata: { ...row.metadata, ownedWorktrees } as ChatTopicMetadata })
+ .where(and(eq(topics.id, topicId), ctx.trashScope()));
+ return next;
+ });
diff --git a/packages/database/src/models/topic/update.ts b/packages/database/src/models/topic/update.ts
index a237fae58ad..18371ea4cec 100644
--- a/packages/database/src/models/topic/update.ts
+++ b/packages/database/src/models/topic/update.ts
@@ -5,8 +5,34 @@ import { type TopicItem, topics } from '../../schemas';
import { joinTopicAgentsToProjects } from '../../utils/projectTopicAgents';
import { recomputeTopicUsage } from '../topicUsage';
import type { TopicModelContext } from './context';
+import { carriedOwnedWorktrees, withOwnedWorktreeClaim } from './ownedWorktree';
import type { TopicMetadataPatch } from './types';
+/**
+ * An explicit metadata snapshot replaces the row's metadata, except for
+ * `ownedWorktrees`: that record is server-owned (which worktrees the app made
+ * for the topic, and their cleanup state), so a snapshot built from an older
+ * read must not erase it. The persisted list wins; a snapshot only seeds one
+ * where none exists yet.
+ */
+const replaceMetadataKeepingOwnedWorktrees = (
+ next: ChatTopicMetadata | null | undefined,
+ existing: ChatTopicMetadata | null | undefined,
+) => {
+ if (!next) return next;
+ // A legacy topic's claim lives only in the markers this snapshot replaces.
+ const claimed = withOwnedWorktreeClaim({ ...next, ...carriedOwnedWorktrees(existing) });
+ return sql`${JSON.stringify(claimed)}::jsonb || case when coalesce(jsonb_exists(${topics.metadata}, 'ownedWorktrees'), false) then jsonb_build_object('ownedWorktrees', ${topics.metadata} -> 'ownedWorktrees') else '{}'::jsonb end`;
+};
+
+const readMetadata = async (ctx: TopicModelContext, id: string) => {
+ const [row] = await ctx.db
+ .select({ metadata: topics.metadata })
+ .from(topics)
+ .where(and(eq(topics.id, id), ctx.ownership()));
+ return row?.metadata;
+};
+
export const update = async (ctx: TopicModelContext, id: string, data: Partial<TopicItem>) => {
/**
* Older clients switch models through the general update endpoint. Clear
@@ -40,7 +66,7 @@ export const update = async (ctx: TopicModelContext, id: string, data: Partial<T
*/
const metadata =
data.metadata !== undefined
- ? data.metadata
+ ? replaceMetadataKeepingOwnedWorktrees(data.metadata, await readMetadata(ctx, id))
: data.status === 'running'
? sql`case when ${topics.status} in ('running', 'waitingForHuman') then ${persistedMetadata} else jsonb_set(${persistedMetadata}, '{runStartedAt}', to_jsonb(now())) end`
: modelChanged
@@ -162,11 +188,14 @@ export const updateMetadata = async (
}
: metadata.onboardingSession;
- const mergedMetadata = {
+ const mergedMetadata = withOwnedWorktreeClaim({
...existing.metadata,
...metadata,
...(mergedOnboardingSession && { onboardingSession: mergedOnboardingSession }),
- } as ChatTopicMetadata;
+ // Server-owned: a patch never replaces it (see `./ownedWorktree`), and a
+ // legacy topic's claim is resolved from its old markers first.
+ ...carriedOwnedWorktrees(existing.metadata),
+ } as ChatTopicMetadata);
return tx
.update(topics)
diff --git a/packages/device-control/src/__tests__/dispatch.test.ts b/packages/device-control/src/__tests__/dispatch.test.ts
index 593644dd3f8..9e3a3990dec 100644
--- a/packages/device-control/src/__tests__/dispatch.test.ts
+++ b/packages/device-control/src/__tests__/dispatch.test.ts
@@ -700,6 +700,31 @@ describe('executeDeviceRpc', () => {
expect(result.success).toBe(false);
});
+ it('publishes the owned-worktree RPCs on the device surface', () => {
+ expect(DEVICE_RPC_METHODS).toEqual(
+ expect.arrayContaining(['cleanupOwnedWorktree', 'restoreOwnedWorktree']),
+ );
+ });
+
+ it('never lets a request widen the owned-worktree guard root', async () => {
+ // `rootDir` is a test-only knob of the shell function; arriving over RPC it
+ // is dropped, so a folder outside `~/.lobehub/worktrees` stays refused.
+ const target = path.join(root, 'wt');
+ const cleanup = (await executeDeviceRpc(
+ 'cleanupOwnedWorktree',
+ { discard: true, rootDir: root, sourcePath: root, worktreePath: target },
+ makeDeps(),
+ )) as { outcome: string };
+ expect(cleanup.outcome).toBe('refused');
+
+ const restore = (await executeDeviceRpc(
+ 'restoreOwnedWorktree',
+ { branch: 'lobehub/x', rootDir: root, sourcePath: root, worktreePath: target },
+ makeDeps(),
+ )) as { outcome: string };
+ expect(restore.outcome).toBe('refused');
+ });
+
describe('interactive terminal', () => {
/** The PTY handlers a host opts into; absent they all refuse. */
const terminalDeps = () => ({
diff --git a/packages/device-control/src/dispatch.ts b/packages/device-control/src/dispatch.ts
index 2021b796a00..473653f0ba4 100644
--- a/packages/device-control/src/dispatch.ts
+++ b/packages/device-control/src/dispatch.ts
@@ -10,6 +10,7 @@ import {
import {
addGitWorktree,
checkoutGitBranch,
+ cleanupOwnedWorktree,
deleteGitBranch,
getGitAheadBehind,
getGitBranch,
@@ -29,6 +30,7 @@ import {
pushGitBranch,
removeGitWorktree,
renameGitBranch,
+ restoreOwnedWorktree,
revertGitFile,
runPullRequestAction,
} from '@lobechat/local-file-shell/git';
@@ -128,6 +130,8 @@ export const DEVICE_RPC_METHODS = [
'deleteGitBranch',
'removeGitWorktree',
'addGitWorktree',
+ 'cleanupOwnedWorktree',
+ 'restoreOwnedWorktree',
'pullGitBranch',
'pushGitBranch',
'revertGitFile',
@@ -460,10 +464,43 @@ export const executeDeviceRpc = async (
case 'addGitWorktree': {
return addGitWorktree(
- params as { branch: string; path: string; startPoint?: string; worktreePath: string },
+ params as {
+ branch: string;
+ ownerToken?: string;
+ path: string;
+ startPoint?: string;
+ worktreePath: string;
+ },
);
}
+ // Only the named fields are forwarded: the guard root is the device's own
+ // `~/.lobehub/worktrees`, never something a request can widen.
+ case 'cleanupOwnedWorktree': {
+ const { discard, ownerToken, sourcePath, worktreePath } = params as {
+ discard?: boolean;
+ ownerToken?: string;
+ sourcePath: string;
+ worktreePath: string;
+ };
+ return cleanupOwnedWorktree({
+ discard: discard === true,
+ ownerToken,
+ sourcePath,
+ worktreePath,
+ });
+ }
+
+ case 'restoreOwnedWorktree': {
+ const { branch, ownerToken, sourcePath, worktreePath } = params as {
+ branch: string;
+ ownerToken?: string;
+ sourcePath: string;
+ worktreePath: string;
+ };
+ return restoreOwnedWorktree({ branch, ownerToken, sourcePath, worktreePath });
+ }
+
case 'pullGitBranch': {
return pullGitBranch(params as { branch?: string; path: string });
}
diff --git a/packages/electron-client-ipc/src/types/git.ts b/packages/electron-client-ipc/src/types/git.ts
index f604e6b6dec..7b59df89f49 100644
--- a/packages/electron-client-ipc/src/types/git.ts
+++ b/packages/electron-client-ipc/src/types/git.ts
@@ -344,8 +344,25 @@ export interface GitRemoveWorktreeResult {
success: boolean;
}
+/** `cleanupOwnedWorktree`: an app-created worktree removed, kept dirty, or refused. */
+export interface GitOwnedWorktreeCleanupResult {
+ branch?: string;
+ dirtyFiles?: number;
+ error?: string;
+ outcome: 'dirty' | 'error' | 'locked' | 'refused' | 'removed';
+ unpushedSubmodules?: number;
+}
+
+/** `restoreOwnedWorktree`: an app-created worktree checked out again at its path. */
+export interface GitOwnedWorktreeRestoreResult {
+ error?: string;
+ outcome: 'branchMissing' | 'error' | 'refused' | 'restored';
+}
+
export interface GitAddWorktreeResult {
error?: string;
+ /** Echo of the creation receipt the device wrote into the worktree. */
+ ownerToken?: string;
/** Echo of the start point the worktree's branch was cut from, when one was requested. */
startPoint?: string;
success: boolean;
diff --git a/packages/local-file-shell/src/git/__tests__/ownedWorktree.test.ts b/packages/local-file-shell/src/git/__tests__/ownedWorktree.test.ts
new file mode 100644
index 00000000000..21ec17185bc
--- /dev/null
+++ b/packages/local-file-shell/src/git/__tests__/ownedWorktree.test.ts
@@ -0,0 +1,434 @@
+import { execFileSync } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { mkdir, mkdtemp, readdir, realpath, rm, symlink, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ cleanupOwnedWorktree,
+ countUncommittedFiles,
+ restoreOwnedWorktree,
+} from '../ownedWorktree';
+import { OWNER_MARKER_FILE, readOwnerMarker, writeOwnerMarker } from '../ownerMarker';
+import { addGitWorktree } from '../worktrees';
+
+const git = (cwd: string, ...args: string[]): string =>
+ execFileSync('git', args, { cwd, encoding: 'utf8' }).trim();
+
+const cleanup: string[] = [];
+const tempDir = async (prefix: string) => {
+ const dir = await realpath(await mkdtemp(path.join(tmpdir(), prefix)));
+ cleanup.push(dir);
+ return dir;
+};
+
+const initRepo = async (dir: string) => {
+ execFileSync('git', ['-c', 'init.defaultBranch=main', 'init'], { cwd: dir });
+ git(dir, 'config', 'user.email', '[email protected]');
+ git(dir, 'config', 'user.name', 'Test');
+ git(dir, 'config', 'commit.gpgsign', 'false');
+ await writeFile(path.join(dir, 'a.txt'), 'hello\n');
+ await writeFile(path.join(dir, '.gitignore'), 'node_modules/\n');
+ git(dir, 'add', '.');
+ git(dir, 'commit', '-m', 'init');
+};
+
+let repo: string;
+let root: string;
+let worktree: string;
+const BRANCH = 'lobehub/quiet-hill';
+/** The creation receipt the app wrote when it made the worktree. */
+const TOKEN = 'owner-token-0123456789abcdef';
+
+const addWorktree = (target: string, branch = BRANCH) =>
+ git(repo, 'worktree', 'add', '-b', branch, target);
+
+beforeEach(async () => {
+ repo = await tempDir('owt-repo-');
+ await initRepo(repo);
+ root = path.join(await tempDir('owt-home-'), '.lobehub', 'worktrees');
+ worktree = path.join(root, 'repo-1a2b3c4d', 'quiet-hill');
+ await mkdir(path.dirname(worktree), { recursive: true });
+ addWorktree(worktree);
+ await writeOwnerMarker(worktree, TOKEN);
+});
+
+afterEach(async () => {
+ await Promise.all(cleanup.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
+});
+
+const run = (
+ params: { discard?: boolean; ownerToken?: string | null; worktreePath?: string } = {},
+) =>
+ cleanupOwnedWorktree({
+ discard: params.discard,
+ ownerToken: params.ownerToken === null ? undefined : (params.ownerToken ?? TOKEN),
+ rootDir: root,
+ sourcePath: repo,
+ worktreePath: params.worktreePath ?? worktree,
+ });
+
+const branches = () => git(repo, 'branch', '--format=%(refname:short)').split('\n');
+
+describe('cleanupOwnedWorktree — clean / dirty', () => {
+ it('removes a clean worktree, prunes it, and keeps the branch', async () => {
+ await expect(run()).resolves.toEqual({ branch: BRANCH, outcome: 'removed' });
+ expect(existsSync(worktree)).toBe(false);
+ expect(git(repo, 'worktree', 'list', '--porcelain')).not.toContain(worktree);
+ expect(branches()).toContain(BRANCH);
+ });
+
+ it('does not count ignored files or unpushed commits as dirty', async () => {
+ await mkdir(path.join(worktree, 'node_modules', 'pkg'), { recursive: true });
+ await writeFile(path.join(worktree, 'node_modules', 'pkg', 'index.js'), 'x');
+ await writeFile(path.join(worktree, 'b.txt'), 'committed\n');
+ git(worktree, 'add', 'b.txt');
+ git(worktree, 'commit', '-m', 'unpushed');
+
+ await expect(run()).resolves.toMatchObject({ outcome: 'removed' });
+ expect(existsSync(worktree)).toBe(false);
+ expect(git(repo, 'log', '--format=%s', '-1', BRANCH)).toBe('unpushed');
+ });
+
+ it('keeps a worktree with tracked changes and counts them', async () => {
+ await writeFile(path.join(worktree, 'a.txt'), 'changed\n');
+ await expect(run()).resolves.toEqual({ branch: BRANCH, dirtyFiles: 1, outcome: 'dirty' });
+ expect(existsSync(worktree)).toBe(true);
+ });
+
+ it('keeps a worktree with untracked files, counting each file', async () => {
+ await mkdir(path.join(worktree, 'new'), { recursive: true });
+ await writeFile(path.join(worktree, 'new', 'one.txt'), '1');
+ await writeFile(path.join(worktree, 'new', 'two.txt'), '2');
+ await writeFile(path.join(worktree, 'a.txt'), 'changed\n');
+ await expect(run()).resolves.toMatchObject({ dirtyFiles: 3, outcome: 'dirty' });
+ });
+
+ it('keeps a worktree whose submodule holds uncommitted work', async () => {
+ const lib = await tempDir('owt-lib-');
+ await initRepo(lib);
+ git(worktree, '-c', 'protocol.file.allow=always', 'submodule', 'add', lib, 'lib');
+ git(worktree, 'commit', '-m', 'add submodule');
+ await expect(countUncommittedFiles(worktree)).resolves.toBe(0);
+
+ await writeFile(path.join(worktree, 'lib', 'scratch.txt'), 'only here');
+ await expect(run()).resolves.toMatchObject({ dirtyFiles: 1, outcome: 'dirty' });
+ expect(existsSync(path.join(worktree, 'lib', 'scratch.txt'))).toBe(true);
+ });
+
+ it('keeps a worktree whose submodule holds commits no remote has, until they are pushed', async () => {
+ const lib = await tempDir('owt-lib-');
+ await initRepo(lib);
+ git(worktree, '-c', 'protocol.file.allow=always', 'submodule', 'add', lib, 'lib');
+ git(worktree, 'commit', '-m', 'add submodule');
+ // A commit made only inside the worktree's submodule, recorded by the parent.
+ const sub = path.join(worktree, 'lib');
+ git(sub, 'config', 'user.email', '[email protected]');
+ git(sub, 'config', 'user.name', 'Test');
+ git(sub, 'config', 'commit.gpgsign', 'false');
+ await writeFile(path.join(sub, 'local.txt'), 'only here\n');
+ git(sub, 'add', 'local.txt');
+ git(sub, 'commit', '-m', 'local submodule work');
+ git(worktree, 'commit', '-am', 'bump submodule');
+ await expect(countUncommittedFiles(worktree)).resolves.toBe(0);
+
+ await expect(run()).resolves.toMatchObject({ outcome: 'dirty', unpushedSubmodules: 1 });
+ expect(existsSync(path.join(sub, 'local.txt'))).toBe(true);
+
+ // Once a remote branch holds it, nothing would be lost.
+ git(sub, 'push', 'origin', 'HEAD:refs/heads/side');
+ git(sub, 'fetch', 'origin');
+ await expect(run()).resolves.toMatchObject({ outcome: 'removed' });
+ });
+
+ it('counts a staged rename once', async () => {
+ git(worktree, 'mv', 'a.txt', 'renamed.txt');
+ await expect(countUncommittedFiles(worktree)).resolves.toBe(1);
+ });
+
+ it('discard removes a dirty worktree, ignored files included, and keeps the branch', async () => {
+ await writeFile(path.join(worktree, 'a.txt'), 'changed\n');
+ await writeFile(path.join(worktree, 'untracked.txt'), 'u');
+ await mkdir(path.join(worktree, 'node_modules'), { recursive: true });
+ await writeFile(path.join(worktree, 'node_modules', 'x.js'), 'x');
+
+ await expect(run({ discard: true })).resolves.toMatchObject({ outcome: 'removed' });
+ expect(existsSync(worktree)).toBe(false);
+ expect(branches()).toContain(BRANCH);
+ });
+
+ it('fully deletes the folder in place when git refuses to remove it', async () => {
+ await mkdir(path.join(worktree, 'node_modules', 'pkg'), { recursive: true });
+ await writeFile(path.join(worktree, 'node_modules', 'pkg', 'index.js'), 'x');
+
+ await expect(
+ cleanupOwnedWorktree({
+ // A file lock or a timeout: git gives up.
+ gitRemove: async () => {
+ throw new Error('fatal: cannot remove worktree');
+ },
+ ownerToken: TOKEN,
+ rootDir: root,
+ sourcePath: repo,
+ worktreePath: worktree,
+ }),
+ ).resolves.toEqual({ branch: BRANCH, outcome: 'removed' });
+
+ expect(existsSync(worktree)).toBe(false);
+ // A delete, not a move: nothing is parked anywhere under the root.
+ expect(existsSync(path.join(root, '.trash'))).toBe(false);
+ expect(await readdir(path.dirname(worktree))).toEqual([]);
+ expect(git(repo, 'worktree', 'list', '--porcelain')).not.toContain(worktree);
+ expect(branches()).toContain(BRANCH);
+ });
+
+ it('reports a locked worktree and leaves it', async () => {
+ git(repo, 'worktree', 'lock', worktree);
+ await expect(run()).resolves.toEqual({ branch: BRANCH, outcome: 'locked' });
+ await expect(run({ discard: true })).resolves.toMatchObject({ outcome: 'locked' });
+ expect(existsSync(worktree)).toBe(true);
+ });
+
+ it('treats a folder that is already gone as removed and prunes its registration', async () => {
+ await rm(worktree, { force: true, recursive: true });
+ await expect(run()).resolves.toEqual({ outcome: 'removed' });
+ expect(git(repo, 'worktree', 'list', '--porcelain')).not.toContain(worktree);
+ });
+});
+
+describe('cleanupOwnedWorktree — path guard', () => {
+ it('refuses a relative path and `..` traversal out of the root', async () => {
+ await expect(run({ worktreePath: 'repo/quiet-hill' })).resolves.toMatchObject({
+ outcome: 'refused',
+ });
+ await expect(
+ run({ worktreePath: path.join(root, '..', '..', path.basename(repo)) }),
+ ).resolves.toMatchObject({ outcome: 'refused' });
+ expect(existsSync(repo)).toBe(true);
+ });
+
+ it('refuses a worktree outside the root even when git lists it', async () => {
+ const outside = path.join(await tempDir('owt-outside-'), 'wt');
+ addWorktree(outside, 'lobehub/outside');
+ await expect(run({ worktreePath: outside })).resolves.toMatchObject({ outcome: 'refused' });
+ expect(existsSync(outside)).toBe(true);
+ });
+
+ it('refuses a symlink inside the root that escapes it', async () => {
+ const outside = path.join(await tempDir('owt-outside-'), 'wt');
+ addWorktree(outside, 'lobehub/outside');
+ const link = path.join(root, 'repo-1a2b3c4d', 'escape');
+ await symlink(outside, link);
+
+ await expect(run({ worktreePath: link })).resolves.toMatchObject({ outcome: 'refused' });
+ expect(existsSync(outside)).toBe(true);
+ });
+
+ it('refuses a folder in the root that the source repo does not list', async () => {
+ const stray = path.join(root, 'repo-1a2b3c4d', 'stray');
+ await mkdir(stray, { recursive: true });
+ await writeFile(path.join(stray, 'keep.txt'), 'x');
+
+ await expect(run({ worktreePath: stray })).resolves.toMatchObject({ outcome: 'refused' });
+ expect(existsSync(path.join(stray, 'keep.txt'))).toBe(true);
+ });
+
+ it('refuses a worktree of another repository', async () => {
+ const other = await tempDir('owt-other-');
+ await initRepo(other);
+ const foreign = path.join(root, 'other-00000000', 'x');
+ await mkdir(path.dirname(foreign), { recursive: true });
+ git(other, 'worktree', 'add', '-b', 'lobehub/x', foreign);
+
+ await expect(run({ worktreePath: foreign })).resolves.toMatchObject({ outcome: 'refused' });
+ expect(existsSync(foreign)).toBe(true);
+ });
+
+ it('refuses the main worktree', async () => {
+ // A source repo cloned under the root: the path guard alone would pass.
+ const mainUnderRoot = path.join(root, 'main-repo');
+ await mkdir(mainUnderRoot, { recursive: true });
+ await initRepo(mainUnderRoot);
+
+ await expect(
+ cleanupOwnedWorktree({
+ rootDir: root,
+ sourcePath: mainUnderRoot,
+ worktreePath: mainUnderRoot,
+ }),
+ ).resolves.toMatchObject({ outcome: 'refused' });
+ expect(existsSync(path.join(mainUnderRoot, '.git'))).toBe(true);
+ });
+});
+
+describe('cleanupOwnedWorktree — creation receipt', () => {
+ it('refuses a topic that claims the path without the receipt the app wrote', async () => {
+ await expect(run({ ownerToken: 'someone-else-0123456789' })).resolves.toMatchObject({
+ outcome: 'refused',
+ });
+ await expect(run({ discard: true, ownerToken: null })).resolves.toMatchObject({
+ outcome: 'refused',
+ });
+ expect(existsSync(worktree)).toBe(true);
+ });
+
+ it('cleans up a worktree from before receipts only automatically, never by discard', async () => {
+ const legacy = path.join(root, 'repo-1a2b3c4d', 'legacy');
+ addWorktree(legacy, 'lobehub/legacy');
+ await writeFile(path.join(legacy, 'scratch.txt'), 'x');
+
+ await expect(
+ run({ discard: true, ownerToken: null, worktreePath: legacy }),
+ ).resolves.toMatchObject({
+ outcome: 'refused',
+ });
+ expect(existsSync(path.join(legacy, 'scratch.txt'))).toBe(true);
+
+ await rm(path.join(legacy, 'scratch.txt'));
+ await expect(run({ ownerToken: null, worktreePath: legacy })).resolves.toMatchObject({
+ outcome: 'removed',
+ });
+ });
+
+ it('writes the receipt when the app creates the worktree', async () => {
+ const created = path.join(root, 'repo-1a2b3c4d', 'created');
+ await expect(
+ addGitWorktree({
+ branch: 'lobehub/created',
+ ownerToken: TOKEN,
+ path: repo,
+ worktreePath: created,
+ }),
+ ).resolves.toMatchObject({ ownerToken: TOKEN, success: true });
+ await expect(readOwnerMarker(created)).resolves.toBe(TOKEN);
+ // Kept in git's admin dir for the worktree, not in its working tree.
+ expect(existsSync(path.join(created, OWNER_MARKER_FILE))).toBe(false);
+ await expect(run({ worktreePath: created })).resolves.toMatchObject({ outcome: 'removed' });
+ });
+
+ it('gives detached-HEAD commits a branch before removing the worktree', async () => {
+ git(worktree, 'checkout', '--detach');
+ await writeFile(path.join(worktree, 'b.txt'), 'only on a detached HEAD\n');
+ git(worktree, 'add', 'b.txt');
+ git(worktree, 'commit', '-m', 'detached work');
+ const head = git(worktree, 'rev-parse', 'HEAD');
+
+ const result = await run();
+ expect(result).toEqual({ branch: `lobehub/detached-${head.slice(0, 12)}`, outcome: 'removed' });
+ expect(git(repo, 'rev-parse', result.branch!)).toBe(head);
+ });
+});
+
+describe('restoreOwnedWorktree', () => {
+ it('checks the branch out again at the original path', async () => {
+ await writeFile(path.join(worktree, 'b.txt'), 'kept on branch\n');
+ git(worktree, 'add', 'b.txt');
+ git(worktree, 'commit', '-m', 'work');
+ await run();
+ expect(existsSync(worktree)).toBe(false);
+
+ await expect(
+ restoreOwnedWorktree({
+ branch: BRANCH,
+ ownerToken: TOKEN,
+ rootDir: root,
+ sourcePath: repo,
+ worktreePath: worktree,
+ }),
+ ).resolves.toEqual({ outcome: 'restored' });
+ expect(git(worktree, 'rev-parse', '--abbrev-ref', 'HEAD')).toBe(BRANCH);
+ // The receipt comes back with it, so the next cleanup is still this topic's.
+ await expect(readOwnerMarker(worktree)).resolves.toBe(TOKEN);
+ expect(existsSync(path.join(worktree, 'b.txt'))).toBe(true);
+ });
+
+ it('waits for a removal still in flight before checking the worktree out again', async () => {
+ let release!: () => void;
+ const slowRemove = new Promise<void>((resolve) => (release = resolve));
+ const cleaning = cleanupOwnedWorktree({
+ // A large worktree: git is still deleting when the restore arrives.
+ gitRemove: async (source, target) => {
+ await slowRemove;
+ git(source, 'worktree', 'remove', '--force', target);
+ },
+ ownerToken: TOKEN,
+ rootDir: root,
+ sourcePath: repo,
+ worktreePath: worktree,
+ });
+ await new Promise((resolve) => setTimeout(resolve, 200));
+ const restoring = restoreOwnedWorktree({
+ branch: BRANCH,
+ ownerToken: TOKEN,
+ rootDir: root,
+ sourcePath: repo,
+ worktreePath: worktree,
+ });
+ release();
+
+ await expect(cleaning).resolves.toMatchObject({ outcome: 'removed' });
+ await expect(restoring).resolves.toEqual({ outcome: 'restored' });
+ // Re-added after the deletion, not swept away by it.
+ expect(existsSync(path.join(worktree, '.git'))).toBe(true);
+ expect(git(worktree, 'rev-parse', '--abbrev-ref', 'HEAD')).toBe(BRANCH);
+ });
+
+ it('is a no-op when the worktree is already there on its branch', async () => {
+ await expect(
+ restoreOwnedWorktree({
+ branch: BRANCH,
+ rootDir: root,
+ sourcePath: repo,
+ worktreePath: worktree,
+ }),
+ ).resolves.toEqual({ outcome: 'restored' });
+ });
+
+ it('reports a deleted branch without creating anything', async () => {
+ await run();
+ git(repo, 'branch', '-D', BRANCH);
+ await expect(
+ restoreOwnedWorktree({
+ branch: BRANCH,
+ rootDir: root,
+ sourcePath: repo,
+ worktreePath: worktree,
+ }),
+ ).resolves.toEqual({ outcome: 'branchMissing' });
+ expect(existsSync(worktree)).toBe(false);
+ });
+
+ it('reports an unreadable source repository as an error, never as a missing branch', async () => {
+ await run();
+ await rm(path.join(repo, '.git'), { force: true, recursive: true });
+ await expect(
+ restoreOwnedWorktree({
+ branch: BRANCH,
+ rootDir: root,
+ sourcePath: repo,
+ worktreePath: worktree,
+ }),
+ ).resolves.toMatchObject({ outcome: 'error' });
+ await expect(
+ restoreOwnedWorktree({
+ branch: BRANCH,
+ rootDir: root,
+ sourcePath: path.join(repo, 'unmounted'),
+ worktreePath: worktree,
+ }),
+ ).resolves.toMatchObject({ outcome: 'error' });
+ });
+
+ it('refuses a path outside the root', async () => {
+ await expect(
+ restoreOwnedWorktree({
+ branch: BRANCH,
+ rootDir: root,
+ sourcePath: repo,
+ worktreePath: path.join(path.dirname(root), 'elsewhere'),
+ }),
+ ).resolves.toMatchObject({ outcome: 'refused' });
+ });
+});
diff --git a/packages/local-file-shell/src/git/index.ts b/packages/local-file-shell/src/git/index.ts
index a005f5982a2..d67536e7f1e 100644
--- a/packages/local-file-shell/src/git/index.ts
+++ b/packages/local-file-shell/src/git/index.ts
@@ -1,5 +1,7 @@
export * from './branches';
export * from './info';
+export * from './ownedWorktree';
+export * from './ownerMarker';
export * from './pullRequest';
export * from './repoType';
export * from './sync';
diff --git a/packages/local-file-shell/src/git/ownedWorktree.ts b/packages/local-file-shell/src/git/ownedWorktree.ts
new file mode 100644
index 00000000000..04c92d22d00
--- /dev/null
+++ b/packages/local-file-shell/src/git/ownedWorktree.ts
@@ -0,0 +1,439 @@
+import { execFile } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { lstat, mkdir, readFile, realpath, rm } from 'node:fs/promises';
+import { homedir } from 'node:os';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+import { createLogger } from '../logger';
+import { isInvalidBranchRef } from './branches';
+import { isValidOwnerToken, readOwnerMarker, writeOwnerMarker } from './ownerMarker';
+import type { GitOwnedWorktreeCleanupResult, GitOwnedWorktreeRestoreResult } from './types';
+import { parseGitWorktreeList } from './worktrees';
+
+const log = createLogger('local-file-shell:git:owned-worktree');
+const warn = (message: string, ...args: unknown[]) => log.warn(message, ...args);
+const execFileAsync = promisify(execFile);
+
+/**
+ * Cleanup and restore of the worktrees the app created for a conversation
+ * (`~/.lobehub/worktrees/<repoKey>/<branch>`). Everything that decides whether
+ * a folder may be deleted runs here, on the device that holds it: the server
+ * only names a path, and a path is acted on only when every guard agrees it is
+ * a linked worktree of that source repo inside the app's worktree root.
+ */
+
+/** Whole-operation budget; a slow `git worktree remove` falls back before it. */
+const CLEANUP_TIMEOUT_MS = 90_000;
+const GIT_REMOVE_TIMEOUT_MS = 45_000;
+const GIT_TIMEOUT_MS = 15_000;
+/** Node's `rm` retries EBUSY / ENOTEMPTY / EPERM (Windows file locks, a watcher). */
+const RM_RETRY = { maxRetries: 5, retryDelay: 200 } as const;
+
+export const defaultOwnedWorktreeRoot = () => path.join(homedir(), '.lobehub', 'worktrees');
+
+const git = async (cwd: string, args: string[], timeout = GIT_TIMEOUT_MS) =>
+ (await execFileAsync('git', args, { cwd, maxBuffer: 16 * 1024 * 1024, timeout })).stdout;
+
+const gitError = (error: any, fallback: string): string =>
+ (error?.stderr ?? error?.message ?? '').toString().trim() || fallback;
+
+const safeRealpath = async (target: string): Promise<string> => {
+ try {
+ return await realpath(target);
+ } catch {
+ return path.resolve(target);
+ }
+};
+
+/** `child` is strictly below `parent` (both already resolved). */
+const isStrictlyInside = (parent: string, child: string): boolean => {
+ const relative = path.relative(parent, child);
+ return !!relative && !relative.startsWith('..') && !path.isAbsolute(relative);
+};
+
+class GuardError extends Error {}
+
+/**
+ * The lexical half of the path guard, which also holds for a folder that no
+ * longer exists: absolute, and below the root once `..` is resolved.
+ */
+const assertLexicallyInsideRoot = (root: string, worktreePath: string) => {
+ if (!path.isAbsolute(worktreePath))
+ throw new GuardError(`Worktree path must be absolute: ${worktreePath}`);
+ if (!isStrictlyInside(path.resolve(root), path.resolve(worktreePath)))
+ throw new GuardError(`Not inside the app's worktree folder: ${worktreePath}`);
+};
+
+/**
+ * The on-disk half: with symlinks resolved the folder is still below the root
+ * (a symlinked worktree or root cannot point the delete elsewhere), and it is
+ * a real directory, not a link to one.
+ */
+const assertResolvedInsideRoot = async (root: string, worktreePath: string) => {
+ const stat = await lstat(worktreePath);
+ if (stat.isSymbolicLink() || !stat.isDirectory())
+ throw new GuardError(`Not a worktree folder: ${worktreePath}`);
+ const [realRoot, realTarget] = await Promise.all([
+ safeRealpath(root),
+ safeRealpath(worktreePath),
+ ]);
+ if (!isStrictlyInside(realRoot, realTarget))
+ throw new GuardError(`Resolves outside the app's worktree folder: ${worktreePath}`);
+};
+
+interface ListedWorktree {
+ branch?: string;
+ locked?: boolean;
+ path: string;
+}
+
+/**
+ * The source repo's own view: the worktree must be one of its linked
+ * worktrees (registered, not the main checkout, not bare).
+ */
+const findLinkedWorktree = async (
+ sourcePath: string,
+ worktreePath: string,
+): Promise<ListedWorktree | undefined> => {
+ const stdout = await git(sourcePath, ['worktree', 'list', '--porcelain', '-z']);
+ const [main, ...linked] = parseGitWorktreeList(stdout);
+ const target = await safeRealpath(worktreePath);
+ if (main && (await safeRealpath(main.path)) === target)
+ throw new GuardError('Refusing to remove the main worktree');
+ for (const entry of linked) {
+ if (entry.bare) continue;
+ if ((await safeRealpath(entry.path)) === target) return entry;
+ }
+};
+
+/** The repo's shared git dir (`<source>/.git` for a normal checkout). */
+const commonGitDir = async (sourcePath: string): Promise<string> => {
+ const out = (await git(sourcePath, ['rev-parse', '--git-common-dir'])).trim();
+ return safeRealpath(path.resolve(sourcePath, out));
+};
+
+/**
+ * Whether this cleanup may act on the worktree: a receipt must match. A
+ * worktree created before receipts existed has none; it may still be cleaned
+ * automatically (only ever when clean, its branch kept), but never discarded.
+ */
+const assertOwner = async (
+ worktreePath: string,
+ ownerToken: string | undefined,
+ discard: boolean,
+) => {
+ const marker = await readOwnerMarker(worktreePath);
+ if (marker) {
+ if (marker !== ownerToken) throw new GuardError('The worktree belongs to another conversation');
+ return;
+ }
+ if (discard)
+ throw new GuardError(
+ 'The worktree has no ownership receipt; delete it by hand if it is not needed',
+ );
+};
+
+/**
+ * A detached HEAD whose commits no branch holds would lose them with the
+ * worktree. Give them a branch first (`lobehub/detached-<sha>`) and report it,
+ * so they survive and a restore checks them out again.
+ */
+const keepDetachedCommits = async (sourcePath: string, worktreePath: string) => {
+ const head = (await git(worktreePath, ['rev-parse', 'HEAD'])).trim();
+ const holders = (
+ await git(sourcePath, ['for-each-ref', '--count=1', '--contains', head, 'refs/heads'])
+ ).trim();
+ if (holders) return undefined;
+ const branch = `lobehub/detached-${head.slice(0, 12)}`;
+ await git(sourcePath, ['branch', '--force', branch, head]);
+ return branch;
+};
+
+/**
+ * A linked worktree's `.git` is a FILE pointing at
+ * `<common git dir>/worktrees/<name>`; anything else (a full clone, a pointer
+ * into another repository) is not this repo's worktree.
+ */
+const assertGitFilePointsToSource = async (sourcePath: string, worktreePath: string) => {
+ const dotGit = path.join(worktreePath, '.git');
+ const stat = await lstat(dotGit).catch(() => undefined);
+ if (!stat?.isFile()) throw new GuardError('Worktree has no .git file');
+ const match = /^gitdir:\s*(.+)$/m.exec(await readFile(dotGit, 'utf8'));
+ if (!match) throw new GuardError('Worktree .git file has no gitdir');
+ const gitdir = await safeRealpath(path.resolve(worktreePath, match[1].trim()));
+ const worktreesDir = path.join(await commonGitDir(sourcePath), 'worktrees');
+ if (!isStrictlyInside(worktreesDir, gitdir))
+ throw new GuardError('Worktree .git does not point back to the source repository');
+};
+
+/**
+ * Uncommitted work that would be lost: tracked changes (staged or not) and
+ * untracked files — inside submodules too, whose working trees the removal
+ * deletes with the worktree. Ignored files (`node_modules`, build output) do
+ * not count, and neither do unpushed commits — the branch is always kept.
+ */
+export const countUncommittedFiles = async (worktreePath: string): Promise<number> => {
+ const stdout = await git(worktreePath, [
+ 'status',
+ '--porcelain=v1',
+ '-z',
+ '--untracked-files=all',
+ // Overrides any `submodule.<name>.ignore` config: a dirty submodule is dirty.
+ '--ignore-submodules=none',
+ ]);
+ const tokens = stdout.split('\0');
+ let count = 0;
+ for (let i = 0; i < tokens.length; i += 1) {
+ const token = tokens[i];
+ if (!token) continue;
+ count += 1;
+ // A rename / copy record carries its original path as the next token.
+ if (token[0] === 'R' || token[0] === 'C') i += 1;
+ }
+ return count;
+};
+
+/**
+ * Submodules whose checked-out commit no remote branch holds. A linked
+ * worktree keeps its submodules' repositories inside its own git admin dir
+ * (`<common>/worktrees/<name>/modules/`), so removing the worktree would take
+ * such commits with it — a clean status says nothing about them.
+ */
+export const countSubmodulesWithLocalCommits = async (worktreePath: string): Promise<number> => {
+ const status = await git(worktreePath, ['submodule', 'status', '--recursive']).catch(() => '');
+ let count = 0;
+ for (const line of status.split('\n')) {
+ // `-` marks a submodule that is not checked out: nothing local to lose.
+ if (!line.trim() || line.startsWith('-')) continue;
+ const subPath = line.slice(1).trim().split(/\s+/)[1];
+ if (!subPath) continue;
+ const dir = path.join(worktreePath, subPath);
+ const head = (await git(dir, ['rev-parse', 'HEAD'])).trim();
+ const held = (
+ await git(dir, ['for-each-ref', '--count=1', '--contains', head, 'refs/remotes'])
+ ).trim();
+ if (!held) count += 1;
+ }
+ return count;
+};
+
+const prune = async (sourcePath: string) => {
+ await git(sourcePath, ['worktree', 'prune']).catch((error) =>
+ warn('git worktree prune failed in %s: %O', sourcePath, error),
+ );
+};
+
+/**
+ * Delete the folder after `git worktree remove` gave up (a file lock, a
+ * submodule, a huge `node_modules` hitting its timeout): a full delete in
+ * place, never a move to a trash folder. Node's `rm` retries the transient
+ * EBUSY / ENOTEMPTY / EPERM on its own.
+ */
+const deleteFolder = (worktreePath: string) =>
+ rm(worktreePath, { force: true, recursive: true, ...RM_RETRY });
+
+const withTimeout = async <T>(work: Promise<T>, ms: number, onTimeout: () => T): Promise<T> => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race([
+ work,
+ new Promise<T>((resolve) => {
+ timer = setTimeout(() => resolve(onTimeout()), ms);
+ }),
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+};
+
+/**
+ * Cleanups still running on this device, by resolved path. The cleanup's
+ * overall budget can expire while a large delete goes on; until it actually
+ * stops, a restore (or another cleanup) of the same path waits for it rather
+ * than writing into a folder that is still disappearing.
+ */
+const deletionsInFlight = new Map<string, Promise<unknown>>();
+
+const waitForDeletion = async (worktreePath: string) => {
+ const inFlight = deletionsInFlight.get(path.resolve(worktreePath));
+ if (inFlight) await inFlight.catch(() => undefined);
+};
+
+const trackDeletion = async <T>(worktreePath: string, work: () => Promise<T>): Promise<T> => {
+ const key = path.resolve(worktreePath);
+ const running = work();
+ deletionsInFlight.set(key, running);
+ try {
+ return await running;
+ } finally {
+ if (deletionsInFlight.get(key) === running) deletionsInFlight.delete(key);
+ }
+};
+
+export interface CleanupOwnedWorktreeParams {
+ /** Delete even with uncommitted work: the user confirmed "Discard and delete". */
+ discard?: boolean;
+ /** Stands in for `git worktree remove`; tests only. Device RPCs never pass it. */
+ gitRemove?: (sourcePath: string, worktreePath: string) => Promise<unknown>;
+ /** The creation receipt the claiming topic holds (see `ownerMarker.ts`). */
+ ownerToken?: string;
+ /** The worktree root; tests only. Device RPCs never pass it. */
+ rootDir?: string;
+ sourcePath: string;
+ worktreePath: string;
+}
+
+const gitWorktreeRemove = (sourcePath: string, worktreePath: string) =>
+ // `--force`: ignored files alone make a plain remove refuse. One `--force`
+ // never removes a locked worktree, which the caller rules out first.
+ git(sourcePath, ['worktree', 'remove', '--force', worktreePath], GIT_REMOVE_TIMEOUT_MS);
+
+const runCleanup = async ({
+ discard,
+ gitRemove = gitWorktreeRemove,
+ ownerToken,
+ rootDir,
+ sourcePath,
+ worktreePath,
+}: CleanupOwnedWorktreeParams): Promise<GitOwnedWorktreeCleanupResult> => {
+ const root = rootDir ?? defaultOwnedWorktreeRoot();
+ if (!sourcePath?.trim() || !worktreePath?.trim())
+ return { error: 'Source and worktree paths are required', outcome: 'refused' };
+
+ try {
+ assertLexicallyInsideRoot(root, worktreePath);
+
+ // Gone already (deleted by hand, or a cleanup that finished after its
+ // report was lost): only the stale registration is left to drop.
+ if (!existsSync(worktreePath)) {
+ if (existsSync(sourcePath)) await prune(sourcePath);
+ return { outcome: 'removed' };
+ }
+
+ await assertResolvedInsideRoot(root, worktreePath);
+ const listed = await findLinkedWorktree(sourcePath, worktreePath);
+ if (!listed) throw new GuardError('Not a worktree of the source repository');
+ await assertGitFilePointsToSource(sourcePath, worktreePath);
+ await assertOwner(worktreePath, ownerToken, !!discard);
+
+ let branch = listed.branch;
+ if (listed.locked) return { branch, outcome: 'locked' };
+
+ if (!discard) {
+ const dirtyFiles = await countUncommittedFiles(worktreePath);
+ if (dirtyFiles > 0) return { branch, dirtyFiles, outcome: 'dirty' };
+ const unpushedSubmodules = await countSubmodulesWithLocalCommits(worktreePath);
+ if (unpushedSubmodules > 0)
+ return { branch, dirtyFiles: 0, outcome: 'dirty', unpushedSubmodules };
+ }
+
+ if (!branch) branch = await keepDetachedCommits(sourcePath, worktreePath);
+
+ try {
+ await gitRemove(sourcePath, listed.path);
+ } catch (error) {
+ warn('git worktree remove failed for %s, removing the folder: %O', worktreePath, error);
+ await deleteFolder(worktreePath);
+ }
+ await prune(sourcePath);
+
+ if (existsSync(worktreePath))
+ return { branch, error: 'The worktree folder could not be removed', outcome: 'error' };
+ return { branch, outcome: 'removed' };
+ } catch (error) {
+ if (error instanceof GuardError) return { error: error.message, outcome: 'refused' };
+ return { error: gitError(error, 'Worktree cleanup failed'), outcome: 'error' };
+ }
+};
+
+/**
+ * Remove an app-created worktree's folder when it holds no uncommitted work
+ * (or `discard` says to drop it). The branch is never touched. Returns what
+ * happened instead of throwing, so the caller can record it as is.
+ */
+export const cleanupOwnedWorktree = async (
+ params: CleanupOwnedWorktreeParams,
+): Promise<GitOwnedWorktreeCleanupResult> => {
+ // One cleanup per folder at a time, and the whole of it is tracked — from
+ // its first check to the end of the delete, past the answer's time budget —
+ // so a restore of the same folder never runs in between.
+ await waitForDeletion(params.worktreePath);
+ return withTimeout(
+ trackDeletion(params.worktreePath, () => runCleanup(params)),
+ CLEANUP_TIMEOUT_MS,
+ () => ({ error: 'Worktree cleanup timed out', outcome: 'error' }),
+ );
+};
+
+/**
+ * Whether the branch exists in the source repository. Only git's own "no such
+ * ref" answer (`show-ref` exit 1) means missing: a source that cannot be read
+ * (an unmounted drive, a moved repo) throws, so it is never mistaken for a
+ * deleted branch — which would send the topic back to its source for good.
+ */
+const branchExists = async (sourcePath: string, branch: string): Promise<boolean> => {
+ // Throws when the source is not a readable repository.
+ await commonGitDir(sourcePath);
+ try {
+ await git(sourcePath, ['show-ref', '--verify', '--quiet', `refs/heads/${branch}`]);
+ return true;
+ } catch (error: any) {
+ if (error?.code === 1) return false;
+ throw error;
+ }
+};
+
+export interface RestoreOwnedWorktreeParams {
+ branch: string;
+ /** Written back as the worktree's creation receipt (see `ownerMarker.ts`). */
+ ownerToken?: string;
+ /** The worktree root; tests only. Device RPCs never pass it. */
+ rootDir?: string;
+ sourcePath: string;
+ worktreePath: string;
+}
+
+/**
+ * Check a cleaned-up worktree out again at its original path, on its original
+ * branch (`git worktree add <path> <branch>`), for a conversation brought back
+ * from the archive or the recycle bin. A worktree already there on that branch
+ * counts as restored.
+ */
+export const restoreOwnedWorktree = async ({
+ branch,
+ ownerToken,
+ rootDir,
+ sourcePath,
+ worktreePath,
+}: RestoreOwnedWorktreeParams): Promise<GitOwnedWorktreeRestoreResult> => {
+ const root = rootDir ?? defaultOwnedWorktreeRoot();
+ if (!sourcePath?.trim() || !worktreePath?.trim() || !branch?.trim())
+ return { error: 'Source path, worktree path and branch are required', outcome: 'refused' };
+ if (isInvalidBranchRef(branch)) return { error: `Invalid branch: ${branch}`, outcome: 'refused' };
+
+ try {
+ assertLexicallyInsideRoot(root, worktreePath);
+ // A cleanup that timed out may still be deleting this folder.
+ await waitForDeletion(worktreePath);
+
+ if (existsSync(worktreePath)) {
+ await assertResolvedInsideRoot(root, worktreePath);
+ const listed = await findLinkedWorktree(sourcePath, worktreePath);
+ if (listed?.branch === branch) return { outcome: 'restored' };
+ return { error: `Folder already exists: ${worktreePath}`, outcome: 'refused' };
+ }
+
+ if (!(await branchExists(sourcePath, branch))) return { outcome: 'branchMissing' };
+
+ // A registration left behind for this path would make `add` refuse.
+ await prune(sourcePath);
+ await mkdir(path.dirname(worktreePath), { recursive: true });
+ await git(sourcePath, ['worktree', 'add', worktreePath, branch], 30_000);
+ if (isValidOwnerToken(ownerToken)) await writeOwnerMarker(worktreePath, ownerToken);
+ return { outcome: 'restored' };
+ } catch (error) {
+ if (error instanceof GuardError) return { error: error.message, outcome: 'refused' };
+ return { error: gitError(error, 'git worktree add failed'), outcome: 'error' };
+ }
+};
diff --git a/packages/local-file-shell/src/git/ownerMarker.ts b/packages/local-file-shell/src/git/ownerMarker.ts
new file mode 100644
index 00000000000..9aa528ad3e1
--- /dev/null
+++ b/packages/local-file-shell/src/git/ownerMarker.ts
@@ -0,0 +1,38 @@
+import { execFile } from 'node:child_process';
+import { existsSync } from 'node:fs';
+import { readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+
+const execFileAsync = promisify(execFile);
+
+/**
+ * The creation receipt: when the app creates a worktree for a conversation it
+ * writes a random owner token into the worktree's own git admin dir
+ * (`<common git dir>/worktrees/<name>/`), which only the device can read. A
+ * cleanup must present the same token, so a topic that merely claims a path —
+ * its metadata is client-written — can never delete another topic's worktree.
+ */
+export const OWNER_MARKER_FILE = 'lobehub-owner';
+const OWNER_TOKEN_PATTERN = /^[\w-]{16,128}$/;
+
+export const isValidOwnerToken = (token: unknown): token is string =>
+ typeof token === 'string' && OWNER_TOKEN_PATTERN.test(token);
+
+const worktreeAdminDir = async (worktreePath: string) =>
+ (
+ await execFileAsync('git', ['rev-parse', '--absolute-git-dir'], {
+ cwd: worktreePath,
+ timeout: 15_000,
+ })
+ ).stdout.trim();
+
+export const writeOwnerMarker = async (worktreePath: string, token: string) => {
+ if (!isValidOwnerToken(token)) throw new Error('Invalid owner token');
+ await writeFile(path.join(await worktreeAdminDir(worktreePath), OWNER_MARKER_FILE), token);
+};
+
+export const readOwnerMarker = async (worktreePath: string): Promise<string | undefined> => {
+ const file = path.join(await worktreeAdminDir(worktreePath), OWNER_MARKER_FILE);
+ return existsSync(file) ? (await readFile(file, 'utf8')).trim() : undefined;
+};
diff --git a/packages/local-file-shell/src/git/types.ts b/packages/local-file-shell/src/git/types.ts
index a503364966e..f50cef5112c 100644
--- a/packages/local-file-shell/src/git/types.ts
+++ b/packages/local-file-shell/src/git/types.ts
@@ -350,8 +350,26 @@ export interface GitRemoveWorktreeResult {
success: boolean;
}
+/** See `cleanupOwnedWorktree`; mirrors `OwnedWorktreeCleanupResult` in `@lobechat/types`. */
+export interface GitOwnedWorktreeCleanupResult {
+ branch?: string;
+ dirtyFiles?: number;
+ error?: string;
+ outcome: 'dirty' | 'error' | 'locked' | 'refused' | 'removed';
+ /** With `dirty`: submodules whose commits no remote holds (they would go with the worktree). */
+ unpushedSubmodules?: number;
+}
+
+/** See `restoreOwnedWorktree`; mirrors `OwnedWorktreeRestoreResult` in `@lobechat/types`. */
+export interface GitOwnedWorktreeRestoreResult {
+ error?: string;
+ outcome: 'branchMissing' | 'error' | 'refused' | 'restored';
+}
+
export interface GitAddWorktreeResult {
error?: string;
+ /** Echo of the creation receipt written into the worktree (see `ownedWorktree.ts`). */
+ ownerToken?: string;
/** Echo of the start point the worktree's branch was cut from; see {@link GitCheckoutResult.startPoint}. */
startPoint?: string;
success: boolean;
diff --git a/packages/local-file-shell/src/git/worktrees.ts b/packages/local-file-shell/src/git/worktrees.ts
index ba71c6e461f..4f1dc51f9f5 100644
--- a/packages/local-file-shell/src/git/worktrees.ts
+++ b/packages/local-file-shell/src/git/worktrees.ts
@@ -6,6 +6,7 @@ import { promisify } from 'node:util';
import { isInvalidBranchRef, qualifyStartPoint } from './branches';
import { getGitWorkingTreeStatus } from './info';
+import { isValidOwnerToken, writeOwnerMarker } from './ownerMarker';
import type {
GitAddWorktreeResult,
GitRemoveWorktreeResult,
@@ -181,11 +182,19 @@ export const removeGitWorktree = async (payload: {
*/
export const addGitWorktree = async (payload: {
branch: string;
+ /**
+ * Set when the app creates the worktree for a conversation: written into the
+ * worktree's git admin dir as its creation receipt (`ownedWorktree.ts`), and
+ * echoed back so the caller knows this device recorded it.
+ */
+ ownerToken?: string;
path: string;
startPoint?: string;
worktreePath: string;
}): Promise<GitAddWorktreeResult> => {
- const { path: dirPath, branch, startPoint, worktreePath } = payload;
+ const { path: dirPath, branch, ownerToken, startPoint, worktreePath } = payload;
+ if (ownerToken !== undefined && !isValidOwnerToken(ownerToken))
+ return { error: 'Invalid owner token', success: false };
if (!dirPath?.trim()) return { error: 'Working directory is required', success: false };
if (!branch?.trim()) return { error: 'Branch name is required', success: false };
if (!worktreePath?.trim()) return { error: 'Worktree path is required', success: false };
@@ -220,9 +229,25 @@ export const addGitWorktree = async (payload: {
],
{ cwd: dirPath, timeout: 30_000 },
);
- return startPoint
- ? { startPoint, success: true, worktreePath }
- : { success: true, worktreePath };
+ // The receipt is what lets this conversation clean the worktree up later;
+ // without it a later cleanup refuses, so report it as part of the add.
+ if (ownerToken) {
+ try {
+ await writeOwnerMarker(worktreePath, ownerToken);
+ } catch (error: any) {
+ return {
+ error: `Worktree created, but its ownership receipt could not be written: ${error?.message ?? error}`,
+ success: false,
+ worktreePath,
+ };
+ }
+ }
+ return {
+ ...(ownerToken && { ownerToken }),
+ ...(startPoint && { startPoint }),
+ success: true,
+ worktreePath,
+ };
} catch (error: any) {
const stderr: string = (error?.stderr ?? error?.message ?? '').toString().trim();
return { error: stderr || 'git worktree add failed', success: false };
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index c0db254571b..d9a5449c797 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3924,6 +3924,30 @@ export default {
'workingPanel.overview.execution.device': 'Connected device',
'workingPanel.overview.execution.local': 'This device',
'workingPanel.overview.files': 'Files',
+ 'workingPanel.overview.keptWorktree.details': 'Details',
+ 'workingPanel.overview.keptWorktree.discard': 'Discard changes and delete',
+ 'workingPanel.overview.keptWorktree.discardConfirm':
+ "This deletes the worktree and everything uncommitted in it, including ignored files. This can't be undone. Commits on its branch are kept.",
+ 'workingPanel.overview.keptWorktree.discardConfirmTitle':
+ 'Discard changes and delete the worktree?',
+ 'workingPanel.overview.keptWorktree.discardFailed': 'Could not delete the worktree',
+ 'workingPanel.overview.keptWorktree.discardPending':
+ "The device is offline. The worktree will be deleted when it's back online.",
+ 'workingPanel.overview.keptWorktree.discarded': 'Worktree deleted. Its branch was kept.',
+ 'workingPanel.overview.keptWorktree.discarding': 'Deleting the worktree…',
+ 'workingPanel.overview.keptWorktree.failedTitle': "Worktree couldn't be cleaned up",
+ 'workingPanel.overview.keptWorktree.hideDetails': 'Hide details',
+ 'workingPanel.overview.keptWorktree.keep': 'Keep',
+ 'workingPanel.overview.keptWorktree.keepFailed': 'Could not keep the worktree',
+ 'workingPanel.overview.keptWorktree.keptToast':
+ "Worktree kept. It won't be cleaned up automatically.",
+ 'workingPanel.overview.keptWorktree.removed': 'Worktree cleaned up · branch {{branch}} kept',
+ 'workingPanel.overview.keptWorktree.removedHint':
+ 'It was removed when this topic was archived or moved to the recycle bin. Sending a message checks the branch out again at the same path.',
+ 'workingPanel.overview.keptWorktree.submoduleTitle':
+ 'Worktree kept: a submodule has commits no remote holds',
+ 'workingPanel.overview.keptWorktree.title_one': 'Worktree kept: {{count}} uncommitted file',
+ 'workingPanel.overview.keptWorktree.title_other': 'Worktree kept: {{count}} uncommitted files',
'workingPanel.overview.outputs': 'Outputs',
'workingPanel.overview.ports.copied': 'Link copied',
'workingPanel.overview.ports.copy': 'Copy link',
@@ -4483,6 +4507,13 @@ export default {
'userFeedbackCard.count_one': '{{count}} comment',
'userFeedbackCard.count_other': '{{count}} comments',
'userFeedbackCard.title': 'User feedback',
+ 'worktreeRestore.branchMissing': "Can't restore the worktree",
+ 'worktreeRestore.branchMissingDesc':
+ 'The branch {{branch}} no longer exists, so this conversation continues in the source repository.',
+ 'worktreeRestore.failed': "Couldn't restore the worktree",
+ 'worktreeRestore.stillCleaning':
+ 'The worktree is still being cleaned up. Try sending again in a moment.',
+ 'worktreeRestore.waiting': 'Waiting for the worktree cleanup to finish before restoring it…',
'you': 'You',
'sandboxDrive.manageEnvironments': 'Settings',
'sandboxDrive.openStorage': 'Sandbox Storage',
diff --git a/packages/types/src/device.ts b/packages/types/src/device.ts
index 83aee2fa8ff..408680cdc15 100644
--- a/packages/types/src/device.ts
+++ b/packages/types/src/device.ts
@@ -671,6 +671,8 @@ export interface DeviceGitRemoveWorktreeResult {
/** Result of the `addGitWorktree` device RPC. Mirrors the desktop shape. */
export interface DeviceGitAddWorktreeResult {
error?: string;
+ /** Echo of the creation receipt the device wrote into the worktree. */
+ ownerToken?: string;
reason?: typeof DEVICE_GIT_OUTDATED;
/** Echo of the start point; see {@link DeviceGitCheckoutResult.startPoint}. */
startPoint?: string;
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 2a1019f5b44..9d4300736d9 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -103,6 +103,7 @@ export * from './inboundWebhook';
export * from './oauthApp';
export * from './openai/chat';
export * from './openai/plugin';
+export * from './ownedWorktree';
export * from './subscription';
export * from './trace';
export * from './understanding';
diff --git a/packages/types/src/ownedWorktree.test.ts b/packages/types/src/ownedWorktree.test.ts
new file mode 100644
index 00000000000..9a66872cf0e
--- /dev/null
+++ b/packages/types/src/ownedWorktree.test.ts
@@ -0,0 +1,185 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ claimAutoCreatedWorktree,
+ findOwnedWorktree,
+ isRetiredTopicStatus,
+ resolveOwnedWorktrees,
+} from './ownedWorktree';
+
+const NOW = () => '2026-11-17T00:00:00.000Z';
+const WT = '/Users/me/.lobehub/worktrees/repo-1a2b3c4d/quiet-hill';
+
+describe('claimAutoCreatedWorktree', () => {
+ it('records the worktree the app created, with its branch and device', () => {
+ const claimed = claimAutoCreatedWorktree(
+ {
+ boundDeviceId: 'dev-1',
+ workingDirectoryConfig: {
+ git: {
+ activeWorktree: WT,
+ autoCreated: true,
+ autoCreatedAt: '2026-11-16T00:00:00.000Z',
+ branch: 'lobehub/quiet-hill',
+ },
+ path: '/code/repo',
+ sessionPath: WT,
+ },
+ },
+ NOW,
+ );
+
+ expect(claimed.ownedWorktrees).toEqual([
+ {
+ branch: 'lobehub/quiet-hill',
+ createdAt: '2026-11-16T00:00:00.000Z',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ]);
+ });
+
+ it('is idempotent and keeps a recorded cleanup state', () => {
+ const metadata = {
+ ownedWorktrees: [
+ {
+ cleanup: { at: 'x', state: 'kept' as const },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ workingDirectoryConfig: {
+ git: { activeWorktree: WT, autoCreated: true },
+ path: '/code/repo',
+ },
+ };
+ expect(claimAutoCreatedWorktree(metadata, NOW)).toBe(metadata);
+ });
+
+ it('carries the creation receipt into the claim', () => {
+ const claimed = claimAutoCreatedWorktree(
+ {
+ workingDirectoryConfig: {
+ git: { activeWorktree: WT, autoCreated: true, ownerToken: 'receipt-0123456789abcdef' },
+ path: '/code/repo',
+ },
+ },
+ NOW,
+ );
+ expect(claimed.ownedWorktrees?.[0].ownerToken).toBe('receipt-0123456789abcdef');
+ });
+
+ it('fills a device id that arrives later', () => {
+ const claimed = claimAutoCreatedWorktree(
+ {
+ boundDeviceId: 'dev-2',
+ ownedWorktrees: [{ createdAt: 'y', path: WT, sourcePath: '/code/repo' }],
+ workingDirectoryConfig: {
+ git: { activeWorktree: WT, autoCreated: true },
+ path: '/code/repo',
+ },
+ },
+ NOW,
+ );
+ expect(claimed.ownedWorktrees?.[0].deviceId).toBe('dev-2');
+ });
+
+ it('claims nothing for a worktree the user picked', () => {
+ const metadata = {
+ workingDirectoryConfig: { git: { activeWorktree: WT }, path: '/code/repo' },
+ };
+ expect(claimAutoCreatedWorktree(metadata, NOW)).toBe(metadata);
+ });
+
+ it('keeps an earlier claim after the topic moved to another worktree', () => {
+ const first = claimAutoCreatedWorktree(
+ {
+ workingDirectoryConfig: {
+ git: { activeWorktree: WT, autoCreated: true },
+ path: '/code/repo',
+ },
+ },
+ NOW,
+ );
+ // The marker is dropped on a move (`dropStaleAutoCreated`); the claim stays.
+ const moved = claimAutoCreatedWorktree(
+ {
+ ...first,
+ workingDirectoryConfig: { git: { activeWorktree: '/other' }, path: '/code/repo' },
+ },
+ NOW,
+ );
+ expect(moved.ownedWorktrees?.map((entry) => entry.path)).toEqual([WT]);
+ });
+});
+
+describe('resolveOwnedWorktrees (backfill for existing topics)', () => {
+ it('backfills from autoCreated + activeWorktree', () => {
+ expect(
+ resolveOwnedWorktrees(
+ {
+ boundDeviceId: 'dev-1',
+ workingDirectoryConfig: {
+ git: { activeWorktree: WT, autoCreated: true, branch: 'lobehub/quiet-hill' },
+ path: '/code/repo',
+ },
+ },
+ NOW,
+ ),
+ ).toEqual([
+ {
+ branch: 'lobehub/quiet-hill',
+ createdAt: NOW(),
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ]);
+ });
+
+ it('backfills from sessionPath after the marker was dropped, without a branch', () => {
+ expect(
+ resolveOwnedWorktrees(
+ {
+ workingDirectoryConfig: {
+ git: { activeWorktree: '/elsewhere', branch: 'feat/x' },
+ path: '/code/repo',
+ sessionPath: WT,
+ },
+ },
+ NOW,
+ ),
+ ).toEqual([{ createdAt: NOW(), path: WT, sourcePath: '/code/repo' }]);
+ });
+
+ it('ignores a sessionPath that is the source itself, and topics without one', () => {
+ expect(
+ resolveOwnedWorktrees({
+ workingDirectoryConfig: { path: '/code/repo', sessionPath: '/code/repo/' },
+ }),
+ ).toEqual([]);
+ expect(resolveOwnedWorktrees({ workingDirectoryConfig: { path: '/code/repo' } })).toEqual([]);
+ expect(resolveOwnedWorktrees(undefined)).toEqual([]);
+ });
+
+ it('does not duplicate a claimed path', () => {
+ const owned = resolveOwnedWorktrees({
+ ownedWorktrees: [{ createdAt: 'y', path: WT, sourcePath: '/code/repo' }],
+ workingDirectoryConfig: { path: '/code/repo', sessionPath: `${WT}/` },
+ });
+ expect(owned).toHaveLength(1);
+ expect(findOwnedWorktree({ ownedWorktrees: owned }, WT)?.sourcePath).toBe('/code/repo');
+ });
+});
+
+describe('isRetiredTopicStatus', () => {
+ it('treats the UI archive (completed) and legacy archived as retired', () => {
+ expect(isRetiredTopicStatus('completed')).toBe(true);
+ expect(isRetiredTopicStatus('archived')).toBe(true);
+ expect(isRetiredTopicStatus('active')).toBe(false);
+ expect(isRetiredTopicStatus(null)).toBe(false);
+ });
+});
diff --git a/packages/types/src/ownedWorktree.ts b/packages/types/src/ownedWorktree.ts
new file mode 100644
index 00000000000..3a67e698dfc
--- /dev/null
+++ b/packages/types/src/ownedWorktree.ts
@@ -0,0 +1,242 @@
+import type { ChatTopicMetadata } from './topic';
+import type { WorkingDirConfig } from './workingDir';
+
+/**
+ * Worktrees a topic owns: the ones the app created for it (Better Coding
+ * Experience "New worktree" on the first send). Recorded on the topic's
+ * metadata as `ownedWorktrees` and never rewritten by a later worktree change
+ * — unlike `workingDirectoryConfig.git.autoCreated`, which is dropped as soon
+ * as the topic moves to another checkout. Retiring the topic (archive or
+ * recycle bin) removes the worktree's folder on its device; the branch is
+ * always kept, so a restored topic can check it out again at the same path.
+ */
+
+/**
+ * Where the automatic cleanup of an owned worktree stands. Absent: the topic
+ * is live and nothing was tried.
+ *
+ * - `pending`: the topic was retired but its device could not run the cleanup
+ * yet (offline, or too old for the RPC); the device runs it when it connects.
+ * - `running`: a cleanup was claimed and is in flight, so a second executor
+ * (another drain, the desktop on startup) leaves it alone.
+ * - `removed`: the folder is gone; the branch is kept.
+ * - `keptDirty`: the worktree had uncommitted work, so it was kept.
+ * - `kept`: the user chose to keep it; never cleaned automatically again.
+ * - `failed`: the device refused or git failed (`reason`), so it was left as is.
+ */
+export type OwnedWorktreeCleanupState =
+ 'failed' | 'kept' | 'keptDirty' | 'pending' | 'removed' | 'running';
+
+/** Why a cleanup was started. */
+export type OwnedWorktreeCleanupTrigger = 'archived' | 'discarded' | 'trashed';
+
+export interface OwnedWorktreeCleanup {
+ /** ISO time of the last state change. */
+ at: string;
+ /** Tracked changes plus untracked files counted when it was kept dirty. */
+ dirtyFiles?: number;
+ /** Device/git message behind `failed`, or why a `pending` one waits. */
+ reason?: string;
+ state: OwnedWorktreeCleanupState;
+ trigger?: OwnedWorktreeCleanupTrigger;
+}
+
+export interface OwnedWorktree {
+ /**
+ * The branch the worktree was created on (`lobehub/…`). Absent only on a
+ * record backfilled from a topic that had already moved away from it; the
+ * device reports it back when the cleanup runs.
+ */
+ branch?: string;
+ cleanup?: OwnedWorktreeCleanup;
+ /** ISO time the worktree was created (or the record backfilled). */
+ createdAt: string;
+ /**
+ * The device that holds the folder — its gateway device id, also for this
+ * desktop. Absent only for a desktop that never registered with the gateway.
+ */
+ deviceId?: string;
+ /**
+ * The nonce the server signed {@link ownerToken} with, over the creator's
+ * user id: the server presents the token only for a topic of that creator.
+ */
+ ownerNonce?: string;
+ /**
+ * The worktree's creation receipt (`WorkingDirGitState.ownerToken`); the
+ * device cleans or restores it only for the matching token. Absent on
+ * worktrees created before receipts: those are only ever cleaned
+ * automatically (clean ones, branch kept), never discarded.
+ */
+ ownerToken?: string;
+ /** Absolute path of the worktree folder on that device. */
+ path: string;
+ /** The repository's main checkout the worktree belongs to. */
+ sourcePath: string;
+}
+
+/** Metadata keys these helpers read; a structural slice of `ChatTopicMetadata`. */
+export interface OwnedWorktreeMetadata {
+ boundDeviceId?: string;
+ ownedWorktrees?: OwnedWorktree[];
+ workingDirectoryConfig?: WorkingDirConfig;
+}
+
+/** A topic as the worktree cleanup reads it (recycle bin included). */
+export interface OwnedWorktreeTopicRow {
+ id: string;
+ isDeleted: boolean | null;
+ metadata: ChatTopicMetadata | null | undefined;
+ status: string | null;
+ userId: string;
+}
+
+/** Topic statuses that mean the run is live or waiting on the user: never clean under them. */
+export const OWNED_WORKTREE_HOLD_STATUSES = ['running', 'waitingForHuman'] as const;
+
+/** Topic statuses the UI calls "archived" (`completed`; `archived` is legacy). */
+export const RETIRED_TOPIC_STATUSES = ['completed', 'archived'] as const;
+
+export const isRetiredTopicStatus = (status: string | null | undefined): boolean =>
+ !!status && (RETIRED_TOPIC_STATUSES as readonly string[]).includes(status);
+
+const samePath = (a: string | undefined, b: string | undefined) =>
+ !!a && !!b && a.replace(/[/\\]+$/, '') === b.replace(/[/\\]+$/, '');
+
+/**
+ * Record the worktree the app created for this topic, when the metadata says
+ * the topic is on one (`git.autoCreated`). Idempotent: a path already recorded
+ * keeps its record, only gaining a device id it lacked. Returns the metadata
+ * unchanged (same reference) when there is nothing to add.
+ */
+export const claimAutoCreatedWorktree = <T extends OwnedWorktreeMetadata>(
+ metadata: T,
+ now: () => string = () => new Date().toISOString(),
+): T => {
+ const config = metadata.workingDirectoryConfig;
+ const git = config?.git;
+ const path = git?.autoCreated ? git.activeWorktree : undefined;
+ if (!config || !git || !path) return metadata;
+
+ const owned = metadata.ownedWorktrees ?? [];
+ const existing = owned.find((entry) => samePath(entry.path, path));
+ if (existing) {
+ if (existing.deviceId || !metadata.boundDeviceId) return metadata;
+ return {
+ ...metadata,
+ ownedWorktrees: owned.map((entry) =>
+ entry === existing ? { ...entry, deviceId: metadata.boundDeviceId } : entry,
+ ),
+ };
+ }
+
+ const entry: OwnedWorktree = {
+ ...(git.branch && { branch: git.branch }),
+ createdAt: git.autoCreatedAt ?? now(),
+ ...(metadata.boundDeviceId && { deviceId: metadata.boundDeviceId }),
+ ...(git.ownerToken && { ownerToken: git.ownerToken }),
+ ...(git.ownerNonce && { ownerNonce: git.ownerNonce }),
+ path,
+ sourcePath: config.path,
+ };
+ return { ...metadata, ownedWorktrees: [...owned, entry] };
+};
+
+/**
+ * The worktrees this topic owns, including the ones a topic created before
+ * `ownedWorktrees` existed: its marker (`autoCreated` + `activeWorktree`) or,
+ * once that marker was dropped by a move, the CLI start folder the app set to
+ * the worktree it created (`sessionPath`, only ever written for one). The
+ * backfilled records are what the caller persists on its first write.
+ */
+export const resolveOwnedWorktrees = (
+ metadata: OwnedWorktreeMetadata | null | undefined,
+ now: () => string = () => new Date().toISOString(),
+): OwnedWorktree[] => {
+ if (!metadata) return [];
+ const claimed = claimAutoCreatedWorktree(metadata, now);
+ const owned = [...(claimed.ownedWorktrees ?? [])];
+ const config = metadata.workingDirectoryConfig;
+ const sessionPath = config?.sessionPath;
+ if (
+ config &&
+ sessionPath &&
+ !samePath(sessionPath, config.path) &&
+ !owned.some((entry) => samePath(entry.path, sessionPath))
+ ) {
+ owned.push({
+ ...(samePath(config.git?.activeWorktree, sessionPath) &&
+ config.git?.branch && { branch: config.git.branch }),
+ createdAt: config.git?.autoCreatedAt ?? now(),
+ ...(metadata.boundDeviceId && { deviceId: metadata.boundDeviceId }),
+ path: sessionPath,
+ sourcePath: config.path,
+ });
+ }
+ return owned;
+};
+
+export const findOwnedWorktree = (
+ metadata: OwnedWorktreeMetadata | null | undefined,
+ path: string,
+): OwnedWorktree | undefined =>
+ resolveOwnedWorktrees(metadata).find((entry) => samePath(entry.path, path));
+
+/** The paths a topic runs in (current worktree and CLI start folder). */
+export const getTopicWorktreePaths = (
+ metadata: OwnedWorktreeMetadata | null | undefined,
+): string[] => {
+ const config = metadata?.workingDirectoryConfig;
+ return [config?.git?.activeWorktree, config?.sessionPath].filter(
+ (path): path is string => !!path,
+ );
+};
+
+/**
+ * What a device reports for one `cleanupOwnedWorktree` call. `removed` covers a
+ * folder that was already gone; `refused` is a guard rejection (outside the
+ * worktree root, not a linked worktree of the source…), which the caller
+ * records as `failed` and never retries.
+ */
+export type OwnedWorktreeCleanupOutcome =
+ | 'dirty'
+ | 'error'
+ | 'locked'
+ | 'refused'
+ | 'removed'
+ /** Server side only: the device could not be reached (offline, no gateway, too old). */
+ | 'unreachable';
+
+export interface OwnedWorktreeCleanupResult {
+ /** The branch the worktree was on, so a backfilled record learns it. */
+ branch?: string;
+ /** Tracked changes + untracked files, for `dirty`. */
+ dirtyFiles?: number;
+ error?: string;
+ outcome: OwnedWorktreeCleanupOutcome;
+ /** With `unreachable`: the device answered, but predates the owned-worktree RPCs. */
+ outdated?: boolean;
+ /** With `dirty`: submodules whose commits no remote holds. */
+ unpushedSubmodules?: number;
+}
+
+/** `cleanup.reason` of a worktree kept for its submodules' unpushed commits. */
+export const SUBMODULE_COMMITS_REASON = 'submoduleCommits';
+
+/** What a device reports for one `restoreOwnedWorktree` call. */
+export interface OwnedWorktreeRestoreResult {
+ /** With `needsLocal`: the branch to check out, as the server last recorded it. */
+ branch?: string;
+ error?: string;
+ /**
+ * `branchMissing`: the branch is gone (deleted after a merge); nothing was
+ * created. Server side only: `unreachable` (the device could not be reached),
+ * `busy` (a cleanup is deleting the folder right now; ask again shortly) and
+ * `needsLocal` (the desktop runs the re-checkout itself over IPC).
+ */
+ outcome:
+ 'branchMissing' | 'busy' | 'error' | 'needsLocal' | 'refused' | 'restored' | 'unreachable';
+ outdated?: boolean;
+}
+
+/** The device client predates the owned-worktree RPCs. */
+export const OWNED_WORKTREE_RPC_UNSUPPORTED = 'Unknown device RPC method';
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index bbb9dd8d173..a13d72dd7f5 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -12,6 +12,7 @@ import type { WorkingDirConfig } from '../device';
import { workingDirConfigSchema } from '../device';
import type { BotSenderMetadata } from '../message';
import type { BaseDataModel } from '../meta';
+import type { OwnedWorktree } from '../ownedWorktree';
import type { OnboardingUnderstandingSession } from '../understanding';
import type { OnboardingTaskRecommendationSession } from '../user/onboardingTasks';
@@ -301,6 +302,13 @@ export interface ChatTopicMetadata {
*/
onboardingFeedback?: OnboardingFeedbackEntry;
onboardingSession?: OnboardingSessionSnapshot;
+ /**
+ * Worktrees the app created for this topic, and where their automatic
+ * cleanup stands. Server-owned: claimed whenever metadata is written with
+ * `workingDirectoryConfig.git.autoCreated`, and deliberately absent from
+ * the client-writable metadata schema. See `./ownedWorktree`.
+ */
+ ownedWorktrees?: OwnedWorktree[];
/** Measured dominant provider by token volume — see {@link ChatTopicMetadata.model}. */
provider?: string;
/**
diff --git a/packages/types/src/workingDir.ts b/packages/types/src/workingDir.ts
index 72d4826ab5b..d8027d98fc9 100644
--- a/packages/types/src/workingDir.ts
+++ b/packages/types/src/workingDir.ts
@@ -89,6 +89,15 @@ export interface WorkingDirGitState {
* the source path itself.
*/
isWorktree?: boolean;
+ /** The nonce the server signed {@link ownerToken} with, for the creator only. */
+ ownerNonce?: string;
+ /**
+ * The creation receipt the device wrote into {@link activeWorktree} when the
+ * app created it (set with {@link autoCreated}, only once the device echoed
+ * it). A cleanup presents it; the device acts only when it matches, so a
+ * client-written claim on someone else's worktree path is worthless.
+ */
+ ownerToken?: string;
/**
* Remote ref {@link branch} publishes to. Dropped alongside {@link github}
* whenever the branch changes — a stale remote ref would bind the topic to
@@ -131,6 +140,8 @@ export const dropStaleAutoCreated = <T extends WorkingDirGitState>(
if (git.activeWorktree !== previousWorktree) {
delete git.autoCreated;
delete git.autoCreatedAt;
+ delete git.ownerToken;
+ delete git.ownerNonce;
}
return git;
};
@@ -197,6 +208,8 @@ export const workingDirConfigSchema = z.object({
})
.optional(),
isWorktree: z.boolean().optional(),
+ ownerNonce: z.string().max(64).optional(),
+ ownerToken: z.string().max(128).optional(),
// Mirrors `WorkingDirGitState.upstream`. A field missing here is not merely
// unvalidated — zod strips it, so it would never survive a write.
upstream: z
diff --git a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts
index cfab4fcd013..70bea22bbde 100644
--- a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts
+++ b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.test.ts
@@ -43,6 +43,12 @@ vi.mock('@/services/git', async (importOriginal) => {
};
});
+// The server-signed creation receipt for a new worktree.
+const issueWorktreeReceipt = vi.hoisted(() =>
+ vi.fn(async () => ({ nonce: 'nonce-1', token: 'signed-token-0123456789' })),
+);
+vi.mock('@/services/ownedWorktree', () => ({ issueWorktreeReceipt }));
+
vi.mock('@/services/device', () => ({
deviceService: { countRunningTopicsInDirectory: vi.fn() },
}));
@@ -387,6 +393,37 @@ describe('prepareDraftGitSend — new worktree', () => {
expect(deviceService.countRunningTopicsInDirectory).not.toHaveBeenCalled();
});
+ it('records the server-signed receipt only once the device echoes it back', async () => {
+ vi.mocked(gitService.addGitWorktree).mockImplementation(async ({ branch, ownerToken }) => ({
+ ownerToken,
+ success: true,
+ worktreePath: `/Users/me/.lobehub/worktrees/lobehub-0000beef/${branch.split('/').at(-1)}`,
+ }));
+ const recorded = await prepareDraftGitSend(context, { prompts: prompts(), t });
+ expect(vi.mocked(gitService.addGitWorktree).mock.calls[0][0].ownerToken).toBe(
+ 'signed-token-0123456789',
+ );
+ expect(recorded.ok && recorded.newTopicWorkingDirectory?.git).toMatchObject({
+ ownerNonce: 'nonce-1',
+ ownerToken: 'signed-token-0123456789',
+ });
+
+ // A device too old to write it echoes nothing: no receipt is claimed.
+ vi.mocked(gitService.addGitWorktree).mockImplementation(async ({ branch }) => ({
+ success: true,
+ worktreePath: `/Users/me/.lobehub/worktrees/lobehub-0000beef/${branch.split('/').at(-1)}`,
+ }));
+ const older = await prepareDraftGitSend(context, { prompts: prompts(), t });
+ expect(older.ok && older.newTopicWorkingDirectory?.git?.ownerToken).toBeUndefined();
+
+ // No receipt from the server: the worktree is still created, without one.
+ issueWorktreeReceipt.mockResolvedValueOnce(undefined as any);
+ vi.mocked(gitService.addGitWorktree).mockClear();
+ const unsigned = await prepareDraftGitSend(context, { prompts: prompts(), t });
+ expect(vi.mocked(gitService.addGitWorktree).mock.calls[0][0].ownerToken).toBeUndefined();
+ expect(unsigned.ok).toBe(true);
+ });
+
it('forks from HEAD without a start point when nothing else was picked', async () => {
await prepareDraftGitSend(context, { prompts: prompts(), t });
diff --git a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts
index 8ce3ad0286d..831b0d23bf0 100644
--- a/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts
+++ b/src/features/ChatInput/ControlBar/DraftGit/prepareSend.ts
@@ -5,6 +5,7 @@ import type { TFunction } from 'i18next';
import { deviceService } from '@/services/device';
import { gitService, isDeviceGitOutdated } from '@/services/git';
+import { issueWorktreeReceipt } from '@/services/ownedWorktree';
import { parseSingleAgentMentionDirectRoute } from '@/store/chat/slices/agentRun/actions/entries/commandBus/parseCommands';
import { gitStatusKey } from '@/store/device/gitStatus/projection';
import { getGitStatusStoreState } from '@/store/device/gitStatus/store';
@@ -133,6 +134,11 @@ const createWorktree = async (
return fail(t('workingDirectory.deviceOutdated'));
const branch = generateWorktreeBranchName({ exclude: await listBranchNames(target) });
+ // The creation receipt, signed by the server for this user: the device
+ // writes it into the worktree, and only a cleanup presenting it — which the
+ // server does only for this user's topics — may later remove the folder.
+ const receipt = await issueWorktreeReceipt();
+ const ownerToken = receipt?.token;
const homeDir = target.deviceId
? undefined
: desktopStateSelectors.userHomePath(getElectronStoreState()) || undefined;
@@ -141,6 +147,7 @@ const createWorktree = async (
const result = await gitService.addGitWorktree({
branch,
deviceId: target.deviceId,
+ ownerToken,
path: target.path,
sourcePath: target.sourcePath,
startPoint,
@@ -163,6 +170,9 @@ const createWorktree = async (
activeWorktree: result.worktreePath,
autoCreated: true,
autoCreatedAt: new Date().toISOString(),
+ // Only what the device confirms it recorded.
+ ...(ownerToken &&
+ result.ownerToken === ownerToken && { ownerNonce: receipt?.nonce, ownerToken }),
branch,
isWorktree: true,
},
diff --git a/src/features/Conversation/WorkingSidebar/Overview/KeptWorktreeRows.tsx b/src/features/Conversation/WorkingSidebar/Overview/KeptWorktreeRows.tsx
new file mode 100644
index 00000000000..0c91e6249be
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Overview/KeptWorktreeRows.tsx
@@ -0,0 +1,260 @@
+'use client';
+
+import type { ChatTopicMetadata, OwnedWorktree } from '@lobechat/types';
+import {
+ isRetiredTopicStatus,
+ resolveOwnedWorktrees,
+ SUBMODULE_COMMITS_REASON,
+} from '@lobechat/types';
+import { Button, confirmModal, cssVar, Flexbox, Text, toast } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { GitBranchIcon, TriangleAlertIcon } from 'lucide-react';
+import { memo, useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useSingleton } from '@/hooks/useSingleton';
+import { useClientDataSWR } from '@/libs/swr';
+import { discardOwnedWorktree, keepOwnedWorktree } from '@/services/ownedWorktree';
+import { topicService } from '@/services/topic';
+
+import {
+ findRemovedWorktree,
+ findWorktreesAwaitingChoice,
+ worktreeRefreshInterval,
+} from './overviewData';
+import { OverviewRow } from './OverviewRow';
+
+const styles = stylex.create({
+ // Lines up with the row's text, past its icon.
+ reason: { paddingInlineStart: '36px', paddingInlineEnd: '8px', wordBreak: 'break-word' },
+});
+
+/**
+ * The topic's owned worktrees as the server has them now. The topic list row
+ * can predate the cleanup (it runs after the archive response), so this reads
+ * the topic itself; `status` is in the key so an archive re-reads it.
+ */
+export const useOwnedWorktrees = (
+ topicId: string | undefined,
+ status?: string | null,
+ enabled = true,
+) => {
+ const key = topicId && enabled ? ['topic-owned-worktrees', topicId, status ?? ''] : null;
+ const keyId = key?.join('\u0000') ?? '';
+ // When each key was first read: a new key (an archive) opens a new
+ // discovery window for the cleanup to start in.
+ const firstReadAt = useSingleton(() => new Map<string, number>());
+ return useClientDataSWR(
+ key,
+ async () => {
+ if (!firstReadAt.has(keyId)) firstReadAt.set(keyId, Date.now());
+ return resolveOwnedWorktrees((await topicService.getTopicDetail(topicId!))?.metadata);
+ },
+ {
+ refreshInterval: (data?: OwnedWorktree[]) =>
+ worktreeRefreshInterval(data, {
+ retired: isRetiredTopicStatus(status),
+ sinceFirstReadMs: Date.now() - (firstReadAt.get(keyId) ?? Date.now()),
+ }),
+ },
+ );
+};
+
+/**
+ * What the Overview shows for the topic's app-created worktrees: the ones it
+ * owns (`entries`), and — when the cleanup already removed the folder the
+ * topic points at — that record, so the git rows stop reading a folder that is
+ * gone. Only a topic that owns a worktree is read.
+ */
+export const useTopicWorktrees = ({
+ metadata,
+ status,
+ topicId,
+ workingDirectory,
+}: {
+ metadata?: ChatTopicMetadata | null;
+ status?: string | null;
+ topicId?: string;
+ workingDirectory?: string;
+}) => {
+ const ownsWorktree = resolveOwnedWorktrees(metadata).length > 0;
+ const { data, mutate } = useOwnedWorktrees(topicId, status, ownsWorktree);
+ const entries = data ?? [];
+ const removed = findRemovedWorktree(entries, workingDirectory);
+ return { entries, mutate, removed };
+};
+
+interface KeptWorktreeRowsProps {
+ entries: OwnedWorktree[];
+ onChange: () => Promise<unknown>;
+ topicId?: string;
+}
+
+/**
+ * A worktree the cleanup kept because it held uncommitted work. Archiving
+ * never asks; the choice is offered here instead: discard the work and delete
+ * the worktree (its branch's commits are kept), or keep it for good.
+ */
+const KeptWorktreeRows = memo<KeptWorktreeRowsProps>(({ entries, onChange, topicId }) => {
+ const { t } = useTranslation('chat');
+ const { t: tCommon } = useTranslation('common');
+ const mutate = onChange;
+ const [busy, setBusy] = useState<string>();
+ /** The failed row whose reason is unfolded. */
+ const [detailsOpen, setDetailsOpen] = useState<string>();
+
+ const kept = findWorktreesAwaitingChoice(entries);
+
+ const handleDiscard = useCallback(
+ (entry: OwnedWorktree) => {
+ if (!topicId) return;
+ confirmModal({
+ cancelText: tCommon('cancel'),
+ content: t('workingPanel.overview.keptWorktree.discardConfirm'),
+ okButtonProps: { danger: true },
+ okText: t('workingPanel.overview.keptWorktree.discard'),
+ title: t('workingPanel.overview.keptWorktree.discardConfirmTitle'),
+ // Closes at once; a large worktree can take a while to delete.
+ onOk: () => {
+ setBusy(entry.path);
+ const pending = toast.loading(t('workingPanel.overview.keptWorktree.discarding'));
+ void (async () => {
+ try {
+ const written = await discardOwnedWorktree(topicId, entry);
+ const state = written?.cleanup?.state;
+ if (state === 'removed')
+ toast.success(t('workingPanel.overview.keptWorktree.discarded'));
+ else if (state === 'pending')
+ toast.info(t('workingPanel.overview.keptWorktree.discardPending'));
+ else
+ // A readable title; the device's own message stays as detail.
+ toast.error({
+ description: written?.cleanup?.reason,
+ title: t('workingPanel.overview.keptWorktree.discardFailed'),
+ });
+ } catch (error) {
+ toast.error({
+ description: (error as Error)?.message,
+ title: t('workingPanel.overview.keptWorktree.discardFailed'),
+ });
+ } finally {
+ pending.close();
+ setBusy(undefined);
+ await mutate();
+ }
+ })();
+ },
+ });
+ },
+ [mutate, t, tCommon, topicId],
+ );
+
+ const handleKeep = useCallback(
+ async (entry: OwnedWorktree) => {
+ if (!topicId) return;
+ setBusy(entry.path);
+ try {
+ await keepOwnedWorktree(topicId, entry);
+ toast.success(t('workingPanel.overview.keptWorktree.keptToast'));
+ await mutate();
+ } catch (error) {
+ toast.error({
+ description: (error as Error)?.message,
+ title: t('workingPanel.overview.keptWorktree.keepFailed'),
+ });
+ } finally {
+ setBusy(undefined);
+ }
+ },
+ [mutate, t, topicId],
+ );
+
+ if (kept.length === 0) return null;
+
+ return (
+ <>
+ {kept.map((entry) => (
+ <Flexbox key={entry.path}>
+ <OverviewRow
+ icon={TriangleAlertIcon}
+ iconColor={cssVar.colorWarning}
+ iconSize={14}
+ title={entry.path}
+ value={
+ entry.cleanup?.state === 'failed'
+ ? t('workingPanel.overview.keptWorktree.failedTitle')
+ : entry.cleanup?.reason === SUBMODULE_COMMITS_REASON
+ ? t('workingPanel.overview.keptWorktree.submoduleTitle')
+ : t('workingPanel.overview.keptWorktree.title', {
+ count: entry.cleanup?.dirtyFiles ?? 0,
+ })
+ }
+ />
+ {entry.cleanup?.state === 'failed' &&
+ entry.cleanup.reason &&
+ detailsOpen === entry.path && (
+ <Text code fontSize={12} type={'secondary'} {...stylex.props(styles.reason)}>
+ {entry.cleanup.reason}
+ </Text>
+ )}
+ <Flexbox horizontal gap={4} justify={'flex-end'} paddingInline={8}>
+ {entry.cleanup?.state === 'failed' && entry.cleanup.reason && (
+ <Button
+ size={'small'}
+ type={'text'}
+ onClick={() =>
+ setDetailsOpen((open) => (open === entry.path ? undefined : entry.path))
+ }
+ >
+ {t(
+ detailsOpen === entry.path
+ ? 'workingPanel.overview.keptWorktree.hideDetails'
+ : 'workingPanel.overview.keptWorktree.details',
+ )}
+ </Button>
+ )}
+ <Button
+ disabled={busy === entry.path}
+ size={'small'}
+ type={'text'}
+ onClick={() => void handleKeep(entry)}
+ >
+ {t('workingPanel.overview.keptWorktree.keep')}
+ </Button>
+ <Button
+ danger
+ loading={busy === entry.path}
+ size={'small'}
+ type={'text'}
+ onClick={() => handleDiscard(entry)}
+ >
+ {t('workingPanel.overview.keptWorktree.discard')}
+ </Button>
+ </Flexbox>
+ </Flexbox>
+ ))}
+ </>
+ );
+});
+
+KeptWorktreeRows.displayName = 'KeptWorktreeRows';
+
+export default KeptWorktreeRows;
+
+/**
+ * The topic's worktree was cleaned up (archived or trashed): its folder is gone,
+ * its branch is kept, and the next message checks it out again at the same path.
+ */
+export const RemovedWorktreeRow = memo<{ entry: OwnedWorktree }>(({ entry }) => {
+ const { t } = useTranslation('chat');
+ return (
+ <OverviewRow
+ icon={GitBranchIcon}
+ iconSize={14}
+ title={t('workingPanel.overview.keptWorktree.removedHint')}
+ value={t('workingPanel.overview.keptWorktree.removed', { branch: entry.branch ?? '' })}
+ />
+ );
+});
+
+RemovedWorktreeRow.displayName = 'RemovedWorktreeRow';
diff --git a/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts b/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts
index e0c7da3e4d8..87de7d1c280 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts
+++ b/src/features/Conversation/WorkingSidebar/Overview/__tests__/overviewData.test.ts
@@ -2,10 +2,14 @@ import { describe, expect, it } from 'vitest';
import {
collectChangeStats,
+ findRemovedWorktree,
+ findWorktreesAwaitingChoice,
getStatusDeviceId,
isLinkedWorktreeCheckout,
shouldShowCiLabel,
shouldShowGitSkeleton,
+ WORKTREE_DISCOVERY_MS,
+ worktreeRefreshInterval,
} from '../overviewData';
describe('collectChangeStats', () => {
@@ -109,3 +113,80 @@ describe('shouldShowGitSkeleton', () => {
expect(shouldShowGitSkeleton({ hasData: false, loading: false })).toBe(false);
});
});
+
+describe('findRemovedWorktree', () => {
+ const WT = '/Users/me/.lobehub/worktrees/repo-1a2b3c4d/quiet-hill';
+ const entry = (state?: 'keptDirty' | 'removed') => ({
+ ...(state && { cleanup: { at: 'x', state } }),
+ createdAt: 'y',
+ path: WT,
+ sourcePath: '/code/repo',
+ });
+
+ it('finds the removed worktree the topic points at, however the path ends', () => {
+ expect(findRemovedWorktree([entry('removed')], `${WT}/`)?.path).toBe(WT);
+ });
+
+ it('ignores worktrees still on disk and other folders', () => {
+ expect(findRemovedWorktree([entry('keptDirty'), entry()], WT)).toBeUndefined();
+ expect(findRemovedWorktree([entry('removed')], '/code/repo')).toBeUndefined();
+ expect(findRemovedWorktree([entry('removed')], undefined)).toBeUndefined();
+ });
+});
+
+describe('findWorktreesAwaitingChoice', () => {
+ const at = (state?: 'failed' | 'kept' | 'keptDirty' | 'pending' | 'removed') => ({
+ ...(state && { cleanup: { at: 'x', state } }),
+ createdAt: 'y',
+ path: `/wt/${state ?? 'live'}`,
+ sourcePath: '/code/repo',
+ });
+
+ it('offers a choice for kept-dirty and failed worktrees only', () => {
+ expect(
+ findWorktreesAwaitingChoice([
+ at(),
+ at('pending'),
+ at('removed'),
+ at('kept'),
+ at('keptDirty'),
+ at('failed'),
+ ]).map((entry) => entry.path),
+ ).toEqual(['/wt/keptDirty', '/wt/failed']);
+ });
+});
+
+describe('worktreeRefreshInterval', () => {
+ const entry = (state?: 'kept' | 'keptDirty' | 'pending' | 'removed' | 'running') => ({
+ ...(state && { cleanup: { at: 'x', state } }),
+ createdAt: 'y',
+ path: '/wt',
+ sourcePath: '/code/repo',
+ });
+ const live = { retired: false, sinceFirstReadMs: 0 };
+
+ it('polls while a cleanup is in flight', () => {
+ expect(worktreeRefreshInterval([entry('running')], live)).toBeGreaterThan(0);
+ expect(worktreeRefreshInterval([entry('pending')], live)).toBeGreaterThan(0);
+ });
+
+ it('keeps polling an archived topic until its cleanup has started', () => {
+ expect(
+ worktreeRefreshInterval([entry()], { retired: true, sinceFirstReadMs: 1000 }),
+ ).toBeGreaterThan(0);
+ expect(
+ worktreeRefreshInterval([entry('removed')], { retired: true, sinceFirstReadMs: 1000 }),
+ ).toBe(0);
+ });
+
+ it('stops for a worktree held on purpose, and for a live topic', () => {
+ expect(
+ worktreeRefreshInterval([entry()], {
+ retired: true,
+ sinceFirstReadMs: WORKTREE_DISCOVERY_MS,
+ }),
+ ).toBe(0);
+ expect(worktreeRefreshInterval([entry()], live)).toBe(0);
+ expect(worktreeRefreshInterval(undefined, live)).toBe(0);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Overview/index.tsx b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
index 6080e61f9b3..36d18d11f0d 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/Overview/index.tsx
@@ -41,7 +41,7 @@ import { gitService } from '@/services/git';
import { useAgentStore } from '@/store/agent';
import { agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
-import { dbMessageSelectors } from '@/store/chat/selectors';
+import { dbMessageSelectors, topicSelectors } from '@/store/chat/selectors';
import {
useFetchGitAheadBehind,
useFetchGitBranch,
@@ -56,6 +56,7 @@ import ProgressSection from '../ProgressSection';
import { toLinkedPullRequest } from '../PullRequest/useSidebarPullRequests';
import { BackgroundTasksSection } from './BackgroundTasks';
import DeviceStatusSection from './DeviceStatusSection';
+import KeptWorktreeRows, { RemovedWorktreeRow, useTopicWorktrees } from './KeptWorktreeRows';
import {
collectChangeStats,
isLinkedWorktreeCheckout,
@@ -126,12 +127,22 @@ const Overview = memo<OverviewProps>(
const isHetero = useAgentStore(agentSelectors.isCurrentAgentHeterogeneous);
const tunnelsEnabled = useUserStore(labPreferSelectors.enableDeviceTunnel);
const topicId = useChatStore((s) => s.activeTopicId);
+ const topicStatus = useChatStore((s) => topicSelectors.currentActiveTopic(s)?.status);
+ const topicMetadata = useChatStore((s) => topicSelectors.currentActiveTopic(s)?.metadata);
const threadId = useChatStore((s) => s.activeThreadId);
const works = useChatStore((s) =>
getAllWorkSummaries(dbMessageSelectors.activeDbMessages(s), threadId),
);
- const gitPath = active && repoType ? workingDirectory : undefined;
+ const topicWorktrees = useTopicWorktrees({
+ metadata: topicMetadata,
+ status: topicStatus,
+ topicId: topicId ?? undefined,
+ workingDirectory,
+ });
+ // A worktree the cleanup removed has no folder left to read git from.
+ const worktreeRemoved = !!topicWorktrees.removed;
+ const gitPath = active && repoType && !worktreeRemoved ? workingDirectory : undefined;
const isGithub = repoType === 'github';
const {
data: branchData,
@@ -446,7 +457,17 @@ const Overview = memo<OverviewProps>(
onClick={() => onOpenTab('files')}
/>
<Flexbox className={sectionStyles.section}>
- {workspaceSection}
+ {/* A worktree the archive cleanup kept for its uncommitted work. */}
+ <KeptWorktreeRows
+ entries={topicWorktrees.entries}
+ topicId={topicId ?? undefined}
+ onChange={topicWorktrees.mutate}
+ />
+ {topicWorktrees.removed ? (
+ <RemovedWorktreeRow entry={topicWorktrees.removed} />
+ ) : (
+ workspaceSection
+ )}
{/* Outside the git rows: a dev server runs in plain folders too. */}
{tunnelsEnabled && deviceId && (
<PortSwitcher
diff --git a/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts b/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts
index a691f1a8621..0adbd449907 100644
--- a/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts
+++ b/src/features/Conversation/WorkingSidebar/Overview/overviewData.ts
@@ -3,6 +3,7 @@ import type {
DeviceExecutionTarget,
DeviceGitPullRequestCiStatus,
DeviceGitWorktreeListItem,
+ OwnedWorktree,
} from '@lobechat/types';
import { normalizeDisplayPath } from '@/features/ChatInput/ControlBar/worktreeHelpers';
@@ -86,3 +87,60 @@ export const shouldShowGitSkeleton = ({
hasData: boolean;
loading: boolean;
}): boolean => loading && !hasData;
+
+/**
+ * The app-created worktree the cleanup already removed, when it is the folder
+ * the topic points at: the Overview then says so instead of reading git from a
+ * folder that no longer exists (which would show its last, stale changes).
+ */
+export const findRemovedWorktree = (
+ entries: OwnedWorktree[],
+ workingDirectory: string | undefined,
+): OwnedWorktree | undefined => {
+ if (!workingDirectory) return;
+ const target = normalizeDisplayPath(workingDirectory);
+ return entries.find(
+ (entry) => entry.cleanup?.state === 'removed' && normalizeDisplayPath(entry.path) === target,
+ );
+};
+
+/**
+ * The app-created worktrees the Overview offers a choice for: kept for their
+ * uncommitted work, or left in place because the cleanup failed (the device
+ * refused or git errored). Either way the folder is still there.
+ */
+export const findWorktreesAwaitingChoice = (entries: OwnedWorktree[]): OwnedWorktree[] =>
+ entries.filter(
+ (entry) => entry.cleanup?.state === 'keptDirty' || entry.cleanup?.state === 'failed',
+ );
+
+const WORKTREE_POLL_MS = 3000;
+/** How long an archived topic's Overview waits for its cleanup to start. */
+export const WORKTREE_DISCOVERY_MS = 60_000;
+
+/**
+ * How often the Overview re-reads the topic's worktrees: while a cleanup is in
+ * flight, and — right after an archive — until the cleanup has started (it
+ * runs after the archive response, so the first read can predate it). A
+ * worktree that stays untouched past the window is held on purpose (in use, a
+ * live run, a lock), and stops the polling.
+ */
+export const worktreeRefreshInterval = (
+ entries: OwnedWorktree[] | undefined,
+ { retired, sinceFirstReadMs }: { retired: boolean; sinceFirstReadMs: number },
+): number => {
+ if (!entries?.length) return 0;
+ if (
+ entries.some(
+ (entry) => entry.cleanup?.state === 'pending' || entry.cleanup?.state === 'running',
+ )
+ )
+ return WORKTREE_POLL_MS;
+ if (
+ retired &&
+ sinceFirstReadMs < WORKTREE_DISCOVERY_MS &&
+ entries.some((entry) => !entry.cleanup)
+ )
+ return WORKTREE_POLL_MS;
+ return 0;
+};
diff --git a/src/features/Electron/system/useDrainWorktreeCleanups.ts b/src/features/Electron/system/useDrainWorktreeCleanups.ts
new file mode 100644
index 00000000000..b81d64a8e5c
--- /dev/null
+++ b/src/features/Electron/system/useDrainWorktreeCleanups.ts
@@ -0,0 +1,24 @@
+import { useEffect } from 'react';
+
+import { drainLocalWorktreeCleanups } from '@/services/ownedWorktree';
+import { useUserStore } from '@/store/user';
+import { authSelectors } from '@/store/user/selectors';
+
+/** Let startup settle first; the drain is housekeeping, not on the critical path. */
+const STARTUP_DRAIN_DELAY_MS = 5000;
+
+/**
+ * Once per signed-in session on desktop start: remove the app-created
+ * worktrees of topics archived or trashed while this desktop could not be
+ * reached (gateway off, or never registered with it). Runs over IPC in the
+ * main process; the server keeps each one from running twice.
+ */
+export const useDrainWorktreeCleanups = () => {
+ const isLogin = useUserStore(authSelectors.isLogin);
+
+ useEffect(() => {
+ if (!isLogin) return;
+ const timer = setTimeout(() => void drainLocalWorktreeCleanups(), STARTUP_DRAIN_DELAY_MS);
+ return () => clearTimeout(timer);
+ }, [isLogin]);
+};
diff --git a/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx b/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx
index 10125c2d912..eebddac0684 100644
--- a/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx
+++ b/src/layout/GlobalProvider/ElectronAppStateSync.desktop.tsx
@@ -5,6 +5,7 @@ import { Button, createModal, ModalFooter } from '@lobehub/ui';
import { useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
+import { useDrainWorktreeCleanups } from '@/features/Electron/system/useDrainWorktreeCleanups';
import { useMacWindowFullscreen } from '@/features/Electron/system/useMacWindowFullscreen';
import { rendererOtaService } from '@/services/electron/rendererOta';
import { useElectronStore } from '@/store/electron';
@@ -22,6 +23,7 @@ import { useElectronStore } from '@/store/electron';
*/
const ElectronAppStateSync = () => {
useMacWindowFullscreen();
+ useDrainWorktreeCleanups();
const { t: tElectron } = useTranslation('electron');
const { t } = useTranslation('common');
const dismissConfirmation = useRef<(() => void) | null>(null);
diff --git a/src/services/electron/git.ts b/src/services/electron/git.ts
index ed65c2c1b4e..938ad5518f8 100644
--- a/src/services/electron/git.ts
+++ b/src/services/electron/git.ts
@@ -9,6 +9,8 @@ import {
type GitDeleteBranchResult,
type GitFileRevertResult,
type GitLinkedPullRequestResult,
+ type GitOwnedWorktreeCleanupResult,
+ type GitOwnedWorktreeRestoreResult,
type GitPullRequestAction,
type GitPullRequestActionResult,
type GitPullRequestActivity,
@@ -166,12 +168,31 @@ class ElectronGitService {
async addGitWorktree(params: {
branch: string;
+ ownerToken?: string;
path: string;
startPoint?: string;
worktreePath: string;
}): Promise<GitAddWorktreeResult> {
return this.ipc.git.addGitWorktree(params);
}
+
+ async cleanupOwnedWorktree(params: {
+ discard?: boolean;
+ ownerToken?: string;
+ sourcePath: string;
+ worktreePath: string;
+ }): Promise<GitOwnedWorktreeCleanupResult> {
+ return this.ipc.git.cleanupOwnedWorktree(params);
+ }
+
+ async restoreOwnedWorktree(params: {
+ branch: string;
+ ownerToken?: string;
+ sourcePath: string;
+ worktreePath: string;
+ }): Promise<GitOwnedWorktreeRestoreResult> {
+ return this.ipc.git.restoreOwnedWorktree(params);
+ }
}
export const electronGitService = new ElectronGitService();
diff --git a/src/services/git.ts b/src/services/git.ts
index 2044e0c4fb2..ea2cd5cd719 100644
--- a/src/services/git.ts
+++ b/src/services/git.ts
@@ -191,6 +191,7 @@ class GitService {
async addGitWorktree({
branch,
deviceId,
+ ownerToken,
path,
sourcePath,
startPoint,
@@ -199,6 +200,8 @@ class GitService {
}: {
branch: string;
deviceId?: string;
+ /** Creation receipt for a worktree the app makes for a conversation; echoed when recorded. */
+ ownerToken?: string;
path: string;
/** The repo's main checkout; the server keys the target folder on it. */
sourcePath?: string;
@@ -211,7 +214,10 @@ class GitService {
stripBranchPrefix?: boolean;
worktreePath: string;
}): Promise<DeviceGitAddWorktreeResult> {
- const start = startPoint ? { startPoint } : {};
+ const start = {
+ ...(startPoint ? { startPoint } : {}),
+ ...(ownerToken ? { ownerToken } : {}),
+ };
const result = deviceId
? await lambdaClient.device.addGitWorktree.mutate({
branch,
diff --git a/src/services/ownedWorktree.test.ts b/src/services/ownedWorktree.test.ts
new file mode 100644
index 00000000000..3222dcf0e64
--- /dev/null
+++ b/src/services/ownedWorktree.test.ts
@@ -0,0 +1,172 @@
+import type { OwnedWorktree } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ claim: vi.fn(),
+ deviceId: 'dev-local' as string | undefined,
+ discard: vi.fn(),
+ ipcCleanup: vi.fn(),
+ ipcRestore: vi.fn(),
+ isDesktop: true,
+ keep: vi.fn(),
+ report: vi.fn(),
+ restore: vi.fn(),
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ get isDesktop() {
+ return mocks.isDesktop;
+ },
+}));
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ topic: {
+ claimLocalWorktreeCleanups: { mutate: mocks.claim },
+ discardOwnedWorktree: { mutate: mocks.discard },
+ keepOwnedWorktree: { mutate: mocks.keep },
+ reportOwnedWorktreeCleanup: { mutate: mocks.report },
+ restoreOwnedWorktree: { mutate: mocks.restore },
+ },
+ },
+}));
+vi.mock('@/services/electron/git', () => ({
+ electronGitService: {
+ cleanupOwnedWorktree: mocks.ipcCleanup,
+ restoreOwnedWorktree: mocks.ipcRestore,
+ },
+}));
+vi.mock('@/store/electron', () => ({
+ getElectronStoreState: () => ({ resolveGatewayDeviceId: async () => mocks.deviceId }),
+}));
+
+const {
+ discardOwnedWorktree,
+ drainLocalWorktreeCleanups,
+ isLocalOwnedWorktree,
+ restoreOwnedWorktree,
+} = await import('./ownedWorktree');
+
+const WT = '/Users/me/.lobehub/worktrees/repo-1a2b3c4d/quiet-hill';
+const entry = (deviceId?: string): OwnedWorktree => ({
+ branch: 'lobehub/quiet-hill',
+ createdAt: 'y',
+ ...(deviceId && { deviceId }),
+ path: WT,
+ sourcePath: '/code/repo',
+});
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.isDesktop = true;
+ mocks.deviceId = 'dev-local';
+});
+
+describe('isLocalOwnedWorktree', () => {
+ it('is this desktop for its own device id or a record without one', async () => {
+ await expect(isLocalOwnedWorktree(entry('dev-local'))).resolves.toBe(true);
+ await expect(isLocalOwnedWorktree(entry())).resolves.toBe(true);
+ await expect(isLocalOwnedWorktree(entry('dev-remote'))).resolves.toBe(false);
+ });
+
+ it('is never local on the web', async () => {
+ mocks.isDesktop = false;
+ await expect(isLocalOwnedWorktree(entry())).resolves.toBe(false);
+ });
+});
+
+describe('drainLocalWorktreeCleanups', () => {
+ it('runs each claimed cleanup over IPC and reports the result', async () => {
+ mocks.claim.mockResolvedValue([
+ {
+ discard: false,
+ entry: {
+ ...entry(),
+ cleanup: { at: 'x', state: 'running', trigger: 'trashed' },
+ ownerToken: 'receipt-0123456789abcdef',
+ },
+ topicId: 't1',
+ },
+ ]);
+ mocks.ipcCleanup.mockResolvedValue({ dirtyFiles: 2, outcome: 'dirty' });
+
+ await expect(drainLocalWorktreeCleanups()).resolves.toBe(1);
+
+ expect(mocks.claim).toHaveBeenCalledWith({ deviceId: 'dev-local' });
+ expect(mocks.ipcCleanup).toHaveBeenCalledWith({
+ discard: false,
+ ownerToken: 'receipt-0123456789abcdef',
+ sourcePath: '/code/repo',
+ worktreePath: WT,
+ });
+ expect(mocks.report).toHaveBeenCalledWith({
+ path: WT,
+ result: { branch: undefined, dirtyFiles: 2, error: undefined, outcome: 'dirty' },
+ topicId: 't1',
+ trigger: 'trashed',
+ });
+ });
+
+ it('does nothing on the web', async () => {
+ mocks.isDesktop = false;
+ await expect(drainLocalWorktreeCleanups()).resolves.toBe(0);
+ expect(mocks.claim).not.toHaveBeenCalled();
+ });
+});
+
+describe('discardOwnedWorktree', () => {
+ it('claims on the server and deletes over IPC for this desktop', async () => {
+ mocks.discard.mockResolvedValue({ ...entry('dev-local'), cleanup: { state: 'running' } });
+ mocks.ipcCleanup.mockResolvedValue({ outcome: 'removed' });
+ mocks.report.mockResolvedValue({ ...entry('dev-local'), cleanup: { state: 'removed' } });
+
+ const written = await discardOwnedWorktree('t1', entry('dev-local'));
+
+ expect(mocks.discard).toHaveBeenCalledWith({ local: true, path: WT, topicId: 't1' });
+ expect(mocks.ipcCleanup).toHaveBeenCalledWith(expect.objectContaining({ discard: true }));
+ expect(mocks.report).toHaveBeenCalledWith(expect.objectContaining({ trigger: 'discarded' }));
+ expect(written?.cleanup?.state).toBe('removed');
+ });
+
+ it('lets the server run it on a remote device', async () => {
+ await discardOwnedWorktree('t1', entry('dev-remote'));
+ expect(mocks.discard).toHaveBeenCalledWith({ path: WT, topicId: 't1' });
+ expect(mocks.ipcCleanup).not.toHaveBeenCalled();
+ });
+});
+
+describe('restoreOwnedWorktree', () => {
+ it('lets the server decide, then re-adds a worktree on this desktop over IPC', async () => {
+ mocks.restore
+ .mockResolvedValueOnce({ branch: 'lobehub/renamed', outcome: 'needsLocal' })
+ .mockResolvedValueOnce({ outcome: 'restored' });
+ mocks.ipcRestore.mockResolvedValue({ outcome: 'restored' });
+
+ await expect(restoreOwnedWorktree('t1', entry())).resolves.toEqual({ outcome: 'restored' });
+ expect(mocks.restore).toHaveBeenNthCalledWith(1, { local: true, path: WT, topicId: 't1' });
+ // The branch the server last recorded wins over the stale list row.
+ expect(mocks.ipcRestore).toHaveBeenCalledWith({
+ branch: 'lobehub/renamed',
+ sourcePath: '/code/repo',
+ worktreePath: WT,
+ });
+ expect(mocks.restore).toHaveBeenNthCalledWith(2, {
+ path: WT,
+ result: { error: undefined, outcome: 'restored' },
+ topicId: 't1',
+ });
+ });
+
+ it('passes a busy or already-restored answer straight through', async () => {
+ mocks.restore.mockResolvedValue({ outcome: 'busy' });
+ await expect(restoreOwnedWorktree('t1', entry())).resolves.toEqual({ outcome: 'busy' });
+ expect(mocks.ipcRestore).not.toHaveBeenCalled();
+ });
+
+ it('asks the server to run it on a remote device', async () => {
+ mocks.restore.mockResolvedValue({ outcome: 'restored' });
+ await restoreOwnedWorktree('t1', entry('dev-remote'));
+ expect(mocks.ipcRestore).not.toHaveBeenCalled();
+ expect(mocks.restore).toHaveBeenCalledWith({ local: false, path: WT, topicId: 't1' });
+ });
+});
diff --git a/src/services/ownedWorktree.ts b/src/services/ownedWorktree.ts
new file mode 100644
index 00000000000..f089cd73e52
--- /dev/null
+++ b/src/services/ownedWorktree.ts
@@ -0,0 +1,196 @@
+import { isDesktop } from '@lobechat/const';
+import type {
+ OwnedWorktree,
+ OwnedWorktreeCleanupResult,
+ OwnedWorktreeCleanupTrigger,
+ OwnedWorktreeRestoreResult,
+} from '@lobechat/types';
+
+import { lambdaClient } from '@/libs/trpc/client';
+import { electronGitService } from '@/services/electron/git';
+
+/**
+ * The client half of the automatic cleanup of app-created worktrees
+ * (`metadata.ownedWorktrees`, see `apps/server/src/services/worktreeCleanup`).
+ *
+ * A worktree on a remote device — or on this desktop while it is connected to
+ * the gateway — is cleaned and restored by the server over the device RPCs. A
+ * worktree on THIS desktop is run here over IPC instead, in the main process:
+ * that also covers a desktop with the gateway off (whose cleanups wait as
+ * pending) or one that never registered with it (records without a device).
+ */
+
+/**
+ * This desktop's gateway device id; `undefined` off desktop or when
+ * unregistered. Imported lazily: the topic service loads this module, and the
+ * electron store must not join its import graph.
+ */
+const localDeviceId = async () => {
+ const { getElectronStoreState } = await import('@/store/electron');
+ return getElectronStoreState().resolveGatewayDeviceId();
+};
+
+/** Whether the worktree lives on this desktop, where IPC can reach it. */
+export const isLocalOwnedWorktree = async (entry: Pick<OwnedWorktree, 'deviceId'>) => {
+ if (!isDesktop) return false;
+ if (!entry.deviceId) return true;
+ return entry.deviceId === (await localDeviceId());
+};
+
+const runLocalCleanup = async (
+ topicId: string,
+ entry: OwnedWorktree,
+ trigger: OwnedWorktreeCleanupTrigger,
+): Promise<OwnedWorktree | null> => {
+ let result: OwnedWorktreeCleanupResult;
+ try {
+ result = await electronGitService.cleanupOwnedWorktree({
+ discard: trigger === 'discarded',
+ ownerToken: entry.ownerToken,
+ sourcePath: entry.sourcePath,
+ worktreePath: entry.path,
+ });
+ } catch (error) {
+ result = { error: (error as Error)?.message || 'Worktree cleanup failed', outcome: 'error' };
+ }
+ // `unreachable` is a server-side answer only; IPC always reaches the device.
+ const outcome = result.outcome === 'unreachable' ? 'error' : result.outcome;
+ return lambdaClient.topic.reportOwnedWorktreeCleanup.mutate({
+ path: entry.path,
+ result: {
+ branch: result.branch,
+ dirtyFiles: result.dirtyFiles,
+ error: result.error,
+ outcome,
+ unpushedSubmodules: result.unpushedSubmodules,
+ },
+ topicId,
+ trigger,
+ });
+};
+
+let draining: Promise<number> | undefined;
+
+/**
+ * Run the cleanups that wait on this desktop: on startup, and shortly after
+ * this desktop archives or trashes a topic (the server marks them pending when
+ * it cannot reach the desktop over the gateway). One drain at a time; the
+ * server's claim keeps a cleanup from running twice anyway.
+ */
+export const drainLocalWorktreeCleanups = (): Promise<number> => {
+ if (!isDesktop) return Promise.resolve(0);
+ draining ??= (async () => {
+ try {
+ const deviceId = await localDeviceId();
+ const claimed = await lambdaClient.topic.claimLocalWorktreeCleanups.mutate({ deviceId });
+ for (const { discard, entry, topicId } of claimed) {
+ await runLocalCleanup(
+ topicId,
+ entry,
+ discard ? 'discarded' : (entry.cleanup?.trigger ?? 'archived'),
+ );
+ }
+ return claimed.length;
+ } catch (error) {
+ console.warn('[ownedWorktree] local cleanup drain failed:', error);
+ return 0;
+ } finally {
+ draining = undefined;
+ }
+ })();
+ return draining;
+};
+
+/** Give the server's own attempt (after the archive response) time to land first. */
+const RETIRE_DRAIN_DELAY_MS = 3000;
+let retireDrainTimer: ReturnType<typeof setTimeout> | undefined;
+
+/**
+ * This desktop just archived or trashed topics: shortly after, run whatever
+ * the server left pending for this desktop (it could not reach it over the
+ * gateway). Bursts — a bulk archive — coalesce into one drain.
+ */
+export const afterTopicsRetired = () => {
+ if (!isDesktop) return;
+ if (retireDrainTimer) clearTimeout(retireDrainTimer);
+ retireDrainTimer = setTimeout(() => {
+ retireDrainTimer = undefined;
+ void drainLocalWorktreeCleanups();
+ }, RETIRE_DRAIN_DELAY_MS);
+};
+
+/**
+ * "Discard changes and delete": force-remove a kept worktree, uncommitted and
+ * ignored files included. The branch is kept.
+ */
+export const discardOwnedWorktree = async (
+ topicId: string,
+ entry: OwnedWorktree,
+): Promise<OwnedWorktree | null> => {
+ if (await isLocalOwnedWorktree(entry)) {
+ const claimed = await lambdaClient.topic.discardOwnedWorktree.mutate({
+ local: true,
+ path: entry.path,
+ topicId,
+ });
+ if (!claimed) return null;
+ return runLocalCleanup(topicId, claimed, 'discarded');
+ }
+ return lambdaClient.topic.discardOwnedWorktree.mutate({ path: entry.path, topicId });
+};
+
+/**
+ * A server-signed creation receipt for a worktree about to be created for a
+ * new topic; `undefined` when the server cannot issue one (the worktree is
+ * then cleaned up only when clean, never discarded by force).
+ */
+export const issueWorktreeReceipt = async () => {
+ try {
+ return (await lambdaClient.topic.issueWorktreeReceipt.mutate()) ?? undefined;
+ } catch (error) {
+ console.warn('[ownedWorktree] could not get a worktree receipt:', error);
+ return undefined;
+ }
+};
+
+/** "Keep": never clean this worktree up automatically again. */
+export const keepOwnedWorktree = (topicId: string, entry: OwnedWorktree) =>
+ lambdaClient.topic.keepOwnedWorktree.mutate({ path: entry.path, topicId });
+
+/**
+ * Check a cleaned-up worktree out again at its original path, on its branch,
+ * before a restored topic's next turn. A gone branch makes the server move the
+ * topic back to its source repository (`branchMissing`).
+ */
+export const restoreOwnedWorktree = async (
+ topicId: string,
+ entry: OwnedWorktree,
+): Promise<OwnedWorktreeRestoreResult> => {
+ const local = await isLocalOwnedWorktree(entry);
+ // The server's record decides: a cleanup still running (`busy`), one that
+ // never ran (cancelled), or a removed folder to check out again.
+ const answer = await lambdaClient.topic.restoreOwnedWorktree.mutate({
+ local,
+ path: entry.path,
+ topicId,
+ });
+ if (answer.outcome !== 'needsLocal') return answer;
+
+ let result: OwnedWorktreeRestoreResult;
+ try {
+ result = await electronGitService.restoreOwnedWorktree({
+ branch: answer.branch ?? entry.branch ?? '',
+ ownerToken: entry.ownerToken,
+ sourcePath: entry.sourcePath,
+ worktreePath: entry.path,
+ });
+ } catch (error) {
+ return { error: (error as Error)?.message, outcome: 'error' };
+ }
+ if (result.outcome !== 'branchMissing' && result.outcome !== 'restored') return result;
+ return lambdaClient.topic.restoreOwnedWorktree.mutate({
+ path: entry.path,
+ result: { error: result.error, outcome: result.outcome },
+ topicId,
+ });
+};
diff --git a/src/services/topic/index.ts b/src/services/topic/index.ts
index 75e8416e5c2..d2d9e18c262 100644
--- a/src/services/topic/index.ts
+++ b/src/services/topic/index.ts
@@ -4,10 +4,12 @@ import type {
HeteroSessionImportStatus,
UpdateTopicMetadataInput,
} from '@lobechat/types';
+import { isRetiredTopicStatus } from '@lobechat/types';
import { INBOX_SESSION_ID } from '@/const/session';
import { TopicTrigger } from '@/const/topic';
import { lambdaClient } from '@/libs/trpc/client';
+import { afterTopicsRetired } from '@/services/ownedWorktree';
import { type BatchTaskResult } from '@/types/service';
import {
type ChatTopic,
@@ -188,8 +190,11 @@ export class TopicService {
) as unknown as ChatTopic[];
};
- updateTopic = (id: string, data: Partial<ChatTopic>) => {
- return lambdaClient.topic.updateTopic.mutate({ id, value: data });
+ updateTopic = async (id: string, data: Partial<ChatTopic>) => {
+ const result = await lambdaClient.topic.updateTopic.mutate({ id, value: data });
+ // Archiving cleans up the worktree the app created for the topic.
+ if (isRetiredTopicStatus(data.status)) afterTopicsRetired();
+ return result;
};
updateTopicModel = (
@@ -236,31 +241,33 @@ export class TopicService {
return lambdaClient.topic.disableSharing.mutate({ topicId });
};
- removeTopic = (id: string, removeFiles?: boolean) => {
- return lambdaClient.topic.removeTopic.mutate({ id, removeFiles });
- };
+ removeTopic = (id: string, removeFiles?: boolean) =>
+ this.retiring(lambdaClient.topic.removeTopic.mutate({ id, removeFiles }));
- removeTopics = (sessionId: string, scope: TopicBatchDeleteScope = 'own') => {
- return lambdaClient.topic.batchDeleteBySessionId.mutate({
- id: this.toDbSessionId(sessionId),
- scope,
- });
- };
+ removeTopics = (sessionId: string, scope: TopicBatchDeleteScope = 'own') =>
+ this.retiring(
+ lambdaClient.topic.batchDeleteBySessionId.mutate({
+ id: this.toDbSessionId(sessionId),
+ scope,
+ }),
+ );
- removeTopicsByAgentId = (agentId: string, scope: TopicBatchDeleteScope = 'own') => {
- return lambdaClient.topic.batchDeleteByAgentId.mutate({ agentId, scope });
- };
+ removeTopicsByAgentId = (agentId: string, scope: TopicBatchDeleteScope = 'own') =>
+ this.retiring(lambdaClient.topic.batchDeleteByAgentId.mutate({ agentId, scope }));
- removeTopicsByGroupId = (groupId: string, scope: TopicBatchDeleteScope = 'own') => {
- return lambdaClient.topic.batchDeleteByGroupId.mutate({ groupId, scope });
- };
+ removeTopicsByGroupId = (groupId: string, scope: TopicBatchDeleteScope = 'own') =>
+ this.retiring(lambdaClient.topic.batchDeleteByGroupId.mutate({ groupId, scope }));
- batchRemoveTopics = (topics: string[]) => {
- return lambdaClient.topic.batchDelete.mutate({ ids: topics });
- };
+ batchRemoveTopics = (topics: string[]) =>
+ this.retiring(lambdaClient.topic.batchDelete.mutate({ ids: topics }));
+
+ removeAllTopic = () => this.retiring(lambdaClient.topic.removeAllTopics.mutate());
- removeAllTopic = () => {
- return lambdaClient.topic.removeAllTopics.mutate();
+ /** Trashing topics cleans up the worktrees the app created for them. */
+ private retiring = async <T>(request: Promise<T>): Promise<T> => {
+ const result = await request;
+ afterTopicsRetired();
+ return result;
};
private toDbSessionId = (sessionId?: string | null) =>
diff --git a/src/store/chat/slices/agentRun/actions/entries/ownedWorktreeRestore.test.ts b/src/store/chat/slices/agentRun/actions/entries/ownedWorktreeRestore.test.ts
new file mode 100644
index 00000000000..0befe8179f1
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/ownedWorktreeRestore.test.ts
@@ -0,0 +1,138 @@
+import type { ChatTopicMetadata } from '@lobechat/types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { ChatTopic } from '@/types/topic';
+
+import { ensureOwnedWorktreeForRun } from './ownedWorktreeRestore';
+
+const mocks = vi.hoisted(() => ({
+ dispatch: vi.fn(),
+ isDesktop: true,
+ restore: vi.fn(),
+ toastClose: vi.fn(),
+ toastError: vi.fn(),
+ toastLoading: vi.fn(),
+ toastWarning: vi.fn(),
+}));
+
+vi.mock('@lobechat/const', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ get isDesktop() {
+ return mocks.isDesktop;
+ },
+}));
+vi.mock('@lobehub/ui', () => ({
+ toast: {
+ error: mocks.toastError,
+ loading: (...args: unknown[]) => {
+ mocks.toastLoading(...args);
+ return { close: mocks.toastClose };
+ },
+ warning: mocks.toastWarning,
+ },
+}));
+vi.mock('@/services/ownedWorktree', () => ({
+ restoreOwnedWorktree: mocks.restore,
+}));
+vi.mock('@/store/chat', () => ({
+ getChatStoreState: () => ({ internal_dispatchTopic: mocks.dispatch }),
+}));
+
+const WT = '/Users/me/.lobehub/worktrees/repo-1a2b3c4d/quiet-hill';
+
+const topic = (metadata: ChatTopicMetadata): ChatTopic =>
+ ({ createdAt: 0, favorite: false, id: 'tpc_1', metadata, title: 't', updatedAt: 0 }) as ChatTopic;
+
+/** A topic born in a worktree the app created, cleaned up while archived. */
+const restoredTopic = () =>
+ topic({
+ boundDeviceId: 'dev-1',
+ ownedWorktrees: [
+ {
+ branch: 'lobehub/quiet-hill',
+ cleanup: { at: 'x', state: 'removed', trigger: 'archived' },
+ createdAt: 'y',
+ deviceId: 'dev-1',
+ path: WT,
+ sourcePath: '/code/repo',
+ },
+ ],
+ workingDirectory: WT,
+ workingDirectoryConfig: {
+ git: { activeWorktree: WT, branch: 'lobehub/quiet-hill' },
+ path: '/code/repo',
+ repoType: 'github',
+ sessionPath: WT,
+ },
+ });
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.isDesktop = true;
+});
+
+describe('ensureOwnedWorktreeForRun', () => {
+ it('leaves a topic without an app-created worktree alone', async () => {
+ const plain = topic({ workingDirectory: '/code/repo' });
+ await expect(ensureOwnedWorktreeForRun(plain)).resolves.toBe(plain);
+ expect(mocks.restore).not.toHaveBeenCalled();
+ });
+
+ it('runs the turn as is when the server says the worktree is there', async () => {
+ mocks.restore.mockResolvedValue({ outcome: 'restored' });
+ const subject = restoredTopic();
+ await expect(ensureOwnedWorktreeForRun(subject)).resolves.toBe(subject);
+ expect(mocks.restore).toHaveBeenCalledWith(
+ 'tpc_1',
+ expect.objectContaining({ branch: 'lobehub/quiet-hill', path: WT }),
+ );
+ expect(subject.metadata?.workingDirectoryConfig?.sessionPath).toBe(WT);
+ });
+
+ it('waits while the archive cleanup is still deleting the folder, then restores it', async () => {
+ vi.useFakeTimers();
+ try {
+ mocks.restore
+ .mockResolvedValueOnce({ outcome: 'busy' })
+ .mockResolvedValueOnce({ outcome: 'busy' })
+ .mockResolvedValueOnce({ outcome: 'restored' });
+ const subject = restoredTopic();
+ const pending = ensureOwnedWorktreeForRun(subject);
+ await vi.runAllTimersAsync();
+
+ await expect(pending).resolves.toBe(subject);
+ expect(mocks.restore).toHaveBeenCalledTimes(3);
+ expect(mocks.toastLoading).toHaveBeenCalledTimes(1);
+ expect(mocks.toastClose).toHaveBeenCalledTimes(1);
+ expect(mocks.toastError).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('falls back to the source repository when the branch is gone, and says so', async () => {
+ mocks.restore.mockResolvedValue({ outcome: 'branchMissing' });
+
+ const out = await ensureOwnedWorktreeForRun(restoredTopic());
+
+ expect(out?.metadata?.workingDirectory).toBe('/code/repo');
+ expect(out?.metadata?.workingDirectoryConfig).toEqual({
+ path: '/code/repo',
+ repoType: 'github',
+ });
+ expect(mocks.toastWarning).toHaveBeenCalledTimes(1);
+ expect(mocks.dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'tpc_1', type: 'updateTopic' }),
+ expect.any(String),
+ );
+ });
+
+ it('never blocks the turn on a failed restore', async () => {
+ mocks.restore.mockResolvedValue({ error: 'fatal: boom', outcome: 'error' });
+ const subject = restoredTopic();
+ await expect(ensureOwnedWorktreeForRun(subject)).resolves.toBe(subject);
+ expect(mocks.toastError).toHaveBeenCalledWith(
+ expect.objectContaining({ description: 'fatal: boom' }),
+ );
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/ownedWorktreeRestore.ts b/src/store/chat/slices/agentRun/actions/entries/ownedWorktreeRestore.ts
new file mode 100644
index 00000000000..549fe68ea85
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/entries/ownedWorktreeRestore.ts
@@ -0,0 +1,108 @@
+import type { ChatTopicMetadata, OwnedWorktree } from '@lobechat/types';
+import { getTopicWorktreePaths, resolveOwnedWorktrees } from '@lobechat/types';
+import { toast } from '@lobehub/ui';
+import { t } from 'i18next';
+
+import { restoreOwnedWorktree } from '@/services/ownedWorktree';
+import type { ChatTopic } from '@/types/topic';
+
+/**
+ * The worktree the app created for this topic that its next turn runs in (its
+ * CLI start folder or current worktree), unless the user keeps it by hand.
+ */
+const worktreeForRun = (metadata: ChatTopicMetadata | undefined): OwnedWorktree | undefined => {
+ const paths = getTopicWorktreePaths(metadata);
+ if (paths.length === 0) return;
+ return resolveOwnedWorktrees(metadata).find((entry) => paths.includes(entry.path));
+};
+
+/** How long a turn waits for a cleanup that is deleting its worktree right now. */
+const BUSY_WAIT_MS = 120_000;
+const BUSY_POLL_MS = 2000;
+
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+
+/**
+ * Ask until the worktree is no longer mid-cleanup: a topic restored while its
+ * archive cleanup is still deleting the folder waits for that to finish, then
+ * checks it out again — it never starts its turn in a folder about to vanish.
+ */
+const restoreWhenSettled = async (topicId: string, entry: OwnedWorktree) => {
+ const deadline = Date.now() + BUSY_WAIT_MS;
+ let waiting: { close: () => void } | undefined;
+ try {
+ for (;;) {
+ const result = await restoreOwnedWorktree(topicId, entry);
+ if (result.outcome !== 'busy' || Date.now() > deadline) return result;
+ waiting ??= toast.loading(t('worktreeRestore.waiting', { ns: 'chat' }));
+ await sleep(BUSY_POLL_MS);
+ }
+ } finally {
+ waiting?.close();
+ }
+};
+
+/** The directory a topic continues in once its worktree's branch is gone. */
+const sourceFallback = (metadata: ChatTopicMetadata, entry: OwnedWorktree): ChatTopicMetadata => {
+ const config = metadata.workingDirectoryConfig;
+ return {
+ ...metadata,
+ workingDirectory: entry.sourcePath,
+ workingDirectoryConfig: {
+ ...(config?.environmentId && { environmentId: config.environmentId }),
+ path: entry.sourcePath,
+ ...(config?.repoType && { repoType: config.repoType }),
+ },
+ };
+};
+
+/**
+ * Before a turn runs in a topic brought back from the archive or the recycle
+ * bin, check out again the worktree the app created for it and the cleanup
+ * removed — same path, same branch (`git worktree add <path> <branch>`), so the
+ * CLI session keyed by that folder resumes. A gone branch moves the topic back
+ * to its source repository, which the server records and this turn uses.
+ *
+ * Never blocks the turn: any other failure is shown and the turn proceeds,
+ * where the missing directory surfaces through the usual spawn guide.
+ */
+export const ensureOwnedWorktreeForRun = async (
+ topic: ChatTopic | undefined,
+): Promise<ChatTopic | undefined> => {
+ const metadata = topic?.metadata;
+ const entry = worktreeForRun(metadata);
+ if (!topic || !metadata || !entry) return topic;
+
+ try {
+ // The server answers from its record, touching the device only for a
+ // folder that was removed.
+ const result = await restoreWhenSettled(topic.id, entry);
+ if (result.outcome === 'restored') return topic;
+ if (result.outcome === 'branchMissing') {
+ toast.warning({
+ description: t('worktreeRestore.branchMissingDesc', {
+ branch: entry.branch ?? '',
+ ns: 'chat',
+ }),
+ title: t('worktreeRestore.branchMissing', { ns: 'chat' }),
+ });
+ const next = { ...topic, metadata: sourceFallback(metadata, entry) };
+ const { getChatStoreState } = await import('@/store/chat');
+ getChatStoreState().internal_dispatchTopic(
+ { id: topic.id, type: 'updateTopic', value: { metadata: next.metadata } },
+ 'ensureOwnedWorktreeForRun/branchMissing',
+ );
+ return next;
+ }
+ toast.error({
+ description:
+ result.outcome === 'busy'
+ ? t('worktreeRestore.stillCleaning', { ns: 'chat' })
+ : result.error,
+ title: t('worktreeRestore.failed', { ns: 'chat' }),
+ });
+ } catch (error) {
+ console.warn('[ensureOwnedWorktreeForRun] restore failed:', error);
+ }
+ return topic;
+};
diff --git a/src/store/chat/slices/agentRun/actions/entries/resolveExistingTopic.ts b/src/store/chat/slices/agentRun/actions/entries/resolveExistingTopic.ts
index be5e869a521..16196cdfe21 100644
--- a/src/store/chat/slices/agentRun/actions/entries/resolveExistingTopic.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/resolveExistingTopic.ts
@@ -1,5 +1,7 @@
import type { ChatTopic } from '@/types/topic';
+import { ensureOwnedWorktreeForRun } from './ownedWorktreeRestore';
+
/**
* Resolve the topic row a run should read its metadata from.
*
@@ -16,17 +18,28 @@ import type { ChatTopic } from '@/types/topic';
* to the old behavior rather than blocking the turn.
*/
export const resolveExistingTopicForRun = async (params: {
+ /**
+ * Bring back the worktree the app created for a restored topic before the
+ * turn runs in it (see `ensureOwnedWorktreeForRun`); injectable for tests.
+ */
+ ensureWorktree?: (topic: ChatTopic | undefined) => Promise<ChatTopic | undefined>;
fetchTopicDetail: (id: string) => Promise<ChatTopic | null>;
/** Only hetero runs consume topic-bound cwd/session metadata — skip the round-trip otherwise. */
isHetero: boolean;
storeTopic: ChatTopic | undefined;
topicId: string | null | undefined;
}): Promise<ChatTopic | undefined> => {
- const { fetchTopicDetail, isHetero, storeTopic, topicId } = params;
- if (storeTopic) return storeTopic;
+ const {
+ ensureWorktree = ensureOwnedWorktreeForRun,
+ fetchTopicDetail,
+ isHetero,
+ storeTopic,
+ topicId,
+ } = params;
+ if (storeTopic) return ensureWorktree(storeTopic);
if (!topicId || !isHetero) return undefined;
try {
- return (await fetchTopicDetail(topicId)) ?? undefined;
+ return await ensureWorktree((await fetchTopicDetail(topicId)) ?? undefined);
} catch (error) {
console.error('[resolveExistingTopicForRun] Failed to fetch topic detail:', error);
return undefined;