From c0a679534753eadf0d3dd8d5f2da765c20c8ab96 Mon Sep 17 00:00:00 2001 From: Felipe Coury Date: Sat, 9 May 2026 21:36:06 -0300 Subject: [PATCH] refactor(worktree): route interactive flow through app-server --- codex-rs/Cargo.lock | 1 + .../schema/json/ClientRequest.json | 187 +++ .../codex_app_server_protocol.schemas.json | 396 +++++++ .../codex_app_server_protocol.v2.schemas.json | 396 +++++++ .../schema/json/v2/WorktreeCreateParams.json | 44 + .../json/v2/WorktreeCreateResponse.json | 152 +++ .../json/v2/WorktreeInspectSourceParams.json | 15 + .../v2/WorktreeInspectSourceResponse.json | 35 + .../schema/json/v2/WorktreeListParams.json | 15 + .../schema/json/v2/WorktreeListResponse.json | 133 +++ .../schema/json/v2/WorktreeRemoveParams.json | 27 + .../json/v2/WorktreeRemoveResponse.json | 20 + .../schema/typescript/ClientRequest.ts | 6 +- .../typescript/v2/WorktreeCreateParams.ts | 13 + .../typescript/v2/WorktreeCreateResponse.ts | 10 + .../typescript/v2/WorktreeDirtyPolicy.ts | 5 + .../typescript/v2/WorktreeDirtyState.ts | 5 + .../schema/typescript/v2/WorktreeInfo.ts | 11 + .../v2/WorktreeInspectSourceParams.ts | 12 + .../v2/WorktreeInspectSourceResponse.ts | 9 + .../typescript/v2/WorktreeListParams.ts | 12 + .../typescript/v2/WorktreeListResponse.ts | 9 + .../schema/typescript/v2/WorktreeLocation.ts | 5 + .../typescript/v2/WorktreeRemoveParams.ts | 12 + .../typescript/v2/WorktreeRemoveResponse.ts | 8 + .../schema/typescript/v2/WorktreeSource.ts | 5 + .../schema/typescript/v2/WorktreeWarning.ts | 5 + .../schema/typescript/v2/index.ts | 14 + .../src/protocol/common.rs | 20 + .../src/protocol/v2/mod.rs | 2 + .../src/protocol/v2/worktree.rs | 158 +++ codex-rs/app-server/Cargo.toml | 1 + codex-rs/app-server/README.md | 7 + codex-rs/app-server/src/message_processor.rs | 26 +- codex-rs/app-server/src/request_processors.rs | 16 + .../request_processors/thread_processor.rs | 34 + .../request_processors/worktree_processor.rs | 201 ++++ codex-rs/cli/src/main.rs | 29 - codex-rs/tui/src/app/event_dispatch.rs | 4 - codex-rs/tui/src/app/worktree.rs | 286 +++-- codex-rs/tui/src/app_event.rs | 6 - codex-rs/tui/src/app_server_session.rs | 18 - codex-rs/tui/src/lib.rs | 93 +- codex-rs/tui/src/remote_worktree.rs | 1042 ----------------- 44 files changed, 2279 insertions(+), 1226 deletions(-) create mode 100644 codex-rs/app-server-protocol/schema/json/v2/WorktreeCreateParams.json create mode 100644 codex-rs/app-server-protocol/schema/json/v2/WorktreeCreateResponse.json create mode 100644 codex-rs/app-server-protocol/schema/json/v2/WorktreeInspectSourceParams.json create mode 100644 codex-rs/app-server-protocol/schema/json/v2/WorktreeInspectSourceResponse.json create mode 100644 codex-rs/app-server-protocol/schema/json/v2/WorktreeListParams.json create mode 100644 codex-rs/app-server-protocol/schema/json/v2/WorktreeListResponse.json create mode 100644 codex-rs/app-server-protocol/schema/json/v2/WorktreeRemoveParams.json create mode 100644 codex-rs/app-server-protocol/schema/json/v2/WorktreeRemoveResponse.json create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeCreateParams.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeCreateResponse.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeDirtyPolicy.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeDirtyState.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInfo.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInspectSourceParams.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInspectSourceResponse.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListParams.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListResponse.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeLocation.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeRemoveParams.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeRemoveResponse.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeSource.ts create mode 100644 codex-rs/app-server-protocol/schema/typescript/v2/WorktreeWarning.ts create mode 100644 codex-rs/app-server-protocol/src/protocol/v2/worktree.rs create mode 100644 codex-rs/app-server/src/request_processors/worktree_processor.rs delete mode 100644 codex-rs/tui/src/remote_worktree.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index d914890f55..8c2fa5141c 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -1896,6 +1896,7 @@ dependencies = [ "codex-utils-cli", "codex-utils-json-to-toml", "codex-utils-pty", + "codex-worktree", "core_test_support", "flate2", "futures", diff --git a/codex-rs/app-server-protocol/schema/json/ClientRequest.json b/codex-rs/app-server-protocol/schema/json/ClientRequest.json index 36596807ba..6a49d3129c 100644 --- a/codex-rs/app-server-protocol/schema/json/ClientRequest.json +++ b/codex-rs/app-server-protocol/schema/json/ClientRequest.json @@ -4564,6 +4564,97 @@ "mode" ], "type": "object" + }, + "WorktreeCreateParams": { + "description": "Create or reuse a managed worktree from the repository containing \\`cwd\\`.", + "properties": { + "baseRef": { + "type": [ + "string", + "null" + ] + }, + "branch": { + "type": "string" + }, + "cwd": { + "description": "Repository-relative workspace cwd to use as the source checkout.", + "type": [ + "string", + "null" + ] + }, + "dirtyPolicy": { + "$ref": "#/definitions/WorktreeDirtyPolicy" + } + }, + "required": [ + "branch", + "dirtyPolicy" + ], + "type": "object" + }, + "WorktreeDirtyPolicy": { + "enum": [ + "fail", + "ignore", + "copyTracked", + "copyAll", + "moveTracked", + "moveAll" + ], + "type": "string" + }, + "WorktreeInspectSourceParams": { + "description": "Inspect dirty state for the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "WorktreeListParams": { + "description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", + "type": [ + "string", + "null" + ] + } + }, + "type": "object" + }, + "WorktreeRemoveParams": { + "description": "Remove a managed worktree in the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to use when resolving \\`name_or_path\\`.", + "type": [ + "string", + "null" + ] + }, + "deleteBranch": { + "type": "boolean" + }, + "force": { + "type": "boolean" + }, + "nameOrPath": { + "type": "string" + } + }, + "required": [ + "nameOrPath" + ], + "type": "object" } }, "description": "Request from the client to the server.", @@ -5578,6 +5669,102 @@ "title": "Fs/unwatchRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "worktree/list" + ], + "title": "Worktree/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WorktreeListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "worktree/inspectSource" + ], + "title": "Worktree/inspectSourceRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WorktreeInspectSourceParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/inspectSourceRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "worktree/create" + ], + "title": "Worktree/createRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WorktreeCreateParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/createRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "worktree/remove" + ], + "title": "Worktree/removeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WorktreeRemoveParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/removeRequest", + "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 acb4b16d93..b113e717e7 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 @@ -1194,6 +1194,102 @@ "title": "Fs/unwatchRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "worktree/list" + ], + "title": "Worktree/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/WorktreeListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "worktree/inspectSource" + ], + "title": "Worktree/inspectSourceRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/WorktreeInspectSourceParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/inspectSourceRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "worktree/create" + ], + "title": "Worktree/createRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/WorktreeCreateParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/createRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/v2/RequestId" + }, + "method": { + "enum": [ + "worktree/remove" + ], + "title": "Worktree/removeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/v2/WorktreeRemoveParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/removeRequest", + "type": "object" + }, { "properties": { "id": { @@ -18653,6 +18749,306 @@ "title": "WindowsWorldWritableWarningNotification", "type": "object" }, + "WorktreeCreateParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Create or reuse a managed worktree from the repository containing \\`cwd\\`.", + "properties": { + "baseRef": { + "type": [ + "string", + "null" + ] + }, + "branch": { + "type": "string" + }, + "cwd": { + "description": "Repository-relative workspace cwd to use as the source checkout.", + "type": [ + "string", + "null" + ] + }, + "dirtyPolicy": { + "$ref": "#/definitions/v2/WorktreeDirtyPolicy" + } + }, + "required": [ + "branch", + "dirtyPolicy" + ], + "title": "WorktreeCreateParams", + "type": "object" + }, + "WorktreeCreateResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Result returned by \\`worktree/create\\`.", + "properties": { + "info": { + "$ref": "#/definitions/v2/WorktreeInfo" + }, + "reused": { + "type": "boolean" + }, + "warnings": { + "items": { + "$ref": "#/definitions/v2/WorktreeWarning" + }, + "type": "array" + } + }, + "required": [ + "info", + "reused", + "warnings" + ], + "title": "WorktreeCreateResponse", + "type": "object" + }, + "WorktreeDirtyPolicy": { + "enum": [ + "fail", + "ignore", + "copyTracked", + "copyAll", + "moveTracked", + "moveAll" + ], + "type": "string" + }, + "WorktreeDirtyState": { + "properties": { + "hasStagedChanges": { + "type": "boolean" + }, + "hasUnstagedChanges": { + "type": "boolean" + }, + "hasUntrackedFiles": { + "type": "boolean" + } + }, + "required": [ + "hasStagedChanges", + "hasUnstagedChanges", + "hasUntrackedFiles" + ], + "type": "object" + }, + "WorktreeInfo": { + "description": "Server-native representation of a managed worktree.", + "properties": { + "branch": { + "type": [ + "string", + "null" + ] + }, + "commonGitDir": { + "type": "string" + }, + "dirty": { + "$ref": "#/definitions/v2/WorktreeDirtyState" + }, + "head": { + "type": [ + "string", + "null" + ] + }, + "id": { + "type": "string" + }, + "location": { + "$ref": "#/definitions/v2/WorktreeLocation" + }, + "metadataPath": { + "type": "string" + }, + "name": { + "type": "string" + }, + "originalRelativeCwd": { + "type": "string" + }, + "ownerThreadId": { + "type": [ + "string", + "null" + ] + }, + "repoName": { + "type": "string" + }, + "repoRoot": { + "type": "string" + }, + "slug": { + "type": "string" + }, + "source": { + "$ref": "#/definitions/v2/WorktreeSource" + }, + "workspaceCwd": { + "type": "string" + }, + "worktreeGitRoot": { + "type": "string" + } + }, + "required": [ + "commonGitDir", + "dirty", + "id", + "location", + "metadataPath", + "name", + "originalRelativeCwd", + "repoName", + "repoRoot", + "slug", + "source", + "workspaceCwd", + "worktreeGitRoot" + ], + "type": "object" + }, + "WorktreeInspectSourceParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Inspect dirty state for the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", + "type": [ + "string", + "null" + ] + } + }, + "title": "WorktreeInspectSourceParams", + "type": "object" + }, + "WorktreeInspectSourceResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Dirty-state response returned by \\`worktree/inspectSource\\`.", + "properties": { + "dirty": { + "$ref": "#/definitions/v2/WorktreeDirtyState" + } + }, + "required": [ + "dirty" + ], + "title": "WorktreeInspectSourceResponse", + "type": "object" + }, + "WorktreeListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", + "type": [ + "string", + "null" + ] + } + }, + "title": "WorktreeListParams", + "type": "object" + }, + "WorktreeListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Managed worktrees returned by \\`worktree/list\\`.", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/v2/WorktreeInfo" + }, + "type": "array" + } + }, + "required": [ + "data" + ], + "title": "WorktreeListResponse", + "type": "object" + }, + "WorktreeLocation": { + "enum": [ + "sibling", + "codexHome", + "external" + ], + "type": "string" + }, + "WorktreeRemoveParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Remove a managed worktree in the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to use when resolving \\`name_or_path\\`.", + "type": [ + "string", + "null" + ] + }, + "deleteBranch": { + "type": "boolean" + }, + "force": { + "type": "boolean" + }, + "nameOrPath": { + "type": "string" + } + }, + "required": [ + "nameOrPath" + ], + "title": "WorktreeRemoveParams", + "type": "object" + }, + "WorktreeRemoveResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Result returned by \\`worktree/remove\\`.", + "properties": { + "deletedBranch": { + "type": [ + "string", + "null" + ] + }, + "removedPath": { + "type": "string" + } + }, + "required": [ + "removedPath" + ], + "title": "WorktreeRemoveResponse", + "type": "object" + }, + "WorktreeSource": { + "enum": [ + "cli", + "app", + "legacy", + "git" + ], + "type": "string" + }, + "WorktreeWarning": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, "WriteStatus": { "enum": [ "ok", 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 ded3dc2b87..84fe8f04f8 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 @@ -1953,6 +1953,102 @@ "title": "Fs/unwatchRequest", "type": "object" }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "worktree/list" + ], + "title": "Worktree/listRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WorktreeListParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/listRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "worktree/inspectSource" + ], + "title": "Worktree/inspectSourceRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WorktreeInspectSourceParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/inspectSourceRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "worktree/create" + ], + "title": "Worktree/createRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WorktreeCreateParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/createRequest", + "type": "object" + }, + { + "properties": { + "id": { + "$ref": "#/definitions/RequestId" + }, + "method": { + "enum": [ + "worktree/remove" + ], + "title": "Worktree/removeRequestMethod", + "type": "string" + }, + "params": { + "$ref": "#/definitions/WorktreeRemoveParams" + } + }, + "required": [ + "id", + "method", + "params" + ], + "title": "Worktree/removeRequest", + "type": "object" + }, { "properties": { "id": { @@ -16539,6 +16635,306 @@ "title": "WindowsWorldWritableWarningNotification", "type": "object" }, + "WorktreeCreateParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Create or reuse a managed worktree from the repository containing \\`cwd\\`.", + "properties": { + "baseRef": { + "type": [ + "string", + "null" + ] + }, + "branch": { + "type": "string" + }, + "cwd": { + "description": "Repository-relative workspace cwd to use as the source checkout.", + "type": [ + "string", + "null" + ] + }, + "dirtyPolicy": { + "$ref": "#/definitions/WorktreeDirtyPolicy" + } + }, + "required": [ + "branch", + "dirtyPolicy" + ], + "title": "WorktreeCreateParams", + "type": "object" + }, + "WorktreeCreateResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Result returned by \\`worktree/create\\`.", + "properties": { + "info": { + "$ref": "#/definitions/WorktreeInfo" + }, + "reused": { + "type": "boolean" + }, + "warnings": { + "items": { + "$ref": "#/definitions/WorktreeWarning" + }, + "type": "array" + } + }, + "required": [ + "info", + "reused", + "warnings" + ], + "title": "WorktreeCreateResponse", + "type": "object" + }, + "WorktreeDirtyPolicy": { + "enum": [ + "fail", + "ignore", + "copyTracked", + "copyAll", + "moveTracked", + "moveAll" + ], + "type": "string" + }, + "WorktreeDirtyState": { + "properties": { + "hasStagedChanges": { + "type": "boolean" + }, + "hasUnstagedChanges": { + "type": "boolean" + }, + "hasUntrackedFiles": { + "type": "boolean" + } + }, + "required": [ + "hasStagedChanges", + "hasUnstagedChanges", + "hasUntrackedFiles" + ], + "type": "object" + }, + "WorktreeInfo": { + "description": "Server-native representation of a managed worktree.", + "properties": { + "branch": { + "type": [ + "string", + "null" + ] + }, + "commonGitDir": { + "type": "string" + }, + "dirty": { + "$ref": "#/definitions/WorktreeDirtyState" + }, + "head": { + "type": [ + "string", + "null" + ] + }, + "id": { + "type": "string" + }, + "location": { + "$ref": "#/definitions/WorktreeLocation" + }, + "metadataPath": { + "type": "string" + }, + "name": { + "type": "string" + }, + "originalRelativeCwd": { + "type": "string" + }, + "ownerThreadId": { + "type": [ + "string", + "null" + ] + }, + "repoName": { + "type": "string" + }, + "repoRoot": { + "type": "string" + }, + "slug": { + "type": "string" + }, + "source": { + "$ref": "#/definitions/WorktreeSource" + }, + "workspaceCwd": { + "type": "string" + }, + "worktreeGitRoot": { + "type": "string" + } + }, + "required": [ + "commonGitDir", + "dirty", + "id", + "location", + "metadataPath", + "name", + "originalRelativeCwd", + "repoName", + "repoRoot", + "slug", + "source", + "workspaceCwd", + "worktreeGitRoot" + ], + "type": "object" + }, + "WorktreeInspectSourceParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Inspect dirty state for the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", + "type": [ + "string", + "null" + ] + } + }, + "title": "WorktreeInspectSourceParams", + "type": "object" + }, + "WorktreeInspectSourceResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Dirty-state response returned by \\`worktree/inspectSource\\`.", + "properties": { + "dirty": { + "$ref": "#/definitions/WorktreeDirtyState" + } + }, + "required": [ + "dirty" + ], + "title": "WorktreeInspectSourceResponse", + "type": "object" + }, + "WorktreeListParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", + "type": [ + "string", + "null" + ] + } + }, + "title": "WorktreeListParams", + "type": "object" + }, + "WorktreeListResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Managed worktrees returned by \\`worktree/list\\`.", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/WorktreeInfo" + }, + "type": "array" + } + }, + "required": [ + "data" + ], + "title": "WorktreeListResponse", + "type": "object" + }, + "WorktreeLocation": { + "enum": [ + "sibling", + "codexHome", + "external" + ], + "type": "string" + }, + "WorktreeRemoveParams": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Remove a managed worktree in the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to use when resolving \\`name_or_path\\`.", + "type": [ + "string", + "null" + ] + }, + "deleteBranch": { + "type": "boolean" + }, + "force": { + "type": "boolean" + }, + "nameOrPath": { + "type": "string" + } + }, + "required": [ + "nameOrPath" + ], + "title": "WorktreeRemoveParams", + "type": "object" + }, + "WorktreeRemoveResponse": { + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Result returned by \\`worktree/remove\\`.", + "properties": { + "deletedBranch": { + "type": [ + "string", + "null" + ] + }, + "removedPath": { + "type": "string" + } + }, + "required": [ + "removedPath" + ], + "title": "WorktreeRemoveResponse", + "type": "object" + }, + "WorktreeSource": { + "enum": [ + "cli", + "app", + "legacy", + "git" + ], + "type": "string" + }, + "WorktreeWarning": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + }, "WriteStatus": { "enum": [ "ok", diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreeCreateParams.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreeCreateParams.json new file mode 100644 index 0000000000..2dd71ba61b --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreeCreateParams.json @@ -0,0 +1,44 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "WorktreeDirtyPolicy": { + "enum": [ + "fail", + "ignore", + "copyTracked", + "copyAll", + "moveTracked", + "moveAll" + ], + "type": "string" + } + }, + "description": "Create or reuse a managed worktree from the repository containing \\`cwd\\`.", + "properties": { + "baseRef": { + "type": [ + "string", + "null" + ] + }, + "branch": { + "type": "string" + }, + "cwd": { + "description": "Repository-relative workspace cwd to use as the source checkout.", + "type": [ + "string", + "null" + ] + }, + "dirtyPolicy": { + "$ref": "#/definitions/WorktreeDirtyPolicy" + } + }, + "required": [ + "branch", + "dirtyPolicy" + ], + "title": "WorktreeCreateParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreeCreateResponse.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreeCreateResponse.json new file mode 100644 index 0000000000..dc04b8b8bd --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreeCreateResponse.json @@ -0,0 +1,152 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "WorktreeDirtyState": { + "properties": { + "hasStagedChanges": { + "type": "boolean" + }, + "hasUnstagedChanges": { + "type": "boolean" + }, + "hasUntrackedFiles": { + "type": "boolean" + } + }, + "required": [ + "hasStagedChanges", + "hasUnstagedChanges", + "hasUntrackedFiles" + ], + "type": "object" + }, + "WorktreeInfo": { + "description": "Server-native representation of a managed worktree.", + "properties": { + "branch": { + "type": [ + "string", + "null" + ] + }, + "commonGitDir": { + "type": "string" + }, + "dirty": { + "$ref": "#/definitions/WorktreeDirtyState" + }, + "head": { + "type": [ + "string", + "null" + ] + }, + "id": { + "type": "string" + }, + "location": { + "$ref": "#/definitions/WorktreeLocation" + }, + "metadataPath": { + "type": "string" + }, + "name": { + "type": "string" + }, + "originalRelativeCwd": { + "type": "string" + }, + "ownerThreadId": { + "type": [ + "string", + "null" + ] + }, + "repoName": { + "type": "string" + }, + "repoRoot": { + "type": "string" + }, + "slug": { + "type": "string" + }, + "source": { + "$ref": "#/definitions/WorktreeSource" + }, + "workspaceCwd": { + "type": "string" + }, + "worktreeGitRoot": { + "type": "string" + } + }, + "required": [ + "commonGitDir", + "dirty", + "id", + "location", + "metadataPath", + "name", + "originalRelativeCwd", + "repoName", + "repoRoot", + "slug", + "source", + "workspaceCwd", + "worktreeGitRoot" + ], + "type": "object" + }, + "WorktreeLocation": { + "enum": [ + "sibling", + "codexHome", + "external" + ], + "type": "string" + }, + "WorktreeSource": { + "enum": [ + "cli", + "app", + "legacy", + "git" + ], + "type": "string" + }, + "WorktreeWarning": { + "properties": { + "message": { + "type": "string" + } + }, + "required": [ + "message" + ], + "type": "object" + } + }, + "description": "Result returned by \\`worktree/create\\`.", + "properties": { + "info": { + "$ref": "#/definitions/WorktreeInfo" + }, + "reused": { + "type": "boolean" + }, + "warnings": { + "items": { + "$ref": "#/definitions/WorktreeWarning" + }, + "type": "array" + } + }, + "required": [ + "info", + "reused", + "warnings" + ], + "title": "WorktreeCreateResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreeInspectSourceParams.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreeInspectSourceParams.json new file mode 100644 index 0000000000..11c4110a68 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreeInspectSourceParams.json @@ -0,0 +1,15 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Inspect dirty state for the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", + "type": [ + "string", + "null" + ] + } + }, + "title": "WorktreeInspectSourceParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreeInspectSourceResponse.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreeInspectSourceResponse.json new file mode 100644 index 0000000000..c3674323da --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreeInspectSourceResponse.json @@ -0,0 +1,35 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "WorktreeDirtyState": { + "properties": { + "hasStagedChanges": { + "type": "boolean" + }, + "hasUnstagedChanges": { + "type": "boolean" + }, + "hasUntrackedFiles": { + "type": "boolean" + } + }, + "required": [ + "hasStagedChanges", + "hasUnstagedChanges", + "hasUntrackedFiles" + ], + "type": "object" + } + }, + "description": "Dirty-state response returned by \\`worktree/inspectSource\\`.", + "properties": { + "dirty": { + "$ref": "#/definitions/WorktreeDirtyState" + } + }, + "required": [ + "dirty" + ], + "title": "WorktreeInspectSourceResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreeListParams.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreeListParams.json new file mode 100644 index 0000000000..50943d6908 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreeListParams.json @@ -0,0 +1,15 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.", + "type": [ + "string", + "null" + ] + } + }, + "title": "WorktreeListParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreeListResponse.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreeListResponse.json new file mode 100644 index 0000000000..5bf4f053db --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreeListResponse.json @@ -0,0 +1,133 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "WorktreeDirtyState": { + "properties": { + "hasStagedChanges": { + "type": "boolean" + }, + "hasUnstagedChanges": { + "type": "boolean" + }, + "hasUntrackedFiles": { + "type": "boolean" + } + }, + "required": [ + "hasStagedChanges", + "hasUnstagedChanges", + "hasUntrackedFiles" + ], + "type": "object" + }, + "WorktreeInfo": { + "description": "Server-native representation of a managed worktree.", + "properties": { + "branch": { + "type": [ + "string", + "null" + ] + }, + "commonGitDir": { + "type": "string" + }, + "dirty": { + "$ref": "#/definitions/WorktreeDirtyState" + }, + "head": { + "type": [ + "string", + "null" + ] + }, + "id": { + "type": "string" + }, + "location": { + "$ref": "#/definitions/WorktreeLocation" + }, + "metadataPath": { + "type": "string" + }, + "name": { + "type": "string" + }, + "originalRelativeCwd": { + "type": "string" + }, + "ownerThreadId": { + "type": [ + "string", + "null" + ] + }, + "repoName": { + "type": "string" + }, + "repoRoot": { + "type": "string" + }, + "slug": { + "type": "string" + }, + "source": { + "$ref": "#/definitions/WorktreeSource" + }, + "workspaceCwd": { + "type": "string" + }, + "worktreeGitRoot": { + "type": "string" + } + }, + "required": [ + "commonGitDir", + "dirty", + "id", + "location", + "metadataPath", + "name", + "originalRelativeCwd", + "repoName", + "repoRoot", + "slug", + "source", + "workspaceCwd", + "worktreeGitRoot" + ], + "type": "object" + }, + "WorktreeLocation": { + "enum": [ + "sibling", + "codexHome", + "external" + ], + "type": "string" + }, + "WorktreeSource": { + "enum": [ + "cli", + "app", + "legacy", + "git" + ], + "type": "string" + } + }, + "description": "Managed worktrees returned by \\`worktree/list\\`.", + "properties": { + "data": { + "items": { + "$ref": "#/definitions/WorktreeInfo" + }, + "type": "array" + } + }, + "required": [ + "data" + ], + "title": "WorktreeListResponse", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreeRemoveParams.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreeRemoveParams.json new file mode 100644 index 0000000000..3bb43971b9 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreeRemoveParams.json @@ -0,0 +1,27 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Remove a managed worktree in the repository containing \\`cwd\\`.", + "properties": { + "cwd": { + "description": "Repository-relative workspace cwd to use when resolving \\`name_or_path\\`.", + "type": [ + "string", + "null" + ] + }, + "deleteBranch": { + "type": "boolean" + }, + "force": { + "type": "boolean" + }, + "nameOrPath": { + "type": "string" + } + }, + "required": [ + "nameOrPath" + ], + "title": "WorktreeRemoveParams", + "type": "object" +} \ No newline at end of file diff --git a/codex-rs/app-server-protocol/schema/json/v2/WorktreeRemoveResponse.json b/codex-rs/app-server-protocol/schema/json/v2/WorktreeRemoveResponse.json new file mode 100644 index 0000000000..a71fd4c127 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/json/v2/WorktreeRemoveResponse.json @@ -0,0 +1,20 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "description": "Result returned by \\`worktree/remove\\`.", + "properties": { + "deletedBranch": { + "type": [ + "string", + "null" + ] + }, + "removedPath": { + "type": "string" + } + }, + "required": [ + "removedPath" + ], + "title": "WorktreeRemoveResponse", + "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 1c03d2eb37..9f0030d994 100644 --- a/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts +++ b/codex-rs/app-server-protocol/schema/typescript/ClientRequest.ts @@ -78,8 +78,12 @@ import type { TurnInterruptParams } from "./v2/TurnInterruptParams"; import type { TurnStartParams } from "./v2/TurnStartParams"; import type { TurnSteerParams } from "./v2/TurnSteerParams"; import type { WindowsSandboxSetupStartParams } from "./v2/WindowsSandboxSetupStartParams"; +import type { WorktreeCreateParams } from "./v2/WorktreeCreateParams"; +import type { WorktreeInspectSourceParams } from "./v2/WorktreeInspectSourceParams"; +import type { WorktreeListParams } from "./v2/WorktreeListParams"; +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": "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": "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/WorktreeCreateParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeCreateParams.ts new file mode 100644 index 0000000000..3174e1ba89 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeCreateParams.ts @@ -0,0 +1,13 @@ +// 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. +import type { WorktreeDirtyPolicy } from "./WorktreeDirtyPolicy"; + +/** + * Create or reuse a managed worktree from the repository containing \`cwd\`. + */ +export type WorktreeCreateParams = { +/** + * Repository-relative workspace cwd to use as the source checkout. + */ +cwd?: string | null, branch: string, baseRef?: string | null, dirtyPolicy: WorktreeDirtyPolicy, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeCreateResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeCreateResponse.ts new file mode 100644 index 0000000000..f358901525 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeCreateResponse.ts @@ -0,0 +1,10 @@ +// 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. +import type { WorktreeInfo } from "./WorktreeInfo"; +import type { WorktreeWarning } from "./WorktreeWarning"; + +/** + * Result returned by \`worktree/create\`. + */ +export type WorktreeCreateResponse = { reused: boolean, info: WorktreeInfo, warnings: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeDirtyPolicy.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeDirtyPolicy.ts new file mode 100644 index 0000000000..8f3287fbec --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeDirtyPolicy.ts @@ -0,0 +1,5 @@ +// 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. + +export type WorktreeDirtyPolicy = "fail" | "ignore" | "copyTracked" | "copyAll" | "moveTracked" | "moveAll"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeDirtyState.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeDirtyState.ts new file mode 100644 index 0000000000..0f790dbb9c --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeDirtyState.ts @@ -0,0 +1,5 @@ +// 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. + +export type WorktreeDirtyState = { hasStagedChanges: boolean, hasUnstagedChanges: boolean, hasUntrackedFiles: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInfo.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInfo.ts new file mode 100644 index 0000000000..4d25ca727f --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInfo.ts @@ -0,0 +1,11 @@ +// 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. +import type { WorktreeDirtyState } from "./WorktreeDirtyState"; +import type { WorktreeLocation } from "./WorktreeLocation"; +import type { WorktreeSource } from "./WorktreeSource"; + +/** + * Server-native representation of a managed worktree. + */ +export type WorktreeInfo = { id: string, name: string, slug: string, source: WorktreeSource, location: WorktreeLocation, repoName: string, repoRoot: string, commonGitDir: string, worktreeGitRoot: string, workspaceCwd: string, originalRelativeCwd: string, branch: string | null, head: string | null, ownerThreadId: string | null, metadataPath: string, dirty: WorktreeDirtyState, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInspectSourceParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInspectSourceParams.ts new file mode 100644 index 0000000000..88527cc36b --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInspectSourceParams.ts @@ -0,0 +1,12 @@ +// 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. + +/** + * Inspect dirty state for the repository containing \`cwd\`. + */ +export type WorktreeInspectSourceParams = { +/** + * Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd. + */ +cwd?: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInspectSourceResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInspectSourceResponse.ts new file mode 100644 index 0000000000..eb09c216f4 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeInspectSourceResponse.ts @@ -0,0 +1,9 @@ +// 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. +import type { WorktreeDirtyState } from "./WorktreeDirtyState"; + +/** + * Dirty-state response returned by \`worktree/inspectSource\`. + */ +export type WorktreeInspectSourceResponse = { dirty: WorktreeDirtyState, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListParams.ts new file mode 100644 index 0000000000..c94e410ad3 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListParams.ts @@ -0,0 +1,12 @@ +// 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. + +/** + * Request the managed worktrees associated with the repository containing \`cwd\`. + */ +export type WorktreeListParams = { +/** + * Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd. + */ +cwd?: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListResponse.ts new file mode 100644 index 0000000000..4d840eab16 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeListResponse.ts @@ -0,0 +1,9 @@ +// 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. +import type { WorktreeInfo } from "./WorktreeInfo"; + +/** + * Managed worktrees returned by \`worktree/list\`. + */ +export type WorktreeListResponse = { data: Array, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeLocation.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeLocation.ts new file mode 100644 index 0000000000..100c8f4223 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeLocation.ts @@ -0,0 +1,5 @@ +// 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. + +export type WorktreeLocation = "sibling" | "codexHome" | "external"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeRemoveParams.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeRemoveParams.ts new file mode 100644 index 0000000000..effd01ea75 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeRemoveParams.ts @@ -0,0 +1,12 @@ +// 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 a managed worktree in the repository containing \`cwd\`. + */ +export type WorktreeRemoveParams = { +/** + * Repository-relative workspace cwd to use when resolving \`name_or_path\`. + */ +cwd?: string | null, nameOrPath: string, force?: boolean, deleteBranch?: boolean, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeRemoveResponse.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeRemoveResponse.ts new file mode 100644 index 0000000000..b339b93218 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeRemoveResponse.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/remove\`. + */ +export type WorktreeRemoveResponse = { removedPath: string, deletedBranch: string | null, }; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeSource.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeSource.ts new file mode 100644 index 0000000000..28907ccedc --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeSource.ts @@ -0,0 +1,5 @@ +// 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. + +export type WorktreeSource = "cli" | "app" | "legacy" | "git"; diff --git a/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeWarning.ts b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeWarning.ts new file mode 100644 index 0000000000..de2481bdf3 --- /dev/null +++ b/codex-rs/app-server-protocol/schema/typescript/v2/WorktreeWarning.ts @@ -0,0 +1,5 @@ +// 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. + +export type WorktreeWarning = { message: string, }; 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 6901e2a040..f894ec2e33 100644 --- a/codex-rs/app-server-protocol/schema/typescript/v2/index.ts +++ b/codex-rs/app-server-protocol/schema/typescript/v2/index.ts @@ -452,4 +452,18 @@ export type { WindowsSandboxSetupMode } from "./WindowsSandboxSetupMode"; export type { WindowsSandboxSetupStartParams } from "./WindowsSandboxSetupStartParams"; export type { WindowsSandboxSetupStartResponse } from "./WindowsSandboxSetupStartResponse"; export type { WindowsWorldWritableWarningNotification } from "./WindowsWorldWritableWarningNotification"; +export type { WorktreeCreateParams } from "./WorktreeCreateParams"; +export type { WorktreeCreateResponse } from "./WorktreeCreateResponse"; +export type { WorktreeDirtyPolicy } from "./WorktreeDirtyPolicy"; +export type { WorktreeDirtyState } from "./WorktreeDirtyState"; +export type { WorktreeInfo } from "./WorktreeInfo"; +export type { WorktreeInspectSourceParams } from "./WorktreeInspectSourceParams"; +export type { WorktreeInspectSourceResponse } from "./WorktreeInspectSourceResponse"; +export type { WorktreeListParams } from "./WorktreeListParams"; +export type { WorktreeListResponse } from "./WorktreeListResponse"; +export type { WorktreeLocation } from "./WorktreeLocation"; +export type { WorktreeRemoveParams } from "./WorktreeRemoveParams"; +export type { WorktreeRemoveResponse } from "./WorktreeRemoveResponse"; +export type { WorktreeSource } from "./WorktreeSource"; +export type { WorktreeWarning } from "./WorktreeWarning"; export type { WriteStatus } from "./WriteStatus"; diff --git a/codex-rs/app-server-protocol/src/protocol/common.rs b/codex-rs/app-server-protocol/src/protocol/common.rs index 682556b976..ae008b496b 100644 --- a/codex-rs/app-server-protocol/src/protocol/common.rs +++ b/codex-rs/app-server-protocol/src/protocol/common.rs @@ -710,6 +710,26 @@ client_request_definitions! { serialization: fs_watch_id(params.watch_id), response: v2::FsUnwatchResponse, }, + WorktreeList => "worktree/list" { + params: v2::WorktreeListParams, + serialization: None, + response: v2::WorktreeListResponse, + }, + WorktreeInspectSource => "worktree/inspectSource" { + params: v2::WorktreeInspectSourceParams, + serialization: None, + response: v2::WorktreeInspectSourceResponse, + }, + WorktreeCreate => "worktree/create" { + params: v2::WorktreeCreateParams, + serialization: global("worktree"), + response: v2::WorktreeCreateResponse, + }, + WorktreeRemove => "worktree/remove" { + params: v2::WorktreeRemoveParams, + serialization: global("worktree"), + response: v2::WorktreeRemoveResponse, + }, SkillsConfigWrite => "skills/config/write" { params: v2::SkillsConfigWriteParams, serialization: global("config"), diff --git a/codex-rs/app-server-protocol/src/protocol/v2/mod.rs b/codex-rs/app-server-protocol/src/protocol/v2/mod.rs index df8a363f82..ad42808bdd 100644 --- a/codex-rs/app-server-protocol/src/protocol/v2/mod.rs +++ b/codex-rs/app-server-protocol/src/protocol/v2/mod.rs @@ -23,6 +23,7 @@ mod thread; mod thread_data; mod turn; mod windows_sandbox; +mod worktree; pub use account::*; pub use apps::*; @@ -48,6 +49,7 @@ pub use thread::*; pub use thread_data::*; pub use turn::*; pub use windows_sandbox::*; +pub use worktree::*; #[cfg(test)] mod tests; diff --git a/codex-rs/app-server-protocol/src/protocol/v2/worktree.rs b/codex-rs/app-server-protocol/src/protocol/v2/worktree.rs new file mode 100644 index 0000000000..35c802255a --- /dev/null +++ b/codex-rs/app-server-protocol/src/protocol/v2/worktree.rs @@ -0,0 +1,158 @@ +use schemars::JsonSchema; +use serde::Deserialize; +use serde::Serialize; +use ts_rs::TS; + +/// Request the managed worktrees associated with the repository containing \`cwd\`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeListParams { + /// Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd. + #[ts(optional = nullable)] + pub cwd: Option, +} + +/// Managed worktrees returned by \`worktree/list\`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeListResponse { + pub data: Vec, +} + +/// Inspect dirty state for the repository containing \`cwd\`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeInspectSourceParams { + /// Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd. + #[ts(optional = nullable)] + pub cwd: Option, +} + +/// Dirty-state response returned by \`worktree/inspectSource\`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeInspectSourceResponse { + pub dirty: WorktreeDirtyState, +} + +/// Create or reuse a managed worktree from the repository containing \`cwd\`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeCreateParams { + /// Repository-relative workspace cwd to use as the source checkout. + #[ts(optional = nullable)] + pub cwd: Option, + pub branch: String, + #[ts(optional = nullable)] + pub base_ref: Option, + pub dirty_policy: WorktreeDirtyPolicy, +} + +/// Result returned by \`worktree/create\`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeCreateResponse { + pub reused: bool, + pub info: WorktreeInfo, + pub warnings: Vec, +} + +/// Remove a managed worktree in the repository containing \`cwd\`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeRemoveParams { + /// Repository-relative workspace cwd to use when resolving \`name_or_path\`. + #[ts(optional = nullable)] + pub cwd: Option, + pub name_or_path: String, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub force: bool, + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub delete_branch: bool, +} + +/// Result returned by \`worktree/remove\`. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeRemoveResponse { + pub removed_path: String, + pub deleted_branch: Option, +} + +/// Server-native representation of a managed worktree. +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeInfo { + pub id: String, + pub name: String, + pub slug: String, + pub source: WorktreeSource, + pub location: WorktreeLocation, + pub repo_name: String, + pub repo_root: String, + pub common_git_dir: String, + pub worktree_git_root: String, + pub workspace_cwd: String, + pub original_relative_cwd: String, + pub branch: Option, + pub head: Option, + pub owner_thread_id: Option, + pub metadata_path: String, + pub dirty: WorktreeDirtyState, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum WorktreeSource { + Cli, + App, + Legacy, + Git, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum WorktreeLocation { + Sibling, + CodexHome, + External, +} + +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub enum WorktreeDirtyPolicy { + Fail, + Ignore, + CopyTracked, + CopyAll, + MoveTracked, + MoveAll, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeDirtyState { + pub has_staged_changes: bool, + pub has_unstaged_changes: bool, + pub has_untracked_files: bool, +} + +#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)] +#[serde(rename_all = "camelCase")] +#[ts(export_to = "v2/")] +pub struct WorktreeWarning { + pub message: String, +} diff --git a/codex-rs/app-server/Cargo.toml b/codex-rs/app-server/Cargo.toml index 6d201bdee3..8416cd0981 100644 --- a/codex-rs/app-server/Cargo.toml +++ b/codex-rs/app-server/Cargo.toml @@ -67,6 +67,7 @@ codex-thread-store = { workspace = true } codex-tools = { workspace = true } codex-utils-absolute-path = { workspace = true } codex-utils-json-to-toml = { workspace = true } +codex-worktree = { workspace = true } chrono = { workspace = true } clap = { workspace = true, features = ["derive"] } futures = { workspace = true } diff --git a/codex-rs/app-server/README.md b/codex-rs/app-server/README.md index ddc3817952..421450c5e7 100644 --- a/codex-rs/app-server/README.md +++ b/codex-rs/app-server/README.md @@ -1150,6 +1150,13 @@ All filesystem paths in this section must be absolute. { "id": 45, "result": {} } ``` +### Worktrees + +- `worktree/list` - list Codex-managed worktrees for the repository containing `cwd`; omitted `cwd` uses the app server's effective cwd. +- `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. + ## Events Event notifications are the server-initiated event stream for thread lifecycles, turn lifecycles, and the items within them. After you start or resume a thread, keep reading stdout for `thread/started`, `thread/archived`, `thread/unarchived`, `thread/closed`, `turn/*`, and `item/*` notifications. diff --git a/codex-rs/app-server/src/message_processor.rs b/codex-rs/app-server/src/message_processor.rs index a3c3877fdc..208983d651 100644 --- a/codex-rs/app-server/src/message_processor.rs +++ b/codex-rs/app-server/src/message_processor.rs @@ -32,6 +32,7 @@ use crate::request_processors::ThreadGoalRequestProcessor; use crate::request_processors::ThreadRequestProcessor; use crate::request_processors::TurnRequestProcessor; use crate::request_processors::WindowsSandboxRequestProcessor; +use crate::request_processors::WorktreeRequestProcessor; use crate::request_serialization::QueuedInitializedRequest; use crate::request_serialization::RequestSerializationQueueKey; use crate::request_serialization::RequestSerializationQueues; @@ -175,6 +176,7 @@ pub(crate) struct MessageProcessor { thread_processor: ThreadRequestProcessor, turn_processor: TurnRequestProcessor, windows_sandbox_processor: WindowsSandboxRequestProcessor, + worktree_processor: WorktreeRequestProcessor, request_serialization_queues: RequestSerializationQueues, } @@ -456,8 +458,9 @@ impl MessageProcessor { let windows_sandbox_processor = WindowsSandboxRequestProcessor::new( outgoing.clone(), Arc::clone(&config), - config_manager, + config_manager.clone(), ); + let worktree_processor = WorktreeRequestProcessor::new(config_manager); Self { outgoing, @@ -481,6 +484,7 @@ impl MessageProcessor { thread_processor, turn_processor, windows_sandbox_processor, + worktree_processor, request_serialization_queues: RequestSerializationQueues::default(), } } @@ -937,6 +941,26 @@ impl MessageProcessor { .unwatch(connection_id, params) .await .map(|response| Some(response.into())), + ClientRequest::WorktreeList { params, .. } => self + .worktree_processor + .list(params) + .await + .map(|response| Some(response.into())), + ClientRequest::WorktreeInspectSource { params, .. } => self + .worktree_processor + .inspect_source(params) + .await + .map(|response| Some(response.into())), + ClientRequest::WorktreeCreate { params, .. } => self + .worktree_processor + .create(params) + .await + .map(|response| Some(response.into())), + ClientRequest::WorktreeRemove { params, .. } => self + .worktree_processor + .remove(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 9f419d7006..ad9845192c 100644 --- a/codex-rs/app-server/src/request_processors.rs +++ b/codex-rs/app-server/src/request_processors.rs @@ -241,6 +241,20 @@ use codex_app_server_protocol::WindowsSandboxSetupCompletedNotification; use codex_app_server_protocol::WindowsSandboxSetupMode; use codex_app_server_protocol::WindowsSandboxSetupStartParams; use codex_app_server_protocol::WindowsSandboxSetupStartResponse; +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::WorktreeDirtyState as ApiWorktreeDirtyState; +use codex_app_server_protocol::WorktreeInfo as ApiWorktreeInfo; +use codex_app_server_protocol::WorktreeInspectSourceParams; +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::WorktreeRemoveParams; +use codex_app_server_protocol::WorktreeRemoveResponse; +use codex_app_server_protocol::WorktreeSource as ApiWorktreeSource; +use codex_app_server_protocol::WorktreeWarning as ApiWorktreeWarning; use codex_arg0::Arg0DispatchPaths; use codex_backend_client::AddCreditsNudgeCreditType as BackendAddCreditsNudgeCreditType; use codex_backend_client::Client as BackendClient; @@ -446,6 +460,7 @@ mod thread_processor; mod token_usage_replay; mod turn_processor; mod windows_sandbox_processor; +mod worktree_processor; pub(crate) use account_processor::AccountRequestProcessor; pub(crate) use apps_processor::AppsRequestProcessor; @@ -467,6 +482,7 @@ pub(crate) use thread_goal_processor::ThreadGoalRequestProcessor; pub(crate) use thread_processor::ThreadRequestProcessor; pub(crate) use turn_processor::TurnRequestProcessor; pub(crate) use windows_sandbox_processor::WindowsSandboxRequestProcessor; +pub(crate) use worktree_processor::WorktreeRequestProcessor; use crate::error_code::internal_error; use crate::error_code::invalid_request; diff --git a/codex-rs/app-server/src/request_processors/thread_processor.rs b/codex-rs/app-server/src/request_processors/thread_processor.rs index 783e53ccb0..326bb08d75 100644 --- a/codex-rs/app-server/src/request_processors/thread_processor.rs +++ b/codex-rs/app-server/src/request_processors/thread_processor.rs @@ -1044,6 +1044,7 @@ impl ThreadRequestProcessor { .collect() }; let core_dynamic_tool_count = core_dynamic_tools.len(); + let codex_home = config.codex_home.to_path_buf(); let NewThread { thread_id, @@ -1147,6 +1148,11 @@ impl ThreadRequestProcessor { ); let active_permission_profile = thread_response_active_permission_profile(config_snapshot.active_permission_profile); + bind_worktree_thread_best_effort( + codex_home.as_path(), + config_snapshot.cwd.as_path(), + &thread.id, + ); let response = ThreadStartResponse { thread: thread.clone(), @@ -2480,6 +2486,11 @@ impl ThreadRequestProcessor { let active_permission_profile = thread_response_active_permission_profile( config_snapshot.active_permission_profile, ); + bind_worktree_thread_best_effort( + self.config.codex_home.as_path(), + session_configured.cwd.as_path(), + &thread.id, + ); let response = ThreadResumeResponse { thread, @@ -3127,6 +3138,11 @@ impl ThreadRequestProcessor { ); let active_permission_profile = thread_response_active_permission_profile(config_snapshot.active_permission_profile); + bind_worktree_thread_best_effort( + self.config.codex_home.as_path(), + session_configured.cwd.as_path(), + &thread.id, + ); let response = ThreadForkResponse { thread: thread.clone(), @@ -3325,6 +3341,24 @@ impl ThreadRequestProcessor { } } +fn bind_worktree_thread_best_effort( + codex_home: &std::path::Path, + cwd: &std::path::Path, + thread_id: &str, +) { + match codex_worktree::resolve_worktree(codex_home, cwd) { + Ok(Some(_)) => { + if let Err(err) = codex_worktree::bind_thread(cwd, thread_id) { + tracing::warn!(?err, "failed to bind managed worktree to thread"); + } + } + Ok(None) => {} + Err(err) => { + tracing::warn!(?err, "failed to resolve managed worktree metadata"); + } + } +} + fn xcode_26_4_mcp_elicitations_auto_deny( client_name: Option<&str>, client_version: Option<&str>, diff --git a/codex-rs/app-server/src/request_processors/worktree_processor.rs b/codex-rs/app-server/src/request_processors/worktree_processor.rs new file mode 100644 index 0000000000..0e55356691 --- /dev/null +++ b/codex-rs/app-server/src/request_processors/worktree_processor.rs @@ -0,0 +1,201 @@ +use super::*; + +use std::path::PathBuf; + +use codex_worktree::DirtyPolicy; +use codex_worktree::DirtyState; +use codex_worktree::WorktreeInfo; +use codex_worktree::WorktreeListQuery; +use codex_worktree::WorktreeLocation; +use codex_worktree::WorktreeRemoveRequest; +use codex_worktree::WorktreeRequest; +use codex_worktree::WorktreeSource; +use codex_worktree::WorktreeWarning; + +#[derive(Clone)] +pub(crate) struct WorktreeRequestProcessor { + config_manager: ConfigManager, +} + +impl WorktreeRequestProcessor { + pub(crate) fn new(config_manager: ConfigManager) -> Self { + Self { config_manager } + } + + pub(crate) async fn list( + &self, + params: WorktreeListParams, + ) -> Result { + let cwd = 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, + }) + .map_err(map_worktree_error)? + .into_iter() + .map(api_worktree_info) + .collect(); + Ok(WorktreeListResponse { data }) + } + + pub(crate) async fn inspect_source( + &self, + params: WorktreeInspectSourceParams, + ) -> Result { + let cwd = self.resolve_cwd(params.cwd).await?; + let dirty = api_dirty_state(codex_worktree::dirty_state(&cwd).map_err(map_worktree_error)?); + Ok(WorktreeInspectSourceResponse { dirty }) + } + + pub(crate) async fn create( + &self, + params: WorktreeCreateParams, + ) -> Result { + let cwd = self.resolve_cwd(params.cwd).await?; + let resolution = codex_worktree::ensure_worktree(WorktreeRequest { + codex_home: self.config_manager.codex_home().to_path_buf(), + source_cwd: cwd, + branch: params.branch, + base_ref: params.base_ref, + dirty_policy: dirty_policy_from_api(params.dirty_policy), + }) + .map_err(map_worktree_error)?; + Ok(WorktreeCreateResponse { + reused: resolution.reused, + info: api_worktree_info(resolution.info), + warnings: resolution + .warnings + .into_iter() + .map(api_worktree_warning) + .collect(), + }) + } + + pub(crate) async fn remove( + &self, + params: WorktreeRemoveParams, + ) -> Result { + let cwd = self.resolve_cwd(params.cwd).await?; + let result = codex_worktree::remove_worktree(WorktreeRemoveRequest { + codex_home: self.config_manager.codex_home().to_path_buf(), + source_cwd: Some(cwd), + name_or_path: params.name_or_path, + force: params.force, + delete_branch: params.delete_branch, + }) + .map_err(map_worktree_error)?; + Ok(WorktreeRemoveResponse { + removed_path: result.removed_path.to_string_lossy().to_string(), + deleted_branch: result.deleted_branch, + }) + } + + async fn resolve_cwd(&self, cwd: Option) -> Result { + match cwd { + Some(cwd) => Ok(PathBuf::from(cwd)), + None => self + .config_manager + .load_latest_config(/*fallback_cwd*/ None) + .await + .map(|config| config.cwd.to_path_buf()) + .map_err(|err| internal_error(format!("failed to load worktree cwd: {err}"))), + } + } +} + +fn map_worktree_error(err: anyhow::Error) -> JSONRPCErrorError { + invalid_request(err.to_string()) +} + +fn dirty_policy_from_api(value: ApiWorktreeDirtyPolicy) -> DirtyPolicy { + match value { + ApiWorktreeDirtyPolicy::Fail => DirtyPolicy::Fail, + ApiWorktreeDirtyPolicy::Ignore => DirtyPolicy::Ignore, + ApiWorktreeDirtyPolicy::CopyTracked => DirtyPolicy::CopyTracked, + ApiWorktreeDirtyPolicy::CopyAll => DirtyPolicy::CopyAll, + ApiWorktreeDirtyPolicy::MoveTracked => DirtyPolicy::MoveTracked, + ApiWorktreeDirtyPolicy::MoveAll => DirtyPolicy::MoveAll, + } +} + +fn api_dirty_state(value: DirtyState) -> ApiWorktreeDirtyState { + ApiWorktreeDirtyState { + has_staged_changes: value.has_staged_changes, + has_unstaged_changes: value.has_unstaged_changes, + has_untracked_files: value.has_untracked_files, + } +} + +fn api_worktree_info(value: WorktreeInfo) -> ApiWorktreeInfo { + ApiWorktreeInfo { + id: value.id, + name: value.name, + slug: value.slug, + source: api_worktree_source(value.source), + location: api_worktree_location(value.location), + repo_name: value.repo_name, + repo_root: value.repo_root.to_string_lossy().to_string(), + common_git_dir: value.common_git_dir.to_string_lossy().to_string(), + worktree_git_root: value.worktree_git_root.to_string_lossy().to_string(), + workspace_cwd: value.workspace_cwd.to_string_lossy().to_string(), + original_relative_cwd: value.original_relative_cwd.to_string_lossy().to_string(), + branch: value.branch, + head: value.head, + owner_thread_id: value.owner_thread_id, + metadata_path: value.metadata_path.to_string_lossy().to_string(), + dirty: api_dirty_state(value.dirty), + } +} + +fn api_worktree_source(value: WorktreeSource) -> ApiWorktreeSource { + match value { + WorktreeSource::Cli => ApiWorktreeSource::Cli, + WorktreeSource::App => ApiWorktreeSource::App, + WorktreeSource::Legacy => ApiWorktreeSource::Legacy, + WorktreeSource::Git => ApiWorktreeSource::Git, + } +} + +fn api_worktree_location(value: WorktreeLocation) -> ApiWorktreeLocation { + match value { + WorktreeLocation::Sibling => ApiWorktreeLocation::Sibling, + WorktreeLocation::CodexHome => ApiWorktreeLocation::CodexHome, + WorktreeLocation::External => ApiWorktreeLocation::External, + } +} + +fn api_worktree_warning(value: WorktreeWarning) -> ApiWorktreeWarning { + ApiWorktreeWarning { + message: value.message, + } +} + +#[cfg(test)] +mod tests { + use super::*; + use pretty_assertions::assert_eq; + + #[test] + fn dirty_policy_conversion_preserves_every_variant() { + assert_eq!( + [ + ApiWorktreeDirtyPolicy::Fail, + ApiWorktreeDirtyPolicy::Ignore, + ApiWorktreeDirtyPolicy::CopyTracked, + ApiWorktreeDirtyPolicy::CopyAll, + ApiWorktreeDirtyPolicy::MoveTracked, + ApiWorktreeDirtyPolicy::MoveAll, + ] + .map(dirty_policy_from_api), + [ + DirtyPolicy::Fail, + DirtyPolicy::Ignore, + DirtyPolicy::CopyTracked, + DirtyPolicy::CopyAll, + DirtyPolicy::MoveTracked, + DirtyPolicy::MoveAll, + ] + ); + } +} diff --git a/codex-rs/cli/src/main.rs b/codex-rs/cli/src/main.rs index e4a8f861e4..954f4227a0 100644 --- a/codex-rs/cli/src/main.rs +++ b/codex-rs/cli/src/main.rs @@ -760,14 +760,6 @@ async fn run_debug_app_server_command(cmd: DebugAppServerCommand) -> anyhow::Res } } -fn resolve_worktree_options_for_tui( - cli: &mut TuiCli, - remote: Option<&str>, - remote_auth_token_env: Option<&str>, -) -> anyhow::Result> { - resolve_worktree_options_for_shared_cli(&mut cli.shared, remote, remote_auth_token_env) -} - fn resolve_worktree_options_for_shared_cli( shared: &mut SharedCliOptions, remote: Option<&str>, @@ -1121,11 +1113,6 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { &mut interactive.config_overrides, root_config_overrides.clone(), ); - resolve_worktree_options_for_tui( - &mut interactive, - root_remote.as_deref(), - root_remote_auth_token_env.as_deref(), - )?; let exit_info = run_interactive_tui( interactive, root_remote.clone(), @@ -1299,14 +1286,6 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { include_non_interactive, config_overrides, ); - resolve_worktree_options_for_tui( - &mut interactive, - remote.remote.as_deref().or(root_remote.as_deref()), - remote - .remote_auth_token_env - .as_deref() - .or(root_remote_auth_token_env.as_deref()), - )?; let exit_info = run_interactive_tui( interactive, remote.remote.or(root_remote.clone()), @@ -1333,14 +1312,6 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> { all, config_overrides, ); - resolve_worktree_options_for_tui( - &mut interactive, - remote.remote.as_deref().or(root_remote.as_deref()), - remote - .remote_auth_token_env - .as_deref() - .or(root_remote_auth_token_env.as_deref()), - )?; let exit_info = run_interactive_tui( interactive, remote.remote.or(root_remote.clone()), diff --git a/codex-rs/tui/src/app/event_dispatch.rs b/codex-rs/tui/src/app/event_dispatch.rs index ff3372139f..88f8bea20e 100644 --- a/codex-rs/tui/src/app/event_dispatch.rs +++ b/codex-rs/tui/src/app/event_dispatch.rs @@ -199,10 +199,6 @@ impl App { self.open_worktree_base_ref_prompt(branch); tui.frame_requester().schedule_frame(); } - AppEvent::WorktreesLoaded { cwd, result } => { - self.on_worktrees_loaded(cwd, result); - tui.frame_requester().schedule_frame(); - } AppEvent::CreateWorktreeAndSwitch { branch, base_ref, diff --git a/codex-rs/tui/src/app/worktree.rs b/codex-rs/tui/src/app/worktree.rs index d1b1d8c560..191a359c17 100644 --- a/codex-rs/tui/src/app/worktree.rs +++ b/codex-rs/tui/src/app/worktree.rs @@ -1,17 +1,32 @@ //! App-layer handlers for the worktree TUI flow. -use anyhow::Context; +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::WorktreeDirtyState as ApiWorktreeDirtyState; +use codex_app_server_protocol::WorktreeInfo as ApiWorktreeInfo; +use codex_app_server_protocol::WorktreeInspectSourceParams; +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::WorktreeRemoveParams; +use codex_app_server_protocol::WorktreeRemoveResponse; +use codex_app_server_protocol::WorktreeSource as ApiWorktreeSource; use codex_protocol::ThreadId; use codex_worktree::DirtyPolicy; use codex_worktree::WorktreeInfo; -use codex_worktree::WorktreeListQuery; -use codex_worktree::WorktreeRemoveRequest; +use codex_worktree::WorktreeLocation; use codex_worktree::WorktreeRequest; use codex_worktree::WorktreeResolution; use codex_worktree::WorktreeSource; +use codex_worktree::WorktreeWarning; use std::path::Path; use std::path::PathBuf; use std::time::Duration; +use uuid::Uuid; use super::*; use crate::bottom_pane::custom_prompt_view::CustomPromptView; @@ -50,15 +65,11 @@ impl App { tui.frame_requester(), self.config.animations, )); - if self.remote_app_server_url.is_some() { - let result = self - .list_current_repo_worktrees_remote(app_server) - .await - .map_err(|err| err.to_string()); - self.on_worktrees_loaded(self.session_workspace_cwd(app_server).to_path_buf(), result); - } else { - self.fetch_worktrees_for_picker(); - } + let result = self + .list_current_repo_worktrees_for_session(app_server) + .await + .map_err(|err| err.to_string()); + self.on_worktrees_loaded(self.session_workspace_cwd(app_server).to_path_buf(), result); } pub(super) fn open_worktree_create_prompt(&mut self) { @@ -291,35 +302,12 @@ impl App { return; } - let result = if self.remote_app_server_url.is_some() { - let Some(runner) = self.workspace_command_runner.clone() else { - self.chat_widget.add_error_message( - "Remote worktree removal is unavailable because the workspace command runner is missing." - .to_string(), - ); - return; - }; - crate::remote_worktree::remove_worktree( - &runner, - &app_server.request_handle(), - self.session_workspace_cwd(app_server), - &target, - force, - delete_branch, - ) - .await - } else { - codex_worktree::remove_worktree(WorktreeRemoveRequest { - codex_home: self.config.codex_home.to_path_buf(), - source_cwd: Some(self.session_workspace_cwd(app_server).to_path_buf()), - name_or_path: target.clone(), - force, - delete_branch, - }) - }; + let result = self + .remove_worktree_via_app_server(app_server, target.clone(), force, delete_branch) + .await; match result { Ok(result) => { - let mut message = format!("Removed worktree {}", result.removed_path.display()); + let mut message = format!("Removed worktree {}", result.removed_path); if let Some(branch) = result.deleted_branch { message.push_str(&format!(" and deleted branch {branch}")); } @@ -332,58 +320,40 @@ impl App { } } - fn list_current_repo_worktrees(&self) -> anyhow::Result> { - codex_worktree::list_worktrees(WorktreeListQuery { - codex_home: self.config.codex_home.to_path_buf(), - source_cwd: Some(self.config.cwd.to_path_buf()), - include_all_repos: false, - }) - } - async fn list_current_repo_worktrees_for_session( &self, app_server: &AppServerSession, ) -> anyhow::Result> { - if self.remote_app_server_url.is_some() { - self.list_current_repo_worktrees_remote(app_server).await - } else { - self.list_current_repo_worktrees() - } - } - - async fn list_current_repo_worktrees_remote( - &self, - app_server: &AppServerSession, - ) -> anyhow::Result> { - let runner = self - .workspace_command_runner - .clone() - .context("remote worktree operations require a workspace command runner")?; - crate::remote_worktree::list_current_repo_worktrees( - &runner, - &app_server.request_handle(), - self.session_workspace_cwd(app_server), - ) - .await + let response: WorktreeListResponse = app_server + .request_handle() + .request_typed(ClientRequest::WorktreeList { + request_id: worktree_request_id("worktree-list"), + params: WorktreeListParams { + cwd: Some(self.session_workspace_cwd(app_server).display().to_string()), + }, + }) + .await?; + Ok(response + .data + .into_iter() + .map(worktree_info_from_api) + .collect()) } async fn source_worktree_dirty_state( &self, app_server: &AppServerSession, ) -> anyhow::Result { - if self.remote_app_server_url.is_some() { - let runner = self - .workspace_command_runner - .clone() - .context("remote worktree operations require a workspace command runner")?; - crate::remote_worktree::source_dirty_state( - &runner, - self.session_workspace_cwd(app_server), - ) - .await - } else { - codex_worktree::dirty_state(self.config.cwd.as_path()) - } + let response: WorktreeInspectSourceResponse = app_server + .request_handle() + .request_typed(ClientRequest::WorktreeInspectSource { + request_id: worktree_request_id("worktree-inspect-source"), + params: WorktreeInspectSourceParams { + cwd: Some(self.session_workspace_cwd(app_server).display().to_string()), + }, + }) + .await?; + Ok(dirty_state_from_api(response.dirty)) } fn session_workspace_cwd<'a>(&'a self, app_server: &'a AppServerSession) -> &'a Path { @@ -401,20 +371,6 @@ impl App { } } - fn fetch_worktrees_for_picker(&mut self) { - let query = WorktreeListQuery { - codex_home: self.config.codex_home.to_path_buf(), - source_cwd: Some(self.config.cwd.to_path_buf()), - include_all_repos: false, - }; - let cwd = self.config.cwd.to_path_buf(); - let app_event_tx = self.app_event_tx.clone(); - tokio::task::spawn_blocking(move || { - let result = codex_worktree::list_worktrees(query).map_err(|err| err.to_string()); - app_event_tx.send(AppEvent::WorktreesLoaded { cwd, result }); - }); - } - fn spawn_worktree_create_request( &self, app_server: &AppServerSession, @@ -422,31 +378,24 @@ impl App { ) { let cwd = request.source_cwd.clone(); let app_event_tx = self.app_event_tx.clone(); - if self.remote_app_server_url.is_some() { - let Some(runner) = self.workspace_command_runner.clone() else { - app_event_tx.send(AppEvent::WorktreeCreated { - cwd, - result: Err( - "remote worktree operations require a workspace command runner".to_string(), - ), - }); - return; - }; - let request_handle = app_server.request_handle(); - tokio::spawn(async move { - let result = - crate::remote_worktree::ensure_worktree(&runner, &request_handle, request) - .await - .map_err(|err| err.to_string()); - app_event_tx.send(AppEvent::WorktreeCreated { cwd, result }); - }); - } else { - tokio::task::spawn_blocking(move || { - let result = - codex_worktree::ensure_worktree(request).map_err(|err| err.to_string()); - app_event_tx.send(AppEvent::WorktreeCreated { cwd, result }); - }); - } + let request_handle = app_server.request_handle(); + tokio::spawn(async move { + let result: Result = request_handle + .request_typed(ClientRequest::WorktreeCreate { + request_id: worktree_request_id("worktree-create"), + params: WorktreeCreateParams { + cwd: Some(request.source_cwd.display().to_string()), + branch: request.branch, + base_ref: request.base_ref, + dirty_policy: dirty_policy_to_api(request.dirty_policy), + }, + }) + .await; + let result = result + .map(worktree_resolution_from_api) + .map_err(|err| err.to_string()); + app_event_tx.send(AppEvent::WorktreeCreated { cwd, result }); + }); } async fn switch_to_worktree_info( @@ -680,6 +629,103 @@ impl App { self.file_search .update_search_dir(self.config.cwd.to_path_buf()); } + + async fn remove_worktree_via_app_server( + &self, + app_server: &AppServerSession, + target: String, + force: bool, + delete_branch: bool, + ) -> anyhow::Result { + app_server + .request_handle() + .request_typed(ClientRequest::WorktreeRemove { + request_id: worktree_request_id("worktree-remove"), + params: WorktreeRemoveParams { + cwd: Some(self.session_workspace_cwd(app_server).display().to_string()), + name_or_path: target, + force, + delete_branch, + }, + }) + .await + .map_err(Into::into) + } +} + +fn worktree_request_id(prefix: &str) -> RequestId { + RequestId::String(format!("{prefix}-{}", Uuid::new_v4())) +} + +fn dirty_policy_to_api(value: DirtyPolicy) -> ApiWorktreeDirtyPolicy { + match value { + DirtyPolicy::Fail => ApiWorktreeDirtyPolicy::Fail, + DirtyPolicy::Ignore => ApiWorktreeDirtyPolicy::Ignore, + DirtyPolicy::CopyTracked => ApiWorktreeDirtyPolicy::CopyTracked, + DirtyPolicy::CopyAll => ApiWorktreeDirtyPolicy::CopyAll, + DirtyPolicy::MoveTracked => ApiWorktreeDirtyPolicy::MoveTracked, + DirtyPolicy::MoveAll => ApiWorktreeDirtyPolicy::MoveAll, + } +} + +fn dirty_state_from_api(value: ApiWorktreeDirtyState) -> codex_worktree::DirtyState { + codex_worktree::DirtyState { + has_staged_changes: value.has_staged_changes, + has_unstaged_changes: value.has_unstaged_changes, + has_untracked_files: value.has_untracked_files, + } +} + +fn worktree_info_from_api(value: ApiWorktreeInfo) -> WorktreeInfo { + WorktreeInfo { + id: value.id, + name: value.name, + slug: value.slug, + source: worktree_source_from_api(value.source), + location: worktree_location_from_api(value.location), + repo_name: value.repo_name, + repo_root: PathBuf::from(value.repo_root), + common_git_dir: PathBuf::from(value.common_git_dir), + worktree_git_root: PathBuf::from(value.worktree_git_root), + workspace_cwd: PathBuf::from(value.workspace_cwd), + original_relative_cwd: PathBuf::from(value.original_relative_cwd), + branch: value.branch, + head: value.head, + owner_thread_id: value.owner_thread_id, + metadata_path: PathBuf::from(value.metadata_path), + dirty: dirty_state_from_api(value.dirty), + } +} + +fn worktree_source_from_api(value: ApiWorktreeSource) -> WorktreeSource { + match value { + ApiWorktreeSource::Cli => WorktreeSource::Cli, + ApiWorktreeSource::App => WorktreeSource::App, + ApiWorktreeSource::Legacy => WorktreeSource::Legacy, + ApiWorktreeSource::Git => WorktreeSource::Git, + } +} + +fn worktree_location_from_api(value: ApiWorktreeLocation) -> WorktreeLocation { + match value { + ApiWorktreeLocation::Sibling => WorktreeLocation::Sibling, + ApiWorktreeLocation::CodexHome => WorktreeLocation::CodexHome, + ApiWorktreeLocation::External => WorktreeLocation::External, + } +} + +fn worktree_resolution_from_api(value: WorktreeCreateResponse) -> WorktreeResolution { + WorktreeResolution { + reused: value.reused, + info: worktree_info_from_api(value.info), + warnings: value + .warnings + .into_iter() + .map(|warning| WorktreeWarning { + message: warning.message, + }) + .collect(), + } } fn worktree_session_message( diff --git a/codex-rs/tui/src/app_event.rs b/codex-rs/tui/src/app_event.rs index 8908029204..3e64344c67 100644 --- a/codex-rs/tui/src/app_event.rs +++ b/codex-rs/tui/src/app_event.rs @@ -205,12 +205,6 @@ pub(crate) enum AppEvent { branch: String, }, - /// Result of loading worktrees for the managed worktree picker. - WorktreesLoaded { - cwd: PathBuf, - result: Result, String>, - }, - /// Create or reuse a managed worktree and switch the TUI into it. CreateWorktreeAndSwitch { branch: String, diff --git a/codex-rs/tui/src/app_server_session.rs b/codex-rs/tui/src/app_server_session.rs index 08752630fc..7d417c3e56 100644 --- a/codex-rs/tui/src/app_server_session.rs +++ b/codex-rs/tui/src/app_server_session.rs @@ -117,7 +117,6 @@ use color_eyre::eyre::ContextCompat; use color_eyre::eyre::Result; use color_eyre::eyre::WrapErr; use std::collections::HashMap; -use std::path::Path; use std::path::PathBuf; use uuid::Uuid; @@ -1430,7 +1429,6 @@ async fn thread_session_state_from_thread_start_response( config: &Config, thread_params_mode: ThreadParamsMode, ) -> Result { - bind_worktree_thread_best_effort(config, response.cwd.as_path(), &response.thread.id); let permission_profile = permission_profile_from_thread_response( &response.sandbox, response.permission_profile.as_ref(), @@ -1463,7 +1461,6 @@ async fn thread_session_state_from_thread_resume_response( config: &Config, thread_params_mode: ThreadParamsMode, ) -> Result { - bind_worktree_thread_best_effort(config, response.cwd.as_path(), &response.thread.id); let permission_profile = permission_profile_from_thread_response( &response.sandbox, response.permission_profile.as_ref(), @@ -1496,7 +1493,6 @@ async fn thread_session_state_from_thread_fork_response( config: &Config, thread_params_mode: ThreadParamsMode, ) -> Result { - bind_worktree_thread_best_effort(config, response.cwd.as_path(), &response.thread.id); let permission_profile = permission_profile_from_thread_response( &response.sandbox, response.permission_profile.as_ref(), @@ -1524,20 +1520,6 @@ async fn thread_session_state_from_thread_fork_response( .await } -fn bind_worktree_thread_best_effort(config: &Config, cwd: &Path, thread_id: &str) { - match codex_worktree::resolve_worktree(config.codex_home.as_path(), cwd) { - Ok(Some(_)) => { - if let Err(err) = codex_worktree::bind_thread(cwd, thread_id) { - tracing::warn!(?err, "failed to bind managed worktree to thread"); - } - } - Ok(None) => {} - Err(err) => { - tracing::warn!(?err, "failed to resolve managed worktree metadata"); - } - } -} - fn permission_profile_from_thread_response( sandbox: &codex_app_server_protocol::SandboxPolicy, permission_profile: Option<&codex_app_server_protocol::PermissionProfile>, diff --git a/codex-rs/tui/src/lib.rs b/codex-rs/tui/src/lib.rs index 55b0c4ef1a..38a5820d0a 100644 --- a/codex-rs/tui/src/lib.rs +++ b/codex-rs/tui/src/lib.rs @@ -28,12 +28,17 @@ use codex_app_server_client::RemoteAppServerConnectArgs; use codex_app_server_protocol::Account as AppServerAccount; use codex_app_server_protocol::AskForApproval; use codex_app_server_protocol::AuthMode as AppServerAuthMode; +use codex_app_server_protocol::ClientRequest; use codex_app_server_protocol::ConfigWarningNotification; +use codex_app_server_protocol::RequestId; use codex_app_server_protocol::Thread as AppServerThread; use codex_app_server_protocol::ThreadListCwdFilter; use codex_app_server_protocol::ThreadListParams; use codex_app_server_protocol::ThreadSortKey as AppServerThreadSortKey; use codex_app_server_protocol::ThreadSourceKind; +use codex_app_server_protocol::WorktreeCreateParams; +use codex_app_server_protocol::WorktreeCreateResponse; +use codex_app_server_protocol::WorktreeDirtyPolicy; use codex_cloud_requirements::cloud_requirements_loader_for_storage; use codex_config::CloudRequirementsLoader; use codex_config::ConfigLoadError; @@ -55,6 +60,7 @@ use codex_state::log_db; use codex_terminal_detection::terminal_info; use codex_utils_absolute_path::AbsolutePathBuf; use codex_utils_absolute_path::canonicalize_existing_preserving_symlinks; +use codex_utils_cli::WorktreeDirtyCliArg; use codex_utils_oss::ensure_oss_provider_ready; use codex_utils_oss::get_default_model_for_oss_provider; use color_eyre::eyre::WrapErr; @@ -179,7 +185,6 @@ mod tui; mod ui_consts; pub(crate) mod update_action; pub use update_action::UpdateAction; -mod remote_worktree; mod worktree; mod worktree_labels; #[cfg(not(debug_assertions))] @@ -698,6 +703,39 @@ fn latest_session_cwd_filter<'a>( } } +async fn create_startup_worktree( + app_server: &AppServerSession, + cwd: Option<&Path>, + branch: String, + base_ref: Option, + dirty_policy: WorktreeDirtyCliArg, +) -> color_eyre::Result { + app_server + .request_handle() + .request_typed(ClientRequest::WorktreeCreate { + request_id: RequestId::String(format!("startup-worktree-{}", Uuid::new_v4())), + params: WorktreeCreateParams { + cwd: cwd.map(|cwd| cwd.display().to_string()), + branch, + base_ref, + dirty_policy: worktree_dirty_policy_from_cli(dirty_policy), + }, + }) + .await + .map_err(color_eyre::eyre::Report::msg) +} + +fn worktree_dirty_policy_from_cli(value: WorktreeDirtyCliArg) -> WorktreeDirtyPolicy { + match value { + WorktreeDirtyCliArg::Fail => WorktreeDirtyPolicy::Fail, + WorktreeDirtyCliArg::Ignore => WorktreeDirtyPolicy::Ignore, + WorktreeDirtyCliArg::CopyTracked => WorktreeDirtyPolicy::CopyTracked, + WorktreeDirtyCliArg::CopyAll => WorktreeDirtyPolicy::CopyAll, + WorktreeDirtyCliArg::MoveTracked => WorktreeDirtyPolicy::MoveTracked, + WorktreeDirtyCliArg::MoveAll => WorktreeDirtyPolicy::MoveAll, + } +} + pub async fn run_main( mut cli: Cli, arg0_paths: Arg0DispatchPaths, @@ -1089,11 +1127,11 @@ pub async fn run_main( #[allow(clippy::too_many_arguments)] async fn run_ratatui_app( - cli: Cli, + mut cli: Cli, arg0_paths: Arg0DispatchPaths, loader_overrides: LoaderOverrides, app_server_target: AppServerTarget, - remote_cwd_override: Option, + mut remote_cwd_override: Option, initial_config: Config, overrides: ConfigOverrides, cli_kv_overrides: Vec<(String, toml::Value)>, @@ -1175,6 +1213,51 @@ async fn run_ratatui_app( }, ); + let startup_worktree_requested = cli.worktree.is_some(); + let mut initial_config = initial_config; + if let Some(branch) = cli.worktree.take() { + let Some(startup_app_server) = app_server.as_mut() else { + unreachable!("app server should exist while resolving startup worktree"); + }; + let response = match create_startup_worktree( + startup_app_server, + if remote_mode { + remote_cwd_override.as_deref() + } else { + Some(initial_config.cwd.as_path()) + }, + branch, + cli.worktree_base.take(), + cli.worktree_dirty, + ) + .await + { + Ok(response) => response, + Err(err) => { + shutdown_app_server_if_present(app_server.take()).await; + terminal_restore_guard.restore_silently(); + session_log::log_session_end(); + return Err(err); + } + }; + let worktree_cwd = PathBuf::from(response.info.workspace_cwd.clone()); + if remote_mode { + remote_cwd_override = Some(worktree_cwd.clone()); + startup_app_server.set_remote_cwd_override(Some(worktree_cwd)); + } else { + initial_config = load_config_or_exit_with_fallback_cwd( + cli_kv_overrides.clone(), + overrides.clone(), + cloud_requirements.clone(), + Some(worktree_cwd), + ) + .await; + } + initial_config + .startup_warnings + .extend(response.warnings.into_iter().map(|warning| warning.message)); + } + let should_show_trust_screen_flag = !remote_mode && should_show_trust_screen(&initial_config); let mut trust_decision_was_made = false; let login_status = if initial_config.model_provider.requires_openai_auth { @@ -1391,7 +1474,7 @@ async fn run_ratatui_app( }; let current_cwd = config.cwd.clone(); - let allow_prompt = !remote_mode && cli.cwd.is_none(); + let allow_prompt = !remote_mode && cli.cwd.is_none() && !startup_worktree_requested; let action_and_target_session_if_resume_or_fork = match &session_selection { resume_picker::SessionSelection::Resume(target_session) => { Some((CwdPromptAction::Resume, target_session)) @@ -1403,7 +1486,7 @@ async fn run_ratatui_app( }; let fallback_cwd = match action_and_target_session_if_resume_or_fork { Some((action, target_session)) => { - if remote_mode { + if startup_worktree_requested || remote_mode { Some(current_cwd.to_path_buf()) } else { match resolve_cwd_for_resume_or_fork( diff --git a/codex-rs/tui/src/remote_worktree.rs b/codex-rs/tui/src/remote_worktree.rs deleted file mode 100644 index 0d537799b5..0000000000 --- a/codex-rs/tui/src/remote_worktree.rs +++ /dev/null @@ -1,1042 +0,0 @@ -use std::path::Path; -use std::path::PathBuf; - -use anyhow::Context; -use anyhow::Result; -use base64::Engine; -use base64::engine::general_purpose::STANDARD; -use codex_app_server_client::AppServerRequestHandle; -use codex_app_server_protocol::ClientRequest; -use codex_app_server_protocol::FsCopyParams; -use codex_app_server_protocol::FsCopyResponse; -use codex_app_server_protocol::FsCreateDirectoryParams; -use codex_app_server_protocol::FsCreateDirectoryResponse; -use codex_app_server_protocol::FsGetMetadataParams; -use codex_app_server_protocol::FsGetMetadataResponse; -use codex_app_server_protocol::FsReadFileParams; -use codex_app_server_protocol::FsReadFileResponse; -use codex_app_server_protocol::FsRemoveParams; -use codex_app_server_protocol::FsRemoveResponse; -use codex_app_server_protocol::FsWriteFileParams; -use codex_app_server_protocol::FsWriteFileResponse; -use codex_app_server_protocol::RequestId; -use codex_utils_absolute_path::AbsolutePathBuf; -use codex_worktree::DirtyPolicy; -use codex_worktree::DirtyState; -use codex_worktree::WorktreeInfo; -use codex_worktree::WorktreeLocation; -use codex_worktree::WorktreeMetadata; -use codex_worktree::WorktreeRemoveResult; -use codex_worktree::WorktreeRequest; -use codex_worktree::WorktreeResolution; -use codex_worktree::WorktreeSource; -use codex_worktree::WorktreeThreadMetadata; -use codex_worktree::WorktreeWarning; -use uuid::Uuid; - -use crate::workspace_command::WorkspaceCommand; -use crate::workspace_command::WorkspaceCommandRunner; - -pub(crate) async fn list_current_repo_worktrees( - runner: &WorkspaceCommandRunner, - request_handle: &AppServerRequestHandle, - source_cwd: &Path, -) -> Result> { - let repo = RemoteSourceRepo::resolve(runner, source_cwd).await?; - let worktrees = parse_worktree_list( - &git_stdout(runner, &repo.root, &["worktree", "list", "--porcelain"]).await?, - ); - let mut infos = Vec::new(); - for entry in worktrees { - infos.push( - info_from_existing_worktree(runner, request_handle, &entry.path, entry.branch, &repo) - .await?, - ); - } - Ok(infos) -} - -pub(crate) async fn source_dirty_state( - runner: &WorkspaceCommandRunner, - source_cwd: &Path, -) -> Result { - let repo = RemoteSourceRepo::resolve(runner, source_cwd).await?; - dirty_state(runner, &repo.root).await -} - -pub(crate) async fn ensure_worktree( - runner: &WorkspaceCommandRunner, - request_handle: &AppServerRequestHandle, - req: WorktreeRequest, -) -> Result { - let repo = RemoteSourceRepo::resolve(runner, &req.source_cwd).await?; - let branch = req.branch.clone(); - git_status( - runner, - &repo.root, - &["check-ref-format", "--branch", &branch], - ) - .await?; - let worktree_git_root = codex_worktree::sibling_worktree_git_root(&repo.primary_root, &branch)?; - let workspace_cwd = worktree_git_root.join(&repo.relative_cwd); - - if path_exists(request_handle, &worktree_git_root).await? { - let metadata = read_metadata(runner, request_handle, &worktree_git_root) - .await? - .context("managed worktree path already exists but is not owned by Codex")?; - if metadata.branch.as_deref() != Some(branch.as_str()) && metadata.name != branch { - anyhow::bail!( - "managed worktree path {} is already used by {}; choose a different branch name", - worktree_git_root.display(), - metadata.branch.as_deref().unwrap_or(metadata.name.as_str()) - ); - } - let info = info_from_existing_worktree( - runner, - request_handle, - &worktree_git_root, - Some(branch), - &repo, - ) - .await?; - return Ok(WorktreeResolution { - reused: true, - info, - warnings: Vec::new(), - }); - } - - let worktrees = parse_worktree_list( - &git_stdout(runner, &repo.root, &["worktree", "list", "--porcelain"]).await?, - ); - if let Some(existing) = worktrees - .iter() - .find(|entry| entry.branch.as_deref() == Some(branch.as_str())) - && existing.path != worktree_git_root - { - anyhow::bail!( - "branch {branch} is already checked out at {}; remove that worktree first", - existing.path.display() - ); - } - - let warnings = - validate_dirty_policy_before_create(runner, &repo.root, req.dirty_policy).await?; - create_directory( - request_handle, - worktree_git_root - .parent() - .context("managed worktree path has no parent")?, - ) - .await?; - let branch_exists = git_status_result( - runner, - &repo.root, - &[ - "show-ref", - "--verify", - "--quiet", - &format!("refs/heads/{branch}"), - ], - ) - .await? - .success(); - let has_head = git_status_result(runner, &repo.root, &["rev-parse", "--verify", "HEAD"]) - .await? - .success(); - if branch_exists { - git_status( - runner, - &repo.root, - &[ - "worktree", - "add", - &worktree_git_root.to_string_lossy(), - &branch, - ], - ) - .await?; - } else if req.base_ref.is_none() && !has_head { - git_status( - runner, - &repo.root, - &[ - "worktree", - "add", - "--orphan", - "-b", - &branch, - &worktree_git_root.to_string_lossy(), - ], - ) - .await?; - } else { - let base_ref = req.base_ref.as_deref().unwrap_or("HEAD"); - git_status( - runner, - &repo.root, - &[ - "worktree", - "add", - "-b", - &branch, - &worktree_git_root.to_string_lossy(), - base_ref, - ], - ) - .await?; - } - - let prepared_transfer = match prepare_dirty_policy_after_create( - runner, - request_handle, - &repo.root, - &worktree_git_root, - req.dirty_policy, - ) - .await - { - Ok(prepared_transfer) => prepared_transfer, - Err(err) => { - return Err(rollback_failed_create( - runner, - &repo.root, - &worktree_git_root, - &branch, - /*delete_branch*/ !branch_exists, - err, - ) - .await); - } - }; - finalize_dirty_policy_after_create(runner, request_handle, &repo.root, prepared_transfer) - .await?; - let dirty = dirty_state(runner, &worktree_git_root).await?; - let head = git_stdout_result(runner, &worktree_git_root, &["rev-parse", "HEAD"]) - .await? - .success() - .then_some(async { git_stdout(runner, &worktree_git_root, &["rev-parse", "HEAD"]).await }); - let head = match head { - Some(future) => Some(future.await?), - None => None, - }; - let info_metadata_path = - metadata_path(runner, &worktree_git_root, "codex-worktree.json").await?; - let mut info = WorktreeInfo { - id: repo.id.clone(), - name: branch.clone(), - slug: codex_worktree::slugify_name(&branch)?, - source: WorktreeSource::Cli, - location: WorktreeLocation::Sibling, - repo_name: repo.repo_name.clone(), - repo_root: repo.root.clone(), - common_git_dir: repo.common_git_dir.clone(), - worktree_git_root: worktree_git_root.clone(), - workspace_cwd, - original_relative_cwd: repo.relative_cwd.clone(), - branch: Some(branch), - head, - owner_thread_id: None, - metadata_path: info_metadata_path, - dirty, - }; - write_json( - request_handle, - &metadata_path(runner, &worktree_git_root, "codex-thread.json").await?, - &WorktreeThreadMetadata { - version: 1, - owner_thread_id: None, - }, - ) - .await?; - let metadata = WorktreeMetadata::from_info(&info, repo.root); - write_json(request_handle, &info.metadata_path, &metadata).await?; - info.owner_thread_id = metadata.owner_thread_id; - Ok(WorktreeResolution { - reused: false, - info, - warnings: warnings - .into_iter() - .map(|message| WorktreeWarning { message }) - .collect(), - }) -} - -pub(crate) async fn remove_worktree( - runner: &WorkspaceCommandRunner, - request_handle: &AppServerRequestHandle, - source_cwd: &Path, - target: &str, - force: bool, - delete_branch: bool, -) -> Result { - let entries = list_current_repo_worktrees(runner, request_handle, source_cwd).await?; - let info = entries - .into_iter() - .find(|entry| { - entry.branch.as_deref() == Some(target) || entry.name == target || entry.slug == target - }) - .context("no managed worktree matched target")?; - let metadata = read_metadata(runner, request_handle, &info.worktree_git_root) - .await? - .context("refusing to remove a worktree not managed by Codex")?; - if metadata.source != WorktreeSource::Cli { - anyhow::bail!("refusing to remove a worktree not managed by Codex CLI"); - } - if info.dirty.is_dirty() && !force { - anyhow::bail!( - "refusing to remove dirty worktree {}; use --force to override", - info.worktree_git_root.display() - ); - } - let repo = RemoteSourceRepo::resolve(runner, source_cwd).await?; - let mut args = vec!["worktree", "remove"]; - if force { - args.push("--force"); - } - let target_path = info.worktree_git_root.to_string_lossy().to_string(); - args.push(&target_path); - git_status(runner, &repo.primary_root, &args).await?; - let mut deleted_branch = None; - if delete_branch && let Some(branch) = info.branch { - let delete_flag = if force { "-D" } else { "-d" }; - git_status( - runner, - &repo.primary_root, - &["branch", delete_flag, &branch], - ) - .await?; - deleted_branch = Some(branch); - } - Ok(WorktreeRemoveResult { - removed_path: info.worktree_git_root, - deleted_branch, - }) -} - -#[derive(Clone)] -struct RemoteSourceRepo { - root: PathBuf, - primary_root: PathBuf, - relative_cwd: PathBuf, - common_git_dir: PathBuf, - repo_name: String, - id: String, -} - -impl RemoteSourceRepo { - async fn resolve(runner: &WorkspaceCommandRunner, source_cwd: &Path) -> Result { - let root = - PathBuf::from(git_stdout(runner, source_cwd, &["rev-parse", "--show-toplevel"]).await?); - let common_git_dir_raw = - git_stdout(runner, source_cwd, &["rev-parse", "--git-common-dir"]).await?; - let common_git_dir = absolutize(source_cwd, Path::new(&common_git_dir_raw)); - let primary_root = parse_worktree_list( - &git_stdout(runner, &root, &["worktree", "list", "--porcelain"]).await?, - ) - .into_iter() - .next() - .map(|entry| entry.path) - .context("git did not report a primary worktree")?; - let origin = git_stdout_result(runner, &root, &["remote", "get-url", "origin"]).await?; - let origin = origin.success().then_some(origin.stdout.trim().to_string()); - let id = codex_worktree::repo_fingerprint(&common_git_dir, origin.as_deref()); - let repo_name = primary_root - .file_name() - .context("repository root has no directory name")? - .to_string_lossy() - .to_string(); - let relative_cwd = source_cwd - .strip_prefix(&root) - .unwrap_or_else(|_| Path::new("")) - .to_path_buf(); - Ok(Self { - root, - primary_root, - relative_cwd, - common_git_dir, - repo_name, - id, - }) - } -} - -async fn info_from_existing_worktree( - runner: &WorkspaceCommandRunner, - request_handle: &AppServerRequestHandle, - worktree_git_root: &Path, - fallback_branch: Option, - repo: &RemoteSourceRepo, -) -> Result { - let metadata = read_metadata(runner, request_handle, worktree_git_root).await?; - let branch = git_stdout_result( - runner, - worktree_git_root, - &["symbolic-ref", "--quiet", "--short", "HEAD"], - ) - .await? - .success() - .then_some(async { - git_stdout( - runner, - worktree_git_root, - &["symbolic-ref", "--quiet", "--short", "HEAD"], - ) - .await - }); - let branch = match branch { - Some(future) => Some(future.await?), - None => fallback_branch, - }; - let head = git_stdout_result(runner, worktree_git_root, &["rev-parse", "HEAD"]) - .await? - .success() - .then_some(async { git_stdout(runner, worktree_git_root, &["rev-parse", "HEAD"]).await }); - let head = match head { - Some(future) => Some(future.await?), - None => None, - }; - let dirty = dirty_state(runner, worktree_git_root) - .await - .unwrap_or_default(); - let name = metadata - .as_ref() - .map(|metadata| metadata.name.clone()) - .or_else(|| branch.clone()) - .unwrap_or_else(|| repo.repo_name.clone()); - let slug = metadata - .as_ref() - .map(|metadata| metadata.slug.clone()) - .unwrap_or_else(|| name.replace(['/', '\\'], "-")); - Ok(WorktreeInfo { - id: metadata - .as_ref() - .map(|metadata| metadata.repo_id.clone()) - .unwrap_or_else(|| repo.id.clone()), - name, - slug, - source: metadata - .as_ref() - .map(|metadata| metadata.source) - .unwrap_or(WorktreeSource::Git), - location: metadata - .as_ref() - .map(|metadata| metadata.location) - .unwrap_or(WorktreeLocation::External), - repo_name: repo.repo_name.clone(), - repo_root: repo.root.clone(), - common_git_dir: repo.common_git_dir.clone(), - worktree_git_root: worktree_git_root.to_path_buf(), - workspace_cwd: metadata - .as_ref() - .map(|metadata| metadata.workspace_cwd.clone()) - .unwrap_or_else(|| worktree_git_root.to_path_buf()), - original_relative_cwd: metadata - .as_ref() - .map(|metadata| metadata.original_relative_cwd.clone()) - .unwrap_or_default(), - branch, - head, - owner_thread_id: metadata.and_then(|metadata| metadata.owner_thread_id), - metadata_path: metadata_path(runner, worktree_git_root, "codex-worktree.json").await?, - dirty, - }) -} - -async fn dirty_state(runner: &WorkspaceCommandRunner, root: &Path) -> Result { - Ok(DirtyState { - has_staged_changes: !git_stdout(runner, root, &["diff", "--cached", "--name-only", "-z"]) - .await? - .is_empty(), - has_unstaged_changes: !git_stdout(runner, root, &["diff", "--name-only", "-z"]) - .await? - .is_empty(), - has_untracked_files: !git_stdout( - runner, - root, - &["ls-files", "--others", "--exclude-standard", "-z"], - ) - .await? - .is_empty(), - }) -} - -async fn validate_dirty_policy_before_create( - runner: &WorkspaceCommandRunner, - root: &Path, - policy: DirtyPolicy, -) -> Result> { - let state = dirty_state(runner, root).await?; - if !state.is_dirty() { - return Ok(Vec::new()); - } - match policy { - DirtyPolicy::Fail => anyhow::bail!( - "source checkout has uncommitted changes; use --worktree-dirty ignore, copy-tracked, copy-all, move-tracked, or move-all" - ), - DirtyPolicy::Ignore => Ok(vec![ - "source checkout has uncommitted changes; the new worktree was created without them" - .to_string(), - ]), - DirtyPolicy::CopyTracked | DirtyPolicy::MoveTracked if state.has_untracked_files => Ok(vec![ - "untracked files were left in the source checkout; use --worktree-dirty copy-all or move-all to carry them" - .to_string(), - ]), - DirtyPolicy::CopyTracked - | DirtyPolicy::CopyAll - | DirtyPolicy::MoveTracked - | DirtyPolicy::MoveAll => Ok(Vec::new()), - } -} - -async fn prepare_dirty_policy_after_create( - runner: &WorkspaceCommandRunner, - request_handle: &AppServerRequestHandle, - source_root: &Path, - worktree_root: &Path, - policy: DirtyPolicy, -) -> Result { - let state = dirty_state(runner, source_root).await?; - if !state.is_dirty() { - return Ok(PreparedRemoteDirtyTransfer { move_plan: None }); - } - let plan = RemoteTransferPlan::capture(runner, source_root).await?; - match policy { - DirtyPolicy::Fail | DirtyPolicy::Ignore => { - Ok(PreparedRemoteDirtyTransfer { move_plan: None }) - } - DirtyPolicy::CopyTracked => { - plan.apply_tracked_diff(runner, request_handle, worktree_root) - .await?; - Ok(PreparedRemoteDirtyTransfer { move_plan: None }) - } - DirtyPolicy::CopyAll => { - plan.apply_tracked_diff(runner, request_handle, worktree_root) - .await?; - plan.copy_untracked(request_handle, source_root, worktree_root) - .await?; - Ok(PreparedRemoteDirtyTransfer { move_plan: None }) - } - DirtyPolicy::MoveTracked => { - plan.apply_tracked_diff(runner, request_handle, worktree_root) - .await?; - Ok(PreparedRemoteDirtyTransfer { - move_plan: Some(RemoteMovePlan { - transfer: plan, - move_untracked: false, - }), - }) - } - DirtyPolicy::MoveAll => { - plan.apply_tracked_diff(runner, request_handle, worktree_root) - .await?; - plan.copy_untracked(request_handle, source_root, worktree_root) - .await?; - Ok(PreparedRemoteDirtyTransfer { - move_plan: Some(RemoteMovePlan { - transfer: plan, - move_untracked: true, - }), - }) - } - } -} - -async fn finalize_dirty_policy_after_create( - runner: &WorkspaceCommandRunner, - request_handle: &AppServerRequestHandle, - source_root: &Path, - prepared: PreparedRemoteDirtyTransfer, -) -> Result<()> { - let Some(move_plan) = prepared.move_plan else { - return Ok(()); - }; - move_plan - .transfer - .clean_source_after_move( - runner, - request_handle, - source_root, - move_plan.move_untracked, - ) - .await - .with_context(|| { - "worktree already contains transferred changes, but failed to clean the source checkout after move" - }) -} - -async fn rollback_failed_create( - runner: &WorkspaceCommandRunner, - repo_root: &Path, - worktree_git_root: &Path, - branch: &str, - delete_branch: bool, - err: anyhow::Error, -) -> anyhow::Error { - let mut rollback_errors = Vec::new(); - let worktree_arg = worktree_git_root.to_string_lossy().to_string(); - if let Err(rollback_err) = git_status( - runner, - repo_root, - &["worktree", "remove", "--force", &worktree_arg], - ) - .await - { - rollback_errors.push(rollback_err.to_string()); - } - if delete_branch - && let Err(rollback_err) = git_status(runner, repo_root, &["branch", "-D", branch]).await - { - rollback_errors.push(rollback_err.to_string()); - } - if rollback_errors.is_empty() { - err - } else { - anyhow::anyhow!( - "{err}; additionally failed to roll back newly-created worktree: {}", - rollback_errors.join("; ") - ) - } -} - -struct PreparedRemoteDirtyTransfer { - move_plan: Option, -} - -struct RemoteMovePlan { - transfer: RemoteTransferPlan, - move_untracked: bool, -} - -struct RemoteTransferPlan { - staged_diff: String, - unstaged_diff: String, - tracked_paths: Vec, - untracked_paths: Vec, -} - -impl RemoteTransferPlan { - async fn capture(runner: &WorkspaceCommandRunner, source_root: &Path) -> Result { - Ok(Self { - staged_diff: git_stdout_raw_uncapped( - runner, - source_root, - &["diff", "--cached", "--binary"], - ) - .await?, - unstaged_diff: git_stdout_raw_uncapped(runner, source_root, &["diff", "--binary"]) - .await?, - tracked_paths: tracked_paths(runner, source_root).await?, - untracked_paths: untracked_paths(runner, source_root).await?, - }) - } - - async fn apply_tracked_diff( - &self, - runner: &WorkspaceCommandRunner, - request_handle: &AppServerRequestHandle, - worktree_root: &Path, - ) -> Result<()> { - if !self.staged_diff.is_empty() { - apply_patch_file( - runner, - request_handle, - worktree_root, - "staged", - &self.staged_diff, - &["apply", "--index", "--binary"], - ) - .await?; - } - if !self.unstaged_diff.is_empty() { - apply_patch_file( - runner, - request_handle, - worktree_root, - "unstaged", - &self.unstaged_diff, - &["apply", "--binary"], - ) - .await?; - } - Ok(()) - } - - async fn copy_untracked( - &self, - request_handle: &AppServerRequestHandle, - source_root: &Path, - worktree_root: &Path, - ) -> Result<()> { - for relative_path in &self.untracked_paths { - if let Some(parent) = worktree_root.join(relative_path).parent() { - create_directory(request_handle, parent).await?; - } - fs_copy( - request_handle, - &source_root.join(relative_path), - &worktree_root.join(relative_path), - ) - .await?; - } - Ok(()) - } - - async fn clean_source_after_move( - &self, - runner: &WorkspaceCommandRunner, - request_handle: &AppServerRequestHandle, - source_root: &Path, - move_untracked: bool, - ) -> Result<()> { - if git_status_result(runner, source_root, &["rev-parse", "--verify", "HEAD"]) - .await? - .success() - { - git_status(runner, source_root, &["reset", "--hard", "HEAD"]).await?; - } else { - git_status(runner, source_root, &["read-tree", "--empty"]).await?; - for relative_path in &self.tracked_paths { - fs_remove(request_handle, &source_root.join(relative_path)).await?; - } - } - if move_untracked { - for relative_path in &self.untracked_paths { - fs_remove(request_handle, &source_root.join(relative_path)).await?; - } - } - Ok(()) - } -} - -async fn apply_patch_file( - runner: &WorkspaceCommandRunner, - request_handle: &AppServerRequestHandle, - cwd: &Path, - label: &str, - contents: &str, - git_args: &[&str], -) -> Result<()> { - let patch_path = metadata_path( - runner, - cwd, - &format!("codex-worktree-{label}-{}.patch", Uuid::new_v4()), - ) - .await?; - fs_write(request_handle, &patch_path, contents.as_bytes()).await?; - let mut args = git_args.to_vec(); - let patch_arg = patch_path.to_string_lossy().to_string(); - args.push(&patch_arg); - let result = git_status(runner, cwd, &args).await; - let _ = fs_remove(request_handle, &patch_path).await; - result -} - -async fn tracked_paths(runner: &WorkspaceCommandRunner, root: &Path) -> Result> { - let mut paths = paths_from_nul_separated( - &git_stdout(runner, root, &["diff", "--cached", "--name-only", "-z"]).await?, - ); - paths.extend(paths_from_nul_separated( - &git_stdout(runner, root, &["diff", "--name-only", "-z"]).await?, - )); - paths.sort(); - paths.dedup(); - Ok(paths) -} - -async fn untracked_paths(runner: &WorkspaceCommandRunner, root: &Path) -> Result> { - Ok(paths_from_nul_separated( - &git_stdout( - runner, - root, - &["ls-files", "--others", "--exclude-standard", "-z"], - ) - .await?, - )) -} - -fn paths_from_nul_separated(output: &str) -> Vec { - output - .split('\0') - .filter(|path| !path.is_empty()) - .map(PathBuf::from) - .collect() -} - -async fn read_metadata( - runner: &WorkspaceCommandRunner, - request_handle: &AppServerRequestHandle, - worktree_root: &Path, -) -> Result> { - let path = metadata_path(runner, worktree_root, "codex-worktree.json").await?; - if !path_exists(request_handle, &path).await? { - return Ok(None); - } - let contents = fs_read(request_handle, &path).await?; - Ok(Some(serde_json::from_slice(&contents)?)) -} - -async fn write_json( - request_handle: &AppServerRequestHandle, - path: &Path, - value: &T, -) -> Result<()> { - fs_write(request_handle, path, &serde_json::to_vec_pretty(value)?).await -} - -async fn metadata_path( - runner: &WorkspaceCommandRunner, - root: &Path, - name: &str, -) -> Result { - Ok(absolutize( - root, - Path::new(&git_stdout(runner, root, &["rev-parse", "--git-path", name]).await?), - )) -} - -fn absolutize(cwd: &Path, path: &Path) -> PathBuf { - if path.is_absolute() { - path.to_path_buf() - } else { - cwd.join(path) - } -} - -#[derive(Debug)] -struct GitWorktreeEntry { - path: PathBuf, - branch: Option, -} - -fn parse_worktree_list(output: &str) -> Vec { - let mut entries = Vec::new(); - let mut path = None; - let mut branch = None; - for line in output.lines().chain(std::iter::once("")) { - if line.is_empty() { - if let Some(path) = path.take() { - entries.push(GitWorktreeEntry { - path, - branch: branch.take(), - }); - } - continue; - } - if let Some(raw_path) = line.strip_prefix("worktree ") { - path = Some(PathBuf::from(raw_path)); - } else if let Some(raw_branch) = line.strip_prefix("branch ") { - branch = Some(raw_branch.trim_start_matches("refs/heads/").to_string()); - } - } - entries -} - -async fn git_stdout(runner: &WorkspaceCommandRunner, cwd: &Path, args: &[&str]) -> Result { - let output = git_stdout_result(runner, cwd, args).await?; - if !output.success() { - anyhow::bail!("git {} failed: {}", args.join(" "), output.stderr.trim()); - } - Ok(output.stdout.trim_end().to_string()) -} - -async fn git_stdout_raw_uncapped( - runner: &WorkspaceCommandRunner, - cwd: &Path, - args: &[&str], -) -> Result { - let argv = std::iter::once("git") - .chain(args.iter().copied()) - .collect::>(); - let output = runner - .run(WorkspaceCommand::new(argv).cwd(cwd).disable_output_cap()) - .await?; - if !output.success() { - anyhow::bail!("git {} failed: {}", args.join(" "), output.stderr.trim()); - } - Ok(output.stdout) -} - -async fn git_stdout_result( - runner: &WorkspaceCommandRunner, - cwd: &Path, - args: &[&str], -) -> Result { - let argv = std::iter::once("git") - .chain(args.iter().copied()) - .collect::>(); - Ok(runner.run(WorkspaceCommand::new(argv).cwd(cwd)).await?) -} - -async fn git_status(runner: &WorkspaceCommandRunner, cwd: &Path, args: &[&str]) -> Result<()> { - let output = git_status_result(runner, cwd, args).await?; - if !output.success() { - anyhow::bail!("git {} failed: {}", args.join(" "), output.stderr.trim()); - } - Ok(()) -} - -async fn git_status_result( - runner: &WorkspaceCommandRunner, - cwd: &Path, - args: &[&str], -) -> Result { - git_stdout_result(runner, cwd, args).await -} - -fn absolute_path(path: &Path) -> Result { - AbsolutePathBuf::from_absolute_path(path).map_err(Into::into) -} - -async fn path_exists(request_handle: &AppServerRequestHandle, path: &Path) -> Result { - let result: Result = request_handle - .request_typed(ClientRequest::FsGetMetadata { - request_id: RequestId::String(format!("worktree-fs-meta-{}", Uuid::new_v4())), - params: FsGetMetadataParams { - path: absolute_path(path)?, - }, - }) - .await; - Ok(result.is_ok()) -} - -async fn create_directory(request_handle: &AppServerRequestHandle, path: &Path) -> Result<()> { - let _: FsCreateDirectoryResponse = request_handle - .request_typed(ClientRequest::FsCreateDirectory { - request_id: RequestId::String(format!("worktree-fs-mkdir-{}", Uuid::new_v4())), - params: FsCreateDirectoryParams { - path: absolute_path(path)?, - recursive: Some(true), - }, - }) - .await?; - Ok(()) -} - -async fn fs_read(request_handle: &AppServerRequestHandle, path: &Path) -> Result> { - let response: FsReadFileResponse = request_handle - .request_typed(ClientRequest::FsReadFile { - request_id: RequestId::String(format!("worktree-fs-read-{}", Uuid::new_v4())), - params: FsReadFileParams { - path: absolute_path(path)?, - }, - }) - .await?; - Ok(STANDARD.decode(response.data_base64)?) -} - -async fn fs_write( - request_handle: &AppServerRequestHandle, - path: &Path, - bytes: &[u8], -) -> Result<()> { - let _: FsWriteFileResponse = request_handle - .request_typed(ClientRequest::FsWriteFile { - request_id: RequestId::String(format!("worktree-fs-write-{}", Uuid::new_v4())), - params: FsWriteFileParams { - path: absolute_path(path)?, - data_base64: STANDARD.encode(bytes), - }, - }) - .await?; - Ok(()) -} - -async fn fs_copy( - request_handle: &AppServerRequestHandle, - source_path: &Path, - destination_path: &Path, -) -> Result<()> { - let _: FsCopyResponse = request_handle - .request_typed(ClientRequest::FsCopy { - request_id: RequestId::String(format!("worktree-fs-copy-{}", Uuid::new_v4())), - params: FsCopyParams { - source_path: absolute_path(source_path)?, - destination_path: absolute_path(destination_path)?, - recursive: false, - }, - }) - .await?; - Ok(()) -} - -async fn fs_remove(request_handle: &AppServerRequestHandle, path: &Path) -> Result<()> { - let _: FsRemoveResponse = request_handle - .request_typed(ClientRequest::FsRemove { - request_id: RequestId::String(format!("worktree-fs-remove-{}", Uuid::new_v4())), - params: FsRemoveParams { - path: absolute_path(path)?, - recursive: Some(false), - force: Some(true), - }, - }) - .await?; - Ok(()) -} - -#[cfg(test)] -mod tests { - use std::future::Future; - use std::path::PathBuf; - use std::pin::Pin; - use std::sync::Arc; - use std::sync::Mutex; - - use pretty_assertions::assert_eq; - - use super::git_stdout_raw_uncapped; - use crate::workspace_command::WorkspaceCommand; - use crate::workspace_command::WorkspaceCommandError; - use crate::workspace_command::WorkspaceCommandExecutor; - use crate::workspace_command::WorkspaceCommandOutput; - use crate::workspace_command::WorkspaceCommandRunner; - - struct FakeRunner { - seen: Mutex>, - output: WorkspaceCommandOutput, - } - - impl WorkspaceCommandExecutor for FakeRunner { - fn run( - &self, - command: WorkspaceCommand, - ) -> Pin< - Box< - dyn Future> - + Send - + '_, - >, - > { - self.seen.lock().expect("seen lock").push(command); - Box::pin(async move { Ok(self.output.clone()) }) - } - } - - #[tokio::test] - async fn raw_git_stdout_preserves_patch_newline_and_disables_output_cap() { - let fake_runner = Arc::new(FakeRunner { - seen: Mutex::new(Vec::new()), - output: WorkspaceCommandOutput { - exit_code: 0, - stdout: "diff --git a/file b/file\n".to_string(), - stderr: String::new(), - }, - }); - let runner: WorkspaceCommandRunner = fake_runner.clone(); - - let output = git_stdout_raw_uncapped( - &runner, - &PathBuf::from("/repo"), - &["diff", "--cached", "--binary"], - ) - .await - .expect("raw git stdout"); - - assert_eq!(output, "diff --git a/file b/file\n"); - let seen = fake_runner.seen.lock().expect("seen lock"); - assert_eq!(seen.len(), 1); - assert_eq!(seen[0].argv, vec!["git", "diff", "--cached", "--binary"]); - assert_eq!(seen[0].cwd, Some(PathBuf::from("/repo"))); - assert!(seen[0].disable_output_cap); - } -}