diff --git a/CONTEXT.md b/CONTEXT.md new file mode 100644 index 0000000000..2f217e8db9 --- /dev/null +++ b/CONTEXT.md @@ -0,0 +1,69 @@ +# Codex Worktrees + +This context describes how Codex names and reasons about Git-backed session destinations. The product exposes the familiar Git term while distinguishing those destinations from the broader notion of a session workspace. + +## Language + +**Workspace**: +The filesystem location where a Codex session runs. + +**Managed worktree**: +A Codex-owned workspace backed by a Git worktree. +_Avoid_: workspace when the Git-backed ownership matters + +**External worktree**: +A Git worktree visible to Codex but not owned or mutated by Codex. + +**Worktree origin**: +The current creator lineage of a managed worktree, such as CLI or App, retained for compatibility while clients converge on one app-server-backed implementation. + +**Worktree**: +The user-facing term for a managed worktree, matching the Codex App and developers' existing Git vocabulary. +_Avoid_: workspace when referring specifically to the product feature + +**Worktree management**: +Standalone creation, inspection, and removal of managed worktrees outside a running Codex session. + +**Worktree launch**: +Starting a Codex session in a named managed worktree, creating it when needed. + +**Worktree switching**: +Moving an active Codex session into a managed worktree from inside the TUI. + +## Relationships + +- A **managed worktree** is one kind of **workspace** +- An **external worktree** is a visible **workspace** that Codex does not own +- A **worktree** is the user-facing name for a **managed worktree** +- A **worktree origin** describes current provenance, not a permanent product subtype +- A **workspace** may exist without being a **managed worktree** +- **Worktree management** operates on **managed worktrees** whether or not a session is currently running in them +- **Worktree launch** may create or reuse a **managed worktree** before the session begins +- **Worktree switching** may create or reuse a **managed worktree** after the session has begun +- **Worktree management**, **worktree launch**, and **worktree switching** share the app-server-backed managed-worktree model + +## Example dialogue + +> **Dev:** "When a user chooses a **worktree**, are they choosing any **workspace**?" +> **Domain expert:** "No — they are choosing a Codex-managed Git-backed **workspace**." +> +> **Dev:** "Does a **worktree** only exist once a session starts there?" +> **Domain expert:** "No — **worktree management** lets users create and inspect it before a session enters it." +> +> **Dev:** "Why can `--worktree` create one instead of only selecting an existing one?" +> **Domain expert:** "Because **worktree launch** should be a one-step path into the named worktree." +> +> **Dev:** "Can `--force` remove an **external worktree**?" +> **Domain expert:** "No — force bypasses cleanliness checks, not ownership." +> +> **Dev:** "Are CLI and App worktrees different products?" +> **Domain expert:** "No — their **worktree origins** differ today while the App is still migrating toward the shared app-server implementation." +> +> **Dev:** "Can remote CLI commands manage worktrees outside a session?" +> **Domain expert:** "Yes — remote and local management both go through app-server." + +## Flagged ambiguities + +- "workspace" and "worktree" were being used interchangeably — resolved: **workspace** is broader; **worktree** names the Git-backed product feature. +- "force" could imply bypassing ownership — resolved: it only bypasses dirty-state protection for **managed worktrees**. +- "CLI worktree" and "App worktree" could sound like permanent subtypes — resolved: they are current **worktree origins**, not the long-term domain model. diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 8c2fa5141c..4cc383cb78 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -2180,6 +2180,7 @@ dependencies = [ "clap", "clap_complete", "codex-app-server", + "codex-app-server-client", "codex-app-server-protocol", "codex-app-server-test-client", "codex-arg0", @@ -2193,6 +2194,7 @@ dependencies = [ "codex-exec-server", "codex-execpolicy", "codex-features", + "codex-feedback", "codex-login", "codex-mcp", "codex-mcp-server", diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 6a49d3129c..c2c57dab67 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -4621,6 +4621,10 @@ "WorktreeListParams": { "description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.", "properties": { + "all": { + "description": "Include managed worktrees from every repository known to this app-server.", + "type": "boolean" + }, "cwd": { "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", "type": [ @@ -4631,6 +4635,15 @@ }, "type": "object" }, + "WorktreePruneParams": { + "description": "Remove stale managed worktree metadata from app-server storage.", + "properties": { + "dryRun": { + "type": "boolean" + } + }, + "type": "object" + }, "WorktreeRemoveParams": { "description": "Remove a managed worktree in the repository containing \\`cwd\\`.", "properties": { @@ -5765,6 +5778,30 @@ "title": "Worktree/removeRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "worktree/prune" + ], + "title": "Worktree/pruneRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WorktreePruneParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/pruneRequest", + "type": "object" + }, { "properties": { "id": { diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json index b113e717e7..ae66b58cb4 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.schemas.json @@ -1290,6 +1290,30 @@ "title": "Worktree/removeRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "worktree/prune" + ], + "title": "Worktree/pruneRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/WorktreePruneParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/pruneRequest", + "type": "object" + }, { "properties": { "id": { @@ -18946,6 +18970,10 @@ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.", "properties": { + "all": { + "description": "Include managed worktrees from every repository known to this app-server.", + "type": "boolean" + }, "cwd": { "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", "type": [ @@ -18982,6 +19010,34 @@ ], "type": "string" }, + "WorktreePruneParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Remove stale managed worktree metadata from app-server storage.", + "properties": { + "dryRun": { + "type": "boolean" + } + }, + "title": "WorktreePruneParams", + "type": "object" + }, + "WorktreePruneResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Result returned by `worktree/prune`.", + "properties": { + "paths": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "paths" + ], + "title": "WorktreePruneResponse", + "type": "object" + }, "WorktreeRemoveParams": { "$schema": "http://json-schema.org/draft-07/schema#", "description": "Remove a managed worktree in the repository containing \\`cwd\\`.", diff --git a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json index 84fe8f04f8..055f0c21d6 100644 --- a/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json +++ b/codex-rs/app-server-protocol/schema/json/codex_app_server_protocol.v2.schemas.json @@ -2049,6 +2049,30 @@ "title": "Worktree/removeRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "worktree/prune" + ], + "title": "Worktree/pruneRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WorktreePruneParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/pruneRequest", + "type": "object" + }, { "properties": { "id": { @@ -16832,6 +16856,10 @@ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.", "properties": { + "all": { + "description": "Include managed worktrees from every repository known to this app-server.", + "type": "boolean" + }, "cwd": { "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", "type": [ @@ -16868,6 +16896,34 @@ ], "type": "string" }, + "WorktreePruneParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Remove stale managed worktree metadata from app-server storage.", + "properties": { + "dryRun": { + "type": "boolean" + } + }, + "title": "WorktreePruneParams", + "type": "object" + }, + "WorktreePruneResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Result returned by `worktree/prune`.", + "properties": { + "paths": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "paths" + ], + "title": "WorktreePruneResponse", + "type": "object" + }, "WorktreeRemoveParams": { "$schema": "http://json-schema.org/draft-07/schema#", "description": "Remove a managed worktree in the repository containing \\`cwd\\`.", diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreeListParams.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreeListParams.json index 50943d6908..129395c2f6 100644 --- a/codex-rs/app-server-protocol/schema/json/v2/WorktreeListParams.json +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreeListParams.json @@ -2,6 +2,10 @@ "$schema": "http://json-schema.org/draft-07/schema#", "description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.", "properties": { + "all": { + "description": "Include managed worktrees from every repository known to this app-server.", + "type": "boolean" + }, "cwd": { "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", "type": [ diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreePruneParams.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreePruneParams.json new file mode 100644 index 0000000000..a8e78c340c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreePruneParams.json @@ -0,0 +1,11 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Remove stale managed worktree metadata from app-server storage.", + "properties": { + "dryRun": { + "type": "boolean" + } + }, + "title": "WorktreePruneParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreePruneResponse.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreePruneResponse.json new file mode 100644 index 0000000000..e2ccc7afff --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreePruneResponse.json @@ -0,0 +1,17 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Result returned by `worktree/prune`.", + "properties": { + "paths": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "paths" + ], + "title": "WorktreePruneResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts index 9f0030d994..4a26f0f841 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts @@ -81,9 +81,10 @@ import type { WindowsSandboxSetupStartParams } from "./v2/WindowsSandboxSetupSta import type { WorktreeCreateParams } from "./v2/WorktreeCreateParams"; import type { WorktreeInspectSourceParams } from "./v2/WorktreeInspectSourceParams"; import type { WorktreeListParams } from "./v2/WorktreeListParams"; +import type { WorktreePruneParams } from "./v2/WorktreePruneParams"; import type { WorktreeRemoveParams } from "./v2/WorktreeRemoveParams"; /** * Request from the client to the server. */ -export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/approveGuardianDeniedAction", id: RequestId, params: ThreadApproveGuardianDeniedActionParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "hooks/list", id: RequestId, params: HooksListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "marketplace/upgrade", id: RequestId, params: MarketplaceUpgradeParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "plugin/skill/read", id: RequestId, params: PluginSkillReadParams, } | { "method": "plugin/share/save", id: RequestId, params: PluginShareSaveParams, } | { "method": "plugin/share/updateTargets", id: RequestId, params: PluginShareUpdateTargetsParams, } | { "method": "plugin/share/list", id: RequestId, params: PluginShareListParams, } | { "method": "plugin/share/delete", id: RequestId, params: PluginShareDeleteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "device/key/create", id: RequestId, params: DeviceKeyCreateParams, } | { "method": "device/key/public", id: RequestId, params: DeviceKeyPublicParams, } | { "method": "device/key/sign", id: RequestId, params: DeviceKeySignParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "worktree/list", id: RequestId, params: WorktreeListParams, } | { "method": "worktree/inspectSource", id: RequestId, params: WorktreeInspectSourceParams, } | { "method": "worktree/create", id: RequestId, params: WorktreeCreateParams, } | { "method": "worktree/remove", id: RequestId, params: WorktreeRemoveParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "modelProvider/capabilities/read", id: RequestId, params: ModelProviderCapabilitiesReadParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "windowsSandbox/readiness", id: RequestId, params: undefined, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; +export type ClientRequest ={ "method": "initialize", id: RequestId, params: InitializeParams, } | { "method": "thread/start", id: RequestId, params: ThreadStartParams, } | { "method": "thread/resume", id: RequestId, params: ThreadResumeParams, } | { "method": "thread/fork", id: RequestId, params: ThreadForkParams, } | { "method": "thread/archive", id: RequestId, params: ThreadArchiveParams, } | { "method": "thread/unsubscribe", id: RequestId, params: ThreadUnsubscribeParams, } | { "method": "thread/name/set", id: RequestId, params: ThreadSetNameParams, } | { "method": "thread/metadata/update", id: RequestId, params: ThreadMetadataUpdateParams, } | { "method": "thread/unarchive", id: RequestId, params: ThreadUnarchiveParams, } | { "method": "thread/compact/start", id: RequestId, params: ThreadCompactStartParams, } | { "method": "thread/shellCommand", id: RequestId, params: ThreadShellCommandParams, } | { "method": "thread/approveGuardianDeniedAction", id: RequestId, params: ThreadApproveGuardianDeniedActionParams, } | { "method": "thread/rollback", id: RequestId, params: ThreadRollbackParams, } | { "method": "thread/list", id: RequestId, params: ThreadListParams, } | { "method": "thread/loaded/list", id: RequestId, params: ThreadLoadedListParams, } | { "method": "thread/read", id: RequestId, params: ThreadReadParams, } | { "method": "thread/inject_items", id: RequestId, params: ThreadInjectItemsParams, } | { "method": "skills/list", id: RequestId, params: SkillsListParams, } | { "method": "hooks/list", id: RequestId, params: HooksListParams, } | { "method": "marketplace/add", id: RequestId, params: MarketplaceAddParams, } | { "method": "marketplace/remove", id: RequestId, params: MarketplaceRemoveParams, } | { "method": "marketplace/upgrade", id: RequestId, params: MarketplaceUpgradeParams, } | { "method": "plugin/list", id: RequestId, params: PluginListParams, } | { "method": "plugin/read", id: RequestId, params: PluginReadParams, } | { "method": "plugin/skill/read", id: RequestId, params: PluginSkillReadParams, } | { "method": "plugin/share/save", id: RequestId, params: PluginShareSaveParams, } | { "method": "plugin/share/updateTargets", id: RequestId, params: PluginShareUpdateTargetsParams, } | { "method": "plugin/share/list", id: RequestId, params: PluginShareListParams, } | { "method": "plugin/share/delete", id: RequestId, params: PluginShareDeleteParams, } | { "method": "app/list", id: RequestId, params: AppsListParams, } | { "method": "device/key/create", id: RequestId, params: DeviceKeyCreateParams, } | { "method": "device/key/public", id: RequestId, params: DeviceKeyPublicParams, } | { "method": "device/key/sign", id: RequestId, params: DeviceKeySignParams, } | { "method": "fs/readFile", id: RequestId, params: FsReadFileParams, } | { "method": "fs/writeFile", id: RequestId, params: FsWriteFileParams, } | { "method": "fs/createDirectory", id: RequestId, params: FsCreateDirectoryParams, } | { "method": "fs/getMetadata", id: RequestId, params: FsGetMetadataParams, } | { "method": "fs/readDirectory", id: RequestId, params: FsReadDirectoryParams, } | { "method": "fs/remove", id: RequestId, params: FsRemoveParams, } | { "method": "fs/copy", id: RequestId, params: FsCopyParams, } | { "method": "fs/watch", id: RequestId, params: FsWatchParams, } | { "method": "fs/unwatch", id: RequestId, params: FsUnwatchParams, } | { "method": "worktree/list", id: RequestId, params: WorktreeListParams, } | { "method": "worktree/inspectSource", id: RequestId, params: WorktreeInspectSourceParams, } | { "method": "worktree/create", id: RequestId, params: WorktreeCreateParams, } | { "method": "worktree/remove", id: RequestId, params: WorktreeRemoveParams, } | { "method": "worktree/prune", id: RequestId, params: WorktreePruneParams, } | { "method": "skills/config/write", id: RequestId, params: SkillsConfigWriteParams, } | { "method": "plugin/install", id: RequestId, params: PluginInstallParams, } | { "method": "plugin/uninstall", id: RequestId, params: PluginUninstallParams, } | { "method": "turn/start", id: RequestId, params: TurnStartParams, } | { "method": "turn/steer", id: RequestId, params: TurnSteerParams, } | { "method": "turn/interrupt", id: RequestId, params: TurnInterruptParams, } | { "method": "review/start", id: RequestId, params: ReviewStartParams, } | { "method": "model/list", id: RequestId, params: ModelListParams, } | { "method": "modelProvider/capabilities/read", id: RequestId, params: ModelProviderCapabilitiesReadParams, } | { "method": "experimentalFeature/list", id: RequestId, params: ExperimentalFeatureListParams, } | { "method": "experimentalFeature/enablement/set", id: RequestId, params: ExperimentalFeatureEnablementSetParams, } | { "method": "mcpServer/oauth/login", id: RequestId, params: McpServerOauthLoginParams, } | { "method": "config/mcpServer/reload", id: RequestId, params: undefined, } | { "method": "mcpServerStatus/list", id: RequestId, params: ListMcpServerStatusParams, } | { "method": "mcpServer/resource/read", id: RequestId, params: McpResourceReadParams, } | { "method": "mcpServer/tool/call", id: RequestId, params: McpServerToolCallParams, } | { "method": "windowsSandbox/setupStart", id: RequestId, params: WindowsSandboxSetupStartParams, } | { "method": "windowsSandbox/readiness", id: RequestId, params: undefined, } | { "method": "account/login/start", id: RequestId, params: LoginAccountParams, } | { "method": "account/login/cancel", id: RequestId, params: CancelLoginAccountParams, } | { "method": "account/logout", id: RequestId, params: undefined, } | { "method": "account/rateLimits/read", id: RequestId, params: undefined, } | { "method": "account/sendAddCreditsNudgeEmail", id: RequestId, params: SendAddCreditsNudgeEmailParams, } | { "method": "feedback/upload", id: RequestId, params: FeedbackUploadParams, } | { "method": "command/exec", id: RequestId, params: CommandExecParams, } | { "method": "command/exec/write", id: RequestId, params: CommandExecWriteParams, } | { "method": "command/exec/terminate", id: RequestId, params: CommandExecTerminateParams, } | { "method": "command/exec/resize", id: RequestId, params: CommandExecResizeParams, } | { "method": "config/read", id: RequestId, params: ConfigReadParams, } | { "method": "externalAgentConfig/detect", id: RequestId, params: ExternalAgentConfigDetectParams, } | { "method": "externalAgentConfig/import", id: RequestId, params: ExternalAgentConfigImportParams, } | { "method": "config/value/write", id: RequestId, params: ConfigValueWriteParams, } | { "method": "config/batchWrite", id: RequestId, params: ConfigBatchWriteParams, } | { "method": "configRequirements/read", id: RequestId, params: undefined, } | { "method": "account/read", id: RequestId, params: GetAccountParams, } | { "method": "getConversationSummary", id: RequestId, params: GetConversationSummaryParams, } | { "method": "gitDiffToRemote", id: RequestId, params: GitDiffToRemoteParams, } | { "method": "getAuthStatus", id: RequestId, params: GetAuthStatusParams, } | { "method": "fuzzyFileSearch", id: RequestId, params: FuzzyFileSearchParams, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListParams.ts index c94e410ad3..a6da598903 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListParams.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListParams.ts @@ -9,4 +9,8 @@ export type WorktreeListParams = { /** * Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd. */ -cwd?: string | null, }; +cwd?: string | null, +/** + * Include managed worktrees from every repository known to this app-server. + */ +all?: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreePruneParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreePruneParams.ts new file mode 100644 index 0000000000..9f98085b87 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreePruneParams.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Remove stale managed worktree metadata from app-server storage. + */ +export type WorktreePruneParams = { dryRun?: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreePruneResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreePruneResponse.ts new file mode 100644 index 0000000000..e6deae3bfa --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreePruneResponse.ts @@ -0,0 +1,8 @@ +// GENERATED CODE! DO NOT MODIFY BY HAND! + +// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually. + +/** + * Result returned by `worktree/prune`. + */ +export type WorktreePruneResponse = { paths: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts index f894ec2e33..d339f32ff8 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -462,6 +462,8 @@ export type { WorktreeInspectSourceResponse } from "./WorktreeInspectSourceRespo export type { WorktreeListParams } from "./WorktreeListParams"; export type { WorktreeListResponse } from "./WorktreeListResponse"; export type { WorktreeLocation } from "./WorktreeLocation"; +export type { WorktreePruneParams } from "./WorktreePruneParams"; +export type { WorktreePruneResponse } from "./WorktreePruneResponse"; export type { WorktreeRemoveParams } from "./WorktreeRemoveParams"; export type { WorktreeRemoveResponse } from "./WorktreeRemoveResponse"; export type { WorktreeSource } from "./WorktreeSource"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index ae008b496b..3fb874da41 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -730,6 +730,11 @@ client_request_definitions! { serialization: global("worktree"), response: v2::WorktreeRemoveResponse, }, + WorktreePrune => "worktree/prune" { + params: v2::WorktreePruneParams, + serialization: global("worktree"), + response: v2::WorktreePruneResponse, + }, SkillsConfigWrite => "skills/config/write" { params: v2::SkillsConfigWriteParams, serialization: global("config"), diff --git a/codex-rs/app-server-protocol/src/protocol/v2/worktree.rs b/codex-rs/app-server-protocol/src/protocol/v2/worktree.rs index 35c802255a..a92e50b5ad 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/worktree.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/worktree.rs @@ -11,6 +11,9 @@ pub struct WorktreeListParams { /// Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd. #[ts(optional = nullable)] pub cwd: Option, + /// Include managed worktrees from every repository known to this app-server. + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub all: bool, } /// Managed worktrees returned by \`worktree/list\`. @@ -87,6 +90,23 @@ pub struct WorktreeRemoveResponse { pub deleted_branch: Option, } +/// Remove stale managed worktree metadata from app-server storage. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreePruneParams { + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub dry_run: bool, +} + +/// Result returned by `worktree/prune`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreePruneResponse { + pub paths: Vec, +} + /// Server-native representation of a managed worktree. #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] #[serde(rename_all = "camelCase")] diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index 421450c5e7..b938ce2f6b 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -1152,10 +1152,11 @@ All filesystem paths in this section must be absolute. ### Worktrees -- `worktree/list` - list Codex-managed worktrees for the repository containing `cwd`; omitted `cwd` uses the app server's effective cwd. +- `worktree/list` - list Codex-managed worktrees for the repository containing `cwd`; omitted `cwd` uses the app server's effective cwd, and `all` returns worktrees from every repository. - `worktree/inspectSource` - inspect staged, unstaged, and untracked dirty state for the repository containing `cwd`. - `worktree/create` - create or reuse a managed worktree from `cwd`, returning the resolved worktree plus any transfer warnings. - `worktree/remove` - remove a managed worktree resolved from `cwd` and `nameOrPath`, with optional `force` and `deleteBranch` behavior. +- `worktree/prune` - remove stale managed-worktree storage entries, or report them without mutation when `dryRun` is set. ## Events diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index 208983d651..d604b74c5d 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -961,6 +961,11 @@ impl MessageProcessor { .remove(params) .await .map(|response| Some(response.into())), + ClientRequest::WorktreePrune { params, .. } => self + .worktree_processor + .prune(params) + .await + .map(|response| Some(response.into())), ClientRequest::ModelProviderCapabilitiesRead { params: _, .. } => self .config_processor .model_provider_capabilities_read() diff --git a/codex-rs/app-server/src/request_processors.rs b/codex-rs/app-server/src/request_processors.rs index ad9845192c..753acc8272 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -251,6 +251,8 @@ use codex_app_server_protocol::WorktreeInspectSourceResponse; use codex_app_server_protocol::WorktreeListParams; use codex_app_server_protocol::WorktreeListResponse; use codex_app_server_protocol::WorktreeLocation as ApiWorktreeLocation; +use codex_app_server_protocol::WorktreePruneParams; +use codex_app_server_protocol::WorktreePruneResponse; use codex_app_server_protocol::WorktreeRemoveParams; use codex_app_server_protocol::WorktreeRemoveResponse; use codex_app_server_protocol::WorktreeSource as ApiWorktreeSource; diff --git a/codex-rs/app-server/src/request_processors/worktree_processor.rs b/codex-rs/app-server/src/request_processors/worktree_processor.rs index 0e55356691..c912cb9c25 100644 --- a/codex-rs/app-server/src/request_processors/worktree_processor.rs +++ b/codex-rs/app-server/src/request_processors/worktree_processor.rs @@ -26,11 +26,15 @@ impl WorktreeRequestProcessor { &self, params: WorktreeListParams, ) -> Result { - let cwd = self.resolve_cwd(params.cwd).await?; + let source_cwd = if params.all { + None + } else { + Some(self.resolve_cwd(params.cwd).await?) + }; let data = codex_worktree::list_worktrees(WorktreeListQuery { codex_home: self.config_manager.codex_home().to_path_buf(), - source_cwd: Some(cwd), - include_all_repos: false, + source_cwd, + include_all_repos: params.all, }) .map_err(map_worktree_error)? .into_iter() @@ -91,6 +95,31 @@ impl WorktreeRequestProcessor { }) } + pub(crate) async fn prune( + &self, + params: WorktreePruneParams, + ) -> Result { + let stale_paths = + codex_worktree::stale_managed_worktree_dirs(self.config_manager.codex_home()) + .map_err(map_worktree_error)?; + if !params.dry_run { + for path in &stale_paths { + std::fs::remove_dir_all(path).map_err(|err| { + map_worktree_error(anyhow::anyhow!( + "failed to remove stale worktree directory {}: {err}", + path.display() + )) + })?; + } + } + Ok(WorktreePruneResponse { + paths: stale_paths + .into_iter() + .map(|path| path.to_string_lossy().to_string()) + .collect(), + }) + } + async fn resolve_cwd(&self, cwd: Option) -> Result { match cwd { Some(cwd) => Ok(PathBuf::from(cwd)), diff --git a/codex-rs/cli/Cargo.toml b/codex-rs/cli/Cargo.toml index 89249654ea..3560a9cb1e 100644 --- a/codex-rs/cli/Cargo.toml +++ b/codex-rs/cli/Cargo.toml @@ -21,6 +21,7 @@ anyhow = { workspace = true } clap = { workspace = true, features = ["derive"] } clap_complete = { workspace = true } codex-app-server = { workspace = true } +codex-app-server-client = { workspace = true } codex-app-server-protocol = { workspace = true } codex-app-server-test-client = { workspace = true } codex-arg0 = { workspace = true } @@ -34,6 +35,7 @@ codex-core-plugins = { workspace = true } codex-exec = { workspace = true } codex-exec-server = { workspace = true } codex-execpolicy = { workspace = true } +codex-feedback = { workspace = true } codex-features = { workspace = true } codex-login = { workspace = true } codex-memories-write = { workspace = true } diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index 954f4227a0..d65a4bb90d 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -3,6 +3,26 @@ use clap::CommandFactory; use clap::Parser; use clap_complete::Shell; use clap_complete::generate; +use codex_app_server_client::AppServerClient; +use codex_app_server_client::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY; +use codex_app_server_client::EnvironmentManager; +use codex_app_server_client::EnvironmentManagerArgs; +use codex_app_server_client::ExecServerRuntimePaths; +use codex_app_server_client::InProcessAppServerClient; +use codex_app_server_client::InProcessClientStartArgs; +use codex_app_server_client::RemoteAppServerClient; +use codex_app_server_client::RemoteAppServerConnectArgs; +use codex_app_server_protocol::ClientRequest; +use codex_app_server_protocol::RequestId; +use codex_app_server_protocol::WorktreeCreateParams; +use codex_app_server_protocol::WorktreeCreateResponse; +use codex_app_server_protocol::WorktreeDirtyPolicy as ApiWorktreeDirtyPolicy; +use codex_app_server_protocol::WorktreeListParams; +use codex_app_server_protocol::WorktreeListResponse; +use codex_app_server_protocol::WorktreePruneParams; +use codex_app_server_protocol::WorktreePruneResponse; +use codex_app_server_protocol::WorktreeRemoveParams; +use codex_app_server_protocol::WorktreeRemoveResponse; use codex_arg0::Arg0DispatchPaths; use codex_arg0::arg0_dispatch_or_else; use codex_chatgpt::apply_command::ApplyCommand; @@ -36,17 +56,12 @@ use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_cli::CliConfigOverrides; use codex_utils_cli::SharedCliOptions; use codex_utils_cli::WorktreeDirtyCliArg; -use codex_worktree::DirtyPolicy; use codex_worktree::WorktreeInfo; -use codex_worktree::WorktreeListQuery; -use codex_worktree::WorktreeRemoveRequest; -use codex_worktree::WorktreeRequest; use codex_worktree::WorktreeResolution; use owo_colors::OwoColorize; -use std::fs; use std::io::IsTerminal; -use std::path::Path; use std::path::PathBuf; +use std::sync::Arc; use supports_color::Stream; #[cfg(any(target_os = "macos", target_os = "windows"))] @@ -760,10 +775,11 @@ async fn run_debug_app_server_command(cmd: DebugAppServerCommand) -> anyhow::Res } } -fn resolve_worktree_options_for_shared_cli( +async fn resolve_worktree_options_for_shared_cli( shared: &mut SharedCliOptions, remote: Option<&str>, remote_auth_token_env: Option<&str>, + arg0_paths: Arg0DispatchPaths, ) -> anyhow::Result> { let Some(branch) = shared.worktree.take() else { return Ok(None); @@ -773,15 +789,33 @@ fn resolve_worktree_options_for_shared_cli( anyhow::bail!("--worktree is not supported with remote app-server sessions yet"); } - let codex_home = find_codex_home()?.to_path_buf(); let source_cwd = shared.cwd.clone().unwrap_or(std::env::current_dir()?); - let resolution = codex_worktree::ensure_worktree(WorktreeRequest { - codex_home, - source_cwd, - branch, - base_ref: shared.worktree_base.take(), - dirty_policy: dirty_policy_from_cli(shared.worktree_dirty), - })?; + let client = worktree_app_server_client( + /*remote*/ None, /*remote_auth_token_env*/ None, arg0_paths, + ) + .await?; + let response: WorktreeCreateResponse = client + .request_typed(ClientRequest::WorktreeCreate { + request_id: RequestId::Integer(1), + params: WorktreeCreateParams { + cwd: Some(source_cwd.to_string_lossy().to_string()), + branch, + base_ref: shared.worktree_base.take(), + dirty_policy: api_dirty_policy_from_cli(shared.worktree_dirty), + }, + }) + .await?; + let resolution = WorktreeResolution { + reused: response.reused, + info: worktree_info_from_api(response.info)?, + warnings: response + .warnings + .into_iter() + .map(|warning| codex_worktree::WorktreeWarning { + message: warning.message, + }) + .collect(), + }; shared.cwd = Some(resolution.info.workspace_cwd.clone()); #[allow(clippy::print_stderr)] @@ -792,70 +826,79 @@ fn resolve_worktree_options_for_shared_cli( Ok(Some(resolution)) } -fn dirty_policy_from_cli(arg: WorktreeDirtyCliArg) -> DirtyPolicy { - match arg { - WorktreeDirtyCliArg::Fail => DirtyPolicy::Fail, - WorktreeDirtyCliArg::Ignore => DirtyPolicy::Ignore, - WorktreeDirtyCliArg::CopyTracked => DirtyPolicy::CopyTracked, - WorktreeDirtyCliArg::CopyAll => DirtyPolicy::CopyAll, - WorktreeDirtyCliArg::MoveTracked => DirtyPolicy::MoveTracked, - WorktreeDirtyCliArg::MoveAll => DirtyPolicy::MoveAll, - } -} - -fn run_worktree_command(cli: WorktreeCli) -> anyhow::Result<()> { - let codex_home = find_codex_home()?.to_path_buf(); +async fn run_worktree_command( + cli: WorktreeCli, + remote: Option, + remote_auth_token_env: Option, + arg0_paths: Arg0DispatchPaths, +) -> anyhow::Result<()> { + let is_remote = remote.is_some(); + let client = worktree_app_server_client(remote, remote_auth_token_env, arg0_paths).await?; + let cwd = (!is_remote) + .then(std::env::current_dir) + .transpose()? + .map(|cwd| cwd.to_string_lossy().to_string()); + let mut next_request_id = 1_i64; match cli.subcommand { WorktreeSubcommand::Create(command) => { - let resolution = codex_worktree::ensure_worktree(WorktreeRequest { - codex_home, - source_cwd: std::env::current_dir()?, - branch: command.branch, - base_ref: command.base_ref, - dirty_policy: dirty_policy_from_cli(command.dirty), - })?; + let resolution: WorktreeCreateResponse = client + .request_typed(ClientRequest::WorktreeCreate { + request_id: next_cli_request_id(&mut next_request_id), + params: WorktreeCreateParams { + cwd: cwd.clone(), + branch: command.branch, + base_ref: command.base_ref, + dirty_policy: api_dirty_policy_from_cli(command.dirty), + }, + }) + .await?; for warning in &resolution.warnings { eprintln!("warning: {}", warning.message); } - println!("{}", resolution.info.workspace_cwd.display()); + println!("{}", resolution.info.workspace_cwd); } WorktreeSubcommand::List(command) => { - let source_cwd = if command.all { - None - } else { - Some(std::env::current_dir()?) - }; - let entries = codex_worktree::list_worktrees(WorktreeListQuery { - codex_home, - source_cwd, - include_all_repos: command.all, - })?; + let entries = + cli_list_worktrees(&client, cwd.clone(), command.all, &mut next_request_id).await?; print_worktree_list(entries, command.json)?; } WorktreeSubcommand::Path(command) => { - let entries = codex_worktree::list_worktrees(WorktreeListQuery { - codex_home, - source_cwd: Some(std::env::current_dir()?), - include_all_repos: false, - })?; + let entries = + cli_list_worktrees(&client, cwd.clone(), false, &mut next_request_id).await?; let entry = find_named_worktree(entries, &command.name)?; println!("{}", entry.workspace_cwd.display()); } WorktreeSubcommand::Remove(command) => { - let result = codex_worktree::remove_worktree(WorktreeRemoveRequest { - codex_home, - source_cwd: Some(std::env::current_dir()?), - name_or_path: command.name_or_path, - force: command.force, - delete_branch: command.delete_branch, - })?; - println!("removed {}", result.removed_path.display()); + let result: WorktreeRemoveResponse = client + .request_typed(ClientRequest::WorktreeRemove { + request_id: next_cli_request_id(&mut next_request_id), + params: WorktreeRemoveParams { + cwd, + name_or_path: command.name_or_path, + force: command.force, + delete_branch: command.delete_branch, + }, + }) + .await?; + println!("removed {}", result.removed_path); if let Some(branch) = result.deleted_branch { println!("deleted branch {branch}"); } } WorktreeSubcommand::Prune(command) => { - let stale_paths = stale_managed_worktree_dirs(&codex_home)?; + let response: WorktreePruneResponse = client + .request_typed(ClientRequest::WorktreePrune { + request_id: next_cli_request_id(&mut next_request_id), + params: WorktreePruneParams { + dry_run: command.dry_run || command.json, + }, + }) + .await?; + let stale_paths = response + .paths + .into_iter() + .map(PathBuf::from) + .collect::>(); if command.json { println!("{}", serde_json::to_string_pretty(&stale_paths)?); } else if stale_paths.is_empty() { @@ -865,7 +908,6 @@ fn run_worktree_command(cli: WorktreeCli) -> anyhow::Result<()> { if command.dry_run { println!("would remove {}", path.display()); } else { - fs::remove_dir_all(path)?; println!("removed {}", path.display()); } } @@ -875,6 +917,133 @@ fn run_worktree_command(cli: WorktreeCli) -> anyhow::Result<()> { Ok(()) } +async fn cli_list_worktrees( + client: &AppServerClient, + cwd: Option, + all: bool, + next_request_id: &mut i64, +) -> anyhow::Result> { + let response: WorktreeListResponse = client + .request_typed(ClientRequest::WorktreeList { + request_id: next_cli_request_id(next_request_id), + params: WorktreeListParams { cwd, all }, + }) + .await?; + response + .data + .into_iter() + .map(worktree_info_from_api) + .collect() +} + +fn next_cli_request_id(next: &mut i64) -> RequestId { + let request_id = RequestId::Integer(*next); + *next += 1; + request_id +} + +fn api_dirty_policy_from_cli(value: WorktreeDirtyCliArg) -> ApiWorktreeDirtyPolicy { + match value { + WorktreeDirtyCliArg::Fail => ApiWorktreeDirtyPolicy::Fail, + WorktreeDirtyCliArg::Ignore => ApiWorktreeDirtyPolicy::Ignore, + WorktreeDirtyCliArg::CopyTracked => ApiWorktreeDirtyPolicy::CopyTracked, + WorktreeDirtyCliArg::CopyAll => ApiWorktreeDirtyPolicy::CopyAll, + WorktreeDirtyCliArg::MoveTracked => ApiWorktreeDirtyPolicy::MoveTracked, + WorktreeDirtyCliArg::MoveAll => ApiWorktreeDirtyPolicy::MoveAll, + } +} + +async fn worktree_app_server_client( + remote: Option, + remote_auth_token_env: Option, + arg0_paths: Arg0DispatchPaths, +) -> anyhow::Result { + if let Some(remote) = remote { + let websocket_url = + codex_tui::normalize_remote_addr(&remote).map_err(|err| anyhow::anyhow!("{err}"))?; + let auth_token = remote_auth_token_env + .map(|name| std::env::var(&name)) + .transpose()?; + return Ok(AppServerClient::Remote( + RemoteAppServerClient::connect(RemoteAppServerConnectArgs { + websocket_url, + auth_token, + client_name: "codex-cli-worktree".to_string(), + client_version: env!("CARGO_PKG_VERSION").to_string(), + experimental_api: true, + opt_out_notification_methods: Vec::new(), + channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY, + }) + .await?, + )); + } + + let config = Config::load_with_cli_overrides(Vec::new()).await?; + let local_runtime_paths = ExecServerRuntimePaths::from_optional_paths( + arg0_paths.codex_self_exe.clone(), + arg0_paths.codex_linux_sandbox_exe.clone(), + )?; + let config_warnings = config + .startup_warnings + .iter() + .map( + |warning| codex_app_server_protocol::ConfigWarningNotification { + summary: warning.clone(), + details: None, + path: None, + range: None, + }, + ) + .collect(); + Ok(AppServerClient::InProcess( + InProcessAppServerClient::start(InProcessClientStartArgs { + arg0_paths, + config: Arc::new(config), + cli_overrides: Vec::new(), + loader_overrides: codex_config::LoaderOverrides::default(), + cloud_requirements: codex_config::CloudRequirementsLoader::default(), + feedback: codex_feedback::CodexFeedback::new(), + log_db: None, + state_db: None, + environment_manager: Arc::new( + EnvironmentManager::new(EnvironmentManagerArgs::new(local_runtime_paths)).await, + ), + config_warnings, + session_source: codex_protocol::protocol::SessionSource::Cli, + enable_codex_api_key_env: false, + client_name: "codex-cli-worktree".to_string(), + client_version: env!("CARGO_PKG_VERSION").to_string(), + experimental_api: true, + opt_out_notification_methods: Vec::new(), + channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY, + }) + .await?, + )) +} + +fn worktree_info_from_api( + info: codex_app_server_protocol::WorktreeInfo, +) -> anyhow::Result { + Ok(WorktreeInfo { + id: info.id, + name: info.name, + slug: info.slug, + source: serde_json::from_value(serde_json::to_value(info.source)?)?, + location: serde_json::from_value(serde_json::to_value(info.location)?)?, + repo_name: info.repo_name, + repo_root: PathBuf::from(info.repo_root), + common_git_dir: PathBuf::from(info.common_git_dir), + worktree_git_root: PathBuf::from(info.worktree_git_root), + workspace_cwd: PathBuf::from(info.workspace_cwd), + original_relative_cwd: PathBuf::from(info.original_relative_cwd), + branch: info.branch, + head: info.head, + owner_thread_id: info.owner_thread_id, + metadata_path: PathBuf::from(info.metadata_path), + dirty: serde_json::from_value(serde_json::to_value(info.dirty)?)?, + }) +} + fn print_worktree_list(entries: Vec, json: bool) -> anyhow::Result<()> { if json { println!("{}", serde_json::to_string_pretty(&entries)?); @@ -959,52 +1128,6 @@ fn find_named_worktree(entries: Vec, name: &str) -> anyhow::Result } } -fn stale_managed_worktree_dirs(codex_home: &Path) -> anyhow::Result> { - let root = codex_worktree::codex_worktrees_root(codex_home); - if !root.exists() { - return Ok(Vec::new()); - } - - let mut stale = Vec::new(); - for repo_dir in fs::read_dir(&root)? { - let repo_dir = repo_dir?; - if !repo_dir.file_type()?.is_dir() { - continue; - } - for slug_dir in fs::read_dir(repo_dir.path())? { - let slug_dir = slug_dir?; - if !slug_dir.file_type()?.is_dir() { - continue; - } - let mut has_repo_dir = false; - for repo_root in fs::read_dir(slug_dir.path())? { - let repo_root = repo_root?; - if !repo_root.file_type()?.is_dir() { - continue; - } - has_repo_dir = true; - if !repo_root.path().join(".git").exists() || !git_root_is_valid(&repo_root.path()) - { - stale.push(repo_root.path()); - } - } - if !has_repo_dir { - stale.push(slug_dir.path()); - } - } - } - stale.sort(); - Ok(stale) -} - -fn git_root_is_valid(path: &Path) -> bool { - std::process::Command::new("git") - .args(["rev-parse", "--show-toplevel"]) - .current_dir(path) - .output() - .is_ok_and(|output| output.status.success()) -} - #[derive(Debug, Default, Parser, Clone)] struct FeatureToggles { /// Enable a feature (repeatable). Equivalent to `-c features.=true`. @@ -1135,7 +1258,9 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { &mut exec_cli.shared, /*remote*/ None, /*remote_auth_token_env*/ None, - )?; + arg0_paths.clone(), + ) + .await?; prepend_config_flags( &mut exec_cli.config_overrides, root_config_overrides.clone(), @@ -1324,12 +1449,13 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { handle_app_exit(exit_info)?; } Some(Subcommand::Worktree(worktree_cli)) => { - reject_remote_mode_for_subcommand( - root_remote.as_deref(), - root_remote_auth_token_env.as_deref(), - "worktree", - )?; - run_worktree_command(worktree_cli)?; + run_worktree_command( + worktree_cli, + root_remote.clone(), + root_remote_auth_token_env.clone(), + arg0_paths.clone(), + ) + .await?; } Some(Subcommand::Login(mut login_cli)) => { reject_remote_mode_for_subcommand( diff --git a/codex-rs/tui/src/app/worktree.rs b/codex-rs/tui/src/app/worktree.rs index 191a359c17..3efcf26fcc 100644 --- a/codex-rs/tui/src/app/worktree.rs +++ b/codex-rs/tui/src/app/worktree.rs @@ -330,6 +330,7 @@ impl App { request_id: worktree_request_id("worktree-list"), params: WorktreeListParams { cwd: Some(self.session_workspace_cwd(app_server).display().to_string()), + all: false, }, }) .await?; diff --git a/codex-rs/worktree/src/lib.rs b/codex-rs/worktree/src/lib.rs index 8c863028a0..6accd41930 100644 --- a/codex-rs/worktree/src/lib.rs +++ b/codex-rs/worktree/src/lib.rs @@ -16,6 +16,7 @@ pub use manager::ensure_worktree; pub use manager::list_worktrees; pub use manager::remove_worktree; pub use manager::resolve_worktree; +pub use manager::stale_managed_worktree_dirs; pub use metadata::WorktreeMetadata; pub use metadata::WorktreeThreadMetadata; pub use metadata::bind_thread; diff --git a/codex-rs/worktree/src/manager.rs b/codex-rs/worktree/src/manager.rs index 231bf55e14..9fbdc2e9b0 100644 --- a/codex-rs/worktree/src/manager.rs +++ b/codex-rs/worktree/src/manager.rs @@ -309,6 +309,51 @@ fn is_git_root(path: &Path) -> bool { path.join(".git").exists() } +pub fn stale_managed_worktree_dirs(codex_home: &Path) -> Result> { + let root = paths::codex_worktrees_root(codex_home); + if !root.exists() { + return Ok(Vec::new()); + } + let mut stale = Vec::new(); + for repo_dir in fs::read_dir(&root)? { + let repo_dir = repo_dir?; + if !repo_dir.file_type()?.is_dir() { + continue; + } + for slug_dir in fs::read_dir(repo_dir.path())? { + let slug_dir = slug_dir?; + if !slug_dir.file_type()?.is_dir() { + continue; + } + let mut has_repo_dir = false; + for repo_root in fs::read_dir(slug_dir.path())? { + let repo_root = repo_root?; + if !repo_root.file_type()?.is_dir() { + continue; + } + has_repo_dir = true; + if !repo_root.path().join(".git").exists() || !git_root_is_valid(&repo_root.path()) + { + stale.push(repo_root.path()); + } + } + if !has_repo_dir { + stale.push(slug_dir.path()); + } + } + } + stale.sort(); + Ok(stale) +} + +fn git_root_is_valid(path: &Path) -> bool { + std::process::Command::new("git") + .args(["rev-parse", "--show-toplevel"]) + .current_dir(path) + .output() + .is_ok_and(|output| output.status.success()) +} + fn worktree_matches_repo(info: &WorktreeInfo, repo: &SourceRepo) -> bool { info.id == repo.id || paths_match(&info.common_git_dir, &repo.common_git_dir) }