mirror of
https://github.com/openai/codex.git
synced 2026-12-05 01:00:54 +00:00
refactor(worktree): route cli management through app-server
This commit is contained in:
+69
@@ -0,0 +1,69 @@
|
||||
# Codex Worktrees
|
||||
|
||||
This context describes how Codex names and reasons about Git-backed session destinations. The product exposes the familiar Git term while distinguishing those destinations from the broader notion of a session workspace.
|
||||
|
||||
## Language
|
||||
|
||||
**Workspace**:
|
||||
The filesystem location where a Codex session runs.
|
||||
|
||||
**Managed worktree**:
|
||||
A Codex-owned workspace backed by a Git worktree.
|
||||
_Avoid_: workspace when the Git-backed ownership matters
|
||||
|
||||
**External worktree**:
|
||||
A Git worktree visible to Codex but not owned or mutated by Codex.
|
||||
|
||||
**Worktree origin**:
|
||||
The current creator lineage of a managed worktree, such as CLI or App, retained for compatibility while clients converge on one app-server-backed implementation.
|
||||
|
||||
**Worktree**:
|
||||
The user-facing term for a managed worktree, matching the Codex App and developers' existing Git vocabulary.
|
||||
_Avoid_: workspace when referring specifically to the product feature
|
||||
|
||||
**Worktree management**:
|
||||
Standalone creation, inspection, and removal of managed worktrees outside a running Codex session.
|
||||
|
||||
**Worktree launch**:
|
||||
Starting a Codex session in a named managed worktree, creating it when needed.
|
||||
|
||||
**Worktree switching**:
|
||||
Moving an active Codex session into a managed worktree from inside the TUI.
|
||||
|
||||
## Relationships
|
||||
|
||||
- A **managed worktree** is one kind of **workspace**
|
||||
- An **external worktree** is a visible **workspace** that Codex does not own
|
||||
- A **worktree** is the user-facing name for a **managed worktree**
|
||||
- A **worktree origin** describes current provenance, not a permanent product subtype
|
||||
- A **workspace** may exist without being a **managed worktree**
|
||||
- **Worktree management** operates on **managed worktrees** whether or not a session is currently running in them
|
||||
- **Worktree launch** may create or reuse a **managed worktree** before the session begins
|
||||
- **Worktree switching** may create or reuse a **managed worktree** after the session has begun
|
||||
- **Worktree management**, **worktree launch**, and **worktree switching** share the app-server-backed managed-worktree model
|
||||
|
||||
## Example dialogue
|
||||
|
||||
> **Dev:** "When a user chooses a **worktree**, are they choosing any **workspace**?"
|
||||
> **Domain expert:** "No — they are choosing a Codex-managed Git-backed **workspace**."
|
||||
>
|
||||
> **Dev:** "Does a **worktree** only exist once a session starts there?"
|
||||
> **Domain expert:** "No — **worktree management** lets users create and inspect it before a session enters it."
|
||||
>
|
||||
> **Dev:** "Why can `--worktree` create one instead of only selecting an existing one?"
|
||||
> **Domain expert:** "Because **worktree launch** should be a one-step path into the named worktree."
|
||||
>
|
||||
> **Dev:** "Can `--force` remove an **external worktree**?"
|
||||
> **Domain expert:** "No — force bypasses cleanliness checks, not ownership."
|
||||
>
|
||||
> **Dev:** "Are CLI and App worktrees different products?"
|
||||
> **Domain expert:** "No — their **worktree origins** differ today while the App is still migrating toward the shared app-server implementation."
|
||||
>
|
||||
> **Dev:** "Can remote CLI commands manage worktrees outside a session?"
|
||||
> **Domain expert:** "Yes — remote and local management both go through app-server."
|
||||
|
||||
## Flagged ambiguities
|
||||
|
||||
- "workspace" and "worktree" were being used interchangeably — resolved: **workspace** is broader; **worktree** names the Git-backed product feature.
|
||||
- "force" could imply bypassing ownership — resolved: it only bypasses dirty-state protection for **managed worktrees**.
|
||||
- "CLI worktree" and "App worktree" could sound like permanent subtypes — resolved: they are current **worktree origins**, not the long-term domain model.
|
||||
Generated
+2
@@ -2180,6 +2180,7 @@ dependencies = [
|
||||
"clap",
|
||||
"clap_complete",
|
||||
"codex-app-server",
|
||||
"codex-app-server-client",
|
||||
"codex-app-server-protocol",
|
||||
"codex-app-server-test-client",
|
||||
"codex-arg0",
|
||||
@@ -2193,6 +2194,7 @@ dependencies = [
|
||||
"codex-exec-server",
|
||||
"codex-execpolicy",
|
||||
"codex-features",
|
||||
"codex-feedback",
|
||||
"codex-login",
|
||||
"codex-mcp",
|
||||
"codex-mcp-server",
|
||||
|
||||
@@ -4621,6 +4621,10 @@
|
||||
"WorktreeListParams": {
|
||||
"description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.",
|
||||
"properties": {
|
||||
"all": {
|
||||
"description": "Include managed worktrees from every repository known to this app-server.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"cwd": {
|
||||
"description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.",
|
||||
"type": [
|
||||
@@ -4631,6 +4635,15 @@
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"WorktreePruneParams": {
|
||||
"description": "Remove stale managed worktree metadata from app-server storage.",
|
||||
"properties": {
|
||||
"dryRun": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
},
|
||||
"WorktreeRemoveParams": {
|
||||
"description": "Remove a managed worktree in the repository containing \\`cwd\\`.",
|
||||
"properties": {
|
||||
@@ -5765,6 +5778,30 @@
|
||||
"title": "Worktree/removeRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
"$ref": "#/definitions/RequestId"
|
||||
},
|
||||
"method": {
|
||||
"enum": [
|
||||
"worktree/prune"
|
||||
],
|
||||
"title": "Worktree/pruneRequestMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/definitions/WorktreePruneParams"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"method",
|
||||
"params"
|
||||
],
|
||||
"title": "Worktree/pruneRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
|
||||
+56
@@ -1290,6 +1290,30 @@
|
||||
"title": "Worktree/removeRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
"$ref": "#/definitions/v2/RequestId"
|
||||
},
|
||||
"method": {
|
||||
"enum": [
|
||||
"worktree/prune"
|
||||
],
|
||||
"title": "Worktree/pruneRequestMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/definitions/v2/WorktreePruneParams"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"method",
|
||||
"params"
|
||||
],
|
||||
"title": "Worktree/pruneRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
@@ -18946,6 +18970,10 @@
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.",
|
||||
"properties": {
|
||||
"all": {
|
||||
"description": "Include managed worktrees from every repository known to this app-server.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"cwd": {
|
||||
"description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.",
|
||||
"type": [
|
||||
@@ -18982,6 +19010,34 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"WorktreePruneParams": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Remove stale managed worktree metadata from app-server storage.",
|
||||
"properties": {
|
||||
"dryRun": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"title": "WorktreePruneParams",
|
||||
"type": "object"
|
||||
},
|
||||
"WorktreePruneResponse": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Result returned by `worktree/prune`.",
|
||||
"properties": {
|
||||
"paths": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"paths"
|
||||
],
|
||||
"title": "WorktreePruneResponse",
|
||||
"type": "object"
|
||||
},
|
||||
"WorktreeRemoveParams": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Remove a managed worktree in the repository containing \\`cwd\\`.",
|
||||
|
||||
+56
@@ -2049,6 +2049,30 @@
|
||||
"title": "Worktree/removeRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
"$ref": "#/definitions/RequestId"
|
||||
},
|
||||
"method": {
|
||||
"enum": [
|
||||
"worktree/prune"
|
||||
],
|
||||
"title": "Worktree/pruneRequestMethod",
|
||||
"type": "string"
|
||||
},
|
||||
"params": {
|
||||
"$ref": "#/definitions/WorktreePruneParams"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"method",
|
||||
"params"
|
||||
],
|
||||
"title": "Worktree/pruneRequest",
|
||||
"type": "object"
|
||||
},
|
||||
{
|
||||
"properties": {
|
||||
"id": {
|
||||
@@ -16832,6 +16856,10 @@
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.",
|
||||
"properties": {
|
||||
"all": {
|
||||
"description": "Include managed worktrees from every repository known to this app-server.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"cwd": {
|
||||
"description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.",
|
||||
"type": [
|
||||
@@ -16868,6 +16896,34 @@
|
||||
],
|
||||
"type": "string"
|
||||
},
|
||||
"WorktreePruneParams": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Remove stale managed worktree metadata from app-server storage.",
|
||||
"properties": {
|
||||
"dryRun": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"title": "WorktreePruneParams",
|
||||
"type": "object"
|
||||
},
|
||||
"WorktreePruneResponse": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Result returned by `worktree/prune`.",
|
||||
"properties": {
|
||||
"paths": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"paths"
|
||||
],
|
||||
"title": "WorktreePruneResponse",
|
||||
"type": "object"
|
||||
},
|
||||
"WorktreeRemoveParams": {
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Remove a managed worktree in the repository containing \\`cwd\\`.",
|
||||
|
||||
@@ -2,6 +2,10 @@
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Request the managed worktrees associated with the repository containing \\`cwd\\`.",
|
||||
"properties": {
|
||||
"all": {
|
||||
"description": "Include managed worktrees from every repository known to this app-server.",
|
||||
"type": "boolean"
|
||||
},
|
||||
"cwd": {
|
||||
"description": "Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.",
|
||||
"type": [
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Remove stale managed worktree metadata from app-server storage.",
|
||||
"properties": {
|
||||
"dryRun": {
|
||||
"type": "boolean"
|
||||
}
|
||||
},
|
||||
"title": "WorktreePruneParams",
|
||||
"type": "object"
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"description": "Result returned by `worktree/prune`.",
|
||||
"properties": {
|
||||
"paths": {
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"type": "array"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"paths"
|
||||
],
|
||||
"title": "WorktreePruneResponse",
|
||||
"type": "object"
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
@@ -9,4 +9,8 @@ export type WorktreeListParams = {
|
||||
/**
|
||||
* Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.
|
||||
*/
|
||||
cwd?: string | null, };
|
||||
cwd?: string | null,
|
||||
/**
|
||||
* Include managed worktrees from every repository known to this app-server.
|
||||
*/
|
||||
all?: boolean, };
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Remove stale managed worktree metadata from app-server storage.
|
||||
*/
|
||||
export type WorktreePruneParams = { dryRun?: boolean, };
|
||||
@@ -0,0 +1,8 @@
|
||||
// GENERATED CODE! DO NOT MODIFY BY HAND!
|
||||
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Result returned by `worktree/prune`.
|
||||
*/
|
||||
export type WorktreePruneResponse = { paths: Array<string>, };
|
||||
@@ -462,6 +462,8 @@ export type { WorktreeInspectSourceResponse } from "./WorktreeInspectSourceRespo
|
||||
export type { WorktreeListParams } from "./WorktreeListParams";
|
||||
export type { WorktreeListResponse } from "./WorktreeListResponse";
|
||||
export type { WorktreeLocation } from "./WorktreeLocation";
|
||||
export type { WorktreePruneParams } from "./WorktreePruneParams";
|
||||
export type { WorktreePruneResponse } from "./WorktreePruneResponse";
|
||||
export type { WorktreeRemoveParams } from "./WorktreeRemoveParams";
|
||||
export type { WorktreeRemoveResponse } from "./WorktreeRemoveResponse";
|
||||
export type { WorktreeSource } from "./WorktreeSource";
|
||||
|
||||
@@ -730,6 +730,11 @@ client_request_definitions! {
|
||||
serialization: global("worktree"),
|
||||
response: v2::WorktreeRemoveResponse,
|
||||
},
|
||||
WorktreePrune => "worktree/prune" {
|
||||
params: v2::WorktreePruneParams,
|
||||
serialization: global("worktree"),
|
||||
response: v2::WorktreePruneResponse,
|
||||
},
|
||||
SkillsConfigWrite => "skills/config/write" {
|
||||
params: v2::SkillsConfigWriteParams,
|
||||
serialization: global("config"),
|
||||
|
||||
@@ -11,6 +11,9 @@ pub struct WorktreeListParams {
|
||||
/// Repository-relative workspace cwd to inspect. Omitted uses app-server's effective cwd.
|
||||
#[ts(optional = nullable)]
|
||||
pub cwd: Option<String>,
|
||||
/// Include managed worktrees from every repository known to this app-server.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub all: bool,
|
||||
}
|
||||
|
||||
/// Managed worktrees returned by \`worktree/list\`.
|
||||
@@ -87,6 +90,23 @@ pub struct WorktreeRemoveResponse {
|
||||
pub deleted_branch: Option<String>,
|
||||
}
|
||||
|
||||
/// Remove stale managed worktree metadata from app-server storage.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct WorktreePruneParams {
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub dry_run: bool,
|
||||
}
|
||||
|
||||
/// Result returned by `worktree/prune`.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[ts(export_to = "v2/")]
|
||||
pub struct WorktreePruneResponse {
|
||||
pub paths: Vec<String>,
|
||||
}
|
||||
|
||||
/// Server-native representation of a managed worktree.
|
||||
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, JsonSchema, TS)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
|
||||
@@ -1152,10 +1152,11 @@ All filesystem paths in this section must be absolute.
|
||||
|
||||
### Worktrees
|
||||
|
||||
- `worktree/list` - list Codex-managed worktrees for the repository containing `cwd`; omitted `cwd` uses the app server's effective cwd.
|
||||
- `worktree/list` - list Codex-managed worktrees for the repository containing `cwd`; omitted `cwd` uses the app server's effective cwd, and `all` returns worktrees from every repository.
|
||||
- `worktree/inspectSource` - inspect staged, unstaged, and untracked dirty state for the repository containing `cwd`.
|
||||
- `worktree/create` - create or reuse a managed worktree from `cwd`, returning the resolved worktree plus any transfer warnings.
|
||||
- `worktree/remove` - remove a managed worktree resolved from `cwd` and `nameOrPath`, with optional `force` and `deleteBranch` behavior.
|
||||
- `worktree/prune` - remove stale managed-worktree storage entries, or report them without mutation when `dryRun` is set.
|
||||
|
||||
## Events
|
||||
|
||||
|
||||
@@ -961,6 +961,11 @@ impl MessageProcessor {
|
||||
.remove(params)
|
||||
.await
|
||||
.map(|response| Some(response.into())),
|
||||
ClientRequest::WorktreePrune { params, .. } => self
|
||||
.worktree_processor
|
||||
.prune(params)
|
||||
.await
|
||||
.map(|response| Some(response.into())),
|
||||
ClientRequest::ModelProviderCapabilitiesRead { params: _, .. } => self
|
||||
.config_processor
|
||||
.model_provider_capabilities_read()
|
||||
|
||||
@@ -251,6 +251,8 @@ use codex_app_server_protocol::WorktreeInspectSourceResponse;
|
||||
use codex_app_server_protocol::WorktreeListParams;
|
||||
use codex_app_server_protocol::WorktreeListResponse;
|
||||
use codex_app_server_protocol::WorktreeLocation as ApiWorktreeLocation;
|
||||
use codex_app_server_protocol::WorktreePruneParams;
|
||||
use codex_app_server_protocol::WorktreePruneResponse;
|
||||
use codex_app_server_protocol::WorktreeRemoveParams;
|
||||
use codex_app_server_protocol::WorktreeRemoveResponse;
|
||||
use codex_app_server_protocol::WorktreeSource as ApiWorktreeSource;
|
||||
|
||||
@@ -26,11 +26,15 @@ impl WorktreeRequestProcessor {
|
||||
&self,
|
||||
params: WorktreeListParams,
|
||||
) -> Result<WorktreeListResponse, JSONRPCErrorError> {
|
||||
let cwd = self.resolve_cwd(params.cwd).await?;
|
||||
let source_cwd = if params.all {
|
||||
None
|
||||
} else {
|
||||
Some(self.resolve_cwd(params.cwd).await?)
|
||||
};
|
||||
let data = codex_worktree::list_worktrees(WorktreeListQuery {
|
||||
codex_home: self.config_manager.codex_home().to_path_buf(),
|
||||
source_cwd: Some(cwd),
|
||||
include_all_repos: false,
|
||||
source_cwd,
|
||||
include_all_repos: params.all,
|
||||
})
|
||||
.map_err(map_worktree_error)?
|
||||
.into_iter()
|
||||
@@ -91,6 +95,31 @@ impl WorktreeRequestProcessor {
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn prune(
|
||||
&self,
|
||||
params: WorktreePruneParams,
|
||||
) -> Result<WorktreePruneResponse, JSONRPCErrorError> {
|
||||
let stale_paths =
|
||||
codex_worktree::stale_managed_worktree_dirs(self.config_manager.codex_home())
|
||||
.map_err(map_worktree_error)?;
|
||||
if !params.dry_run {
|
||||
for path in &stale_paths {
|
||||
std::fs::remove_dir_all(path).map_err(|err| {
|
||||
map_worktree_error(anyhow::anyhow!(
|
||||
"failed to remove stale worktree directory {}: {err}",
|
||||
path.display()
|
||||
))
|
||||
})?;
|
||||
}
|
||||
}
|
||||
Ok(WorktreePruneResponse {
|
||||
paths: stale_paths
|
||||
.into_iter()
|
||||
.map(|path| path.to_string_lossy().to_string())
|
||||
.collect(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn resolve_cwd(&self, cwd: Option<String>) -> Result<PathBuf, JSONRPCErrorError> {
|
||||
match cwd {
|
||||
Some(cwd) => Ok(PathBuf::from(cwd)),
|
||||
|
||||
@@ -21,6 +21,7 @@ anyhow = { workspace = true }
|
||||
clap = { workspace = true, features = ["derive"] }
|
||||
clap_complete = { workspace = true }
|
||||
codex-app-server = { workspace = true }
|
||||
codex-app-server-client = { workspace = true }
|
||||
codex-app-server-protocol = { workspace = true }
|
||||
codex-app-server-test-client = { workspace = true }
|
||||
codex-arg0 = { workspace = true }
|
||||
@@ -34,6 +35,7 @@ codex-core-plugins = { workspace = true }
|
||||
codex-exec = { workspace = true }
|
||||
codex-exec-server = { workspace = true }
|
||||
codex-execpolicy = { workspace = true }
|
||||
codex-feedback = { workspace = true }
|
||||
codex-features = { workspace = true }
|
||||
codex-login = { workspace = true }
|
||||
codex-memories-write = { workspace = true }
|
||||
|
||||
+240
-114
@@ -3,6 +3,26 @@ use clap::CommandFactory;
|
||||
use clap::Parser;
|
||||
use clap_complete::Shell;
|
||||
use clap_complete::generate;
|
||||
use codex_app_server_client::AppServerClient;
|
||||
use codex_app_server_client::DEFAULT_IN_PROCESS_CHANNEL_CAPACITY;
|
||||
use codex_app_server_client::EnvironmentManager;
|
||||
use codex_app_server_client::EnvironmentManagerArgs;
|
||||
use codex_app_server_client::ExecServerRuntimePaths;
|
||||
use codex_app_server_client::InProcessAppServerClient;
|
||||
use codex_app_server_client::InProcessClientStartArgs;
|
||||
use codex_app_server_client::RemoteAppServerClient;
|
||||
use codex_app_server_client::RemoteAppServerConnectArgs;
|
||||
use codex_app_server_protocol::ClientRequest;
|
||||
use codex_app_server_protocol::RequestId;
|
||||
use codex_app_server_protocol::WorktreeCreateParams;
|
||||
use codex_app_server_protocol::WorktreeCreateResponse;
|
||||
use codex_app_server_protocol::WorktreeDirtyPolicy as ApiWorktreeDirtyPolicy;
|
||||
use codex_app_server_protocol::WorktreeListParams;
|
||||
use codex_app_server_protocol::WorktreeListResponse;
|
||||
use codex_app_server_protocol::WorktreePruneParams;
|
||||
use codex_app_server_protocol::WorktreePruneResponse;
|
||||
use codex_app_server_protocol::WorktreeRemoveParams;
|
||||
use codex_app_server_protocol::WorktreeRemoveResponse;
|
||||
use codex_arg0::Arg0DispatchPaths;
|
||||
use codex_arg0::arg0_dispatch_or_else;
|
||||
use codex_chatgpt::apply_command::ApplyCommand;
|
||||
@@ -36,17 +56,12 @@ use codex_utils_absolute_path::AbsolutePathBuf;
|
||||
use codex_utils_cli::CliConfigOverrides;
|
||||
use codex_utils_cli::SharedCliOptions;
|
||||
use codex_utils_cli::WorktreeDirtyCliArg;
|
||||
use codex_worktree::DirtyPolicy;
|
||||
use codex_worktree::WorktreeInfo;
|
||||
use codex_worktree::WorktreeListQuery;
|
||||
use codex_worktree::WorktreeRemoveRequest;
|
||||
use codex_worktree::WorktreeRequest;
|
||||
use codex_worktree::WorktreeResolution;
|
||||
use owo_colors::OwoColorize;
|
||||
use std::fs;
|
||||
use std::io::IsTerminal;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use supports_color::Stream;
|
||||
|
||||
#[cfg(any(target_os = "macos", target_os = "windows"))]
|
||||
@@ -760,10 +775,11 @@ async fn run_debug_app_server_command(cmd: DebugAppServerCommand) -> anyhow::Res
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_worktree_options_for_shared_cli(
|
||||
async fn resolve_worktree_options_for_shared_cli(
|
||||
shared: &mut SharedCliOptions,
|
||||
remote: Option<&str>,
|
||||
remote_auth_token_env: Option<&str>,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
) -> anyhow::Result<Option<WorktreeResolution>> {
|
||||
let Some(branch) = shared.worktree.take() else {
|
||||
return Ok(None);
|
||||
@@ -773,15 +789,33 @@ fn resolve_worktree_options_for_shared_cli(
|
||||
anyhow::bail!("--worktree is not supported with remote app-server sessions yet");
|
||||
}
|
||||
|
||||
let codex_home = find_codex_home()?.to_path_buf();
|
||||
let source_cwd = shared.cwd.clone().unwrap_or(std::env::current_dir()?);
|
||||
let resolution = codex_worktree::ensure_worktree(WorktreeRequest {
|
||||
codex_home,
|
||||
source_cwd,
|
||||
branch,
|
||||
base_ref: shared.worktree_base.take(),
|
||||
dirty_policy: dirty_policy_from_cli(shared.worktree_dirty),
|
||||
})?;
|
||||
let client = worktree_app_server_client(
|
||||
/*remote*/ None, /*remote_auth_token_env*/ None, arg0_paths,
|
||||
)
|
||||
.await?;
|
||||
let response: WorktreeCreateResponse = client
|
||||
.request_typed(ClientRequest::WorktreeCreate {
|
||||
request_id: RequestId::Integer(1),
|
||||
params: WorktreeCreateParams {
|
||||
cwd: Some(source_cwd.to_string_lossy().to_string()),
|
||||
branch,
|
||||
base_ref: shared.worktree_base.take(),
|
||||
dirty_policy: api_dirty_policy_from_cli(shared.worktree_dirty),
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
let resolution = WorktreeResolution {
|
||||
reused: response.reused,
|
||||
info: worktree_info_from_api(response.info)?,
|
||||
warnings: response
|
||||
.warnings
|
||||
.into_iter()
|
||||
.map(|warning| codex_worktree::WorktreeWarning {
|
||||
message: warning.message,
|
||||
})
|
||||
.collect(),
|
||||
};
|
||||
shared.cwd = Some(resolution.info.workspace_cwd.clone());
|
||||
|
||||
#[allow(clippy::print_stderr)]
|
||||
@@ -792,70 +826,79 @@ fn resolve_worktree_options_for_shared_cli(
|
||||
Ok(Some(resolution))
|
||||
}
|
||||
|
||||
fn dirty_policy_from_cli(arg: WorktreeDirtyCliArg) -> DirtyPolicy {
|
||||
match arg {
|
||||
WorktreeDirtyCliArg::Fail => DirtyPolicy::Fail,
|
||||
WorktreeDirtyCliArg::Ignore => DirtyPolicy::Ignore,
|
||||
WorktreeDirtyCliArg::CopyTracked => DirtyPolicy::CopyTracked,
|
||||
WorktreeDirtyCliArg::CopyAll => DirtyPolicy::CopyAll,
|
||||
WorktreeDirtyCliArg::MoveTracked => DirtyPolicy::MoveTracked,
|
||||
WorktreeDirtyCliArg::MoveAll => DirtyPolicy::MoveAll,
|
||||
}
|
||||
}
|
||||
|
||||
fn run_worktree_command(cli: WorktreeCli) -> anyhow::Result<()> {
|
||||
let codex_home = find_codex_home()?.to_path_buf();
|
||||
async fn run_worktree_command(
|
||||
cli: WorktreeCli,
|
||||
remote: Option<String>,
|
||||
remote_auth_token_env: Option<String>,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
) -> anyhow::Result<()> {
|
||||
let is_remote = remote.is_some();
|
||||
let client = worktree_app_server_client(remote, remote_auth_token_env, arg0_paths).await?;
|
||||
let cwd = (!is_remote)
|
||||
.then(std::env::current_dir)
|
||||
.transpose()?
|
||||
.map(|cwd| cwd.to_string_lossy().to_string());
|
||||
let mut next_request_id = 1_i64;
|
||||
match cli.subcommand {
|
||||
WorktreeSubcommand::Create(command) => {
|
||||
let resolution = codex_worktree::ensure_worktree(WorktreeRequest {
|
||||
codex_home,
|
||||
source_cwd: std::env::current_dir()?,
|
||||
branch: command.branch,
|
||||
base_ref: command.base_ref,
|
||||
dirty_policy: dirty_policy_from_cli(command.dirty),
|
||||
})?;
|
||||
let resolution: WorktreeCreateResponse = client
|
||||
.request_typed(ClientRequest::WorktreeCreate {
|
||||
request_id: next_cli_request_id(&mut next_request_id),
|
||||
params: WorktreeCreateParams {
|
||||
cwd: cwd.clone(),
|
||||
branch: command.branch,
|
||||
base_ref: command.base_ref,
|
||||
dirty_policy: api_dirty_policy_from_cli(command.dirty),
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
for warning in &resolution.warnings {
|
||||
eprintln!("warning: {}", warning.message);
|
||||
}
|
||||
println!("{}", resolution.info.workspace_cwd.display());
|
||||
println!("{}", resolution.info.workspace_cwd);
|
||||
}
|
||||
WorktreeSubcommand::List(command) => {
|
||||
let source_cwd = if command.all {
|
||||
None
|
||||
} else {
|
||||
Some(std::env::current_dir()?)
|
||||
};
|
||||
let entries = codex_worktree::list_worktrees(WorktreeListQuery {
|
||||
codex_home,
|
||||
source_cwd,
|
||||
include_all_repos: command.all,
|
||||
})?;
|
||||
let entries =
|
||||
cli_list_worktrees(&client, cwd.clone(), command.all, &mut next_request_id).await?;
|
||||
print_worktree_list(entries, command.json)?;
|
||||
}
|
||||
WorktreeSubcommand::Path(command) => {
|
||||
let entries = codex_worktree::list_worktrees(WorktreeListQuery {
|
||||
codex_home,
|
||||
source_cwd: Some(std::env::current_dir()?),
|
||||
include_all_repos: false,
|
||||
})?;
|
||||
let entries =
|
||||
cli_list_worktrees(&client, cwd.clone(), false, &mut next_request_id).await?;
|
||||
let entry = find_named_worktree(entries, &command.name)?;
|
||||
println!("{}", entry.workspace_cwd.display());
|
||||
}
|
||||
WorktreeSubcommand::Remove(command) => {
|
||||
let result = codex_worktree::remove_worktree(WorktreeRemoveRequest {
|
||||
codex_home,
|
||||
source_cwd: Some(std::env::current_dir()?),
|
||||
name_or_path: command.name_or_path,
|
||||
force: command.force,
|
||||
delete_branch: command.delete_branch,
|
||||
})?;
|
||||
println!("removed {}", result.removed_path.display());
|
||||
let result: WorktreeRemoveResponse = client
|
||||
.request_typed(ClientRequest::WorktreeRemove {
|
||||
request_id: next_cli_request_id(&mut next_request_id),
|
||||
params: WorktreeRemoveParams {
|
||||
cwd,
|
||||
name_or_path: command.name_or_path,
|
||||
force: command.force,
|
||||
delete_branch: command.delete_branch,
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
println!("removed {}", result.removed_path);
|
||||
if let Some(branch) = result.deleted_branch {
|
||||
println!("deleted branch {branch}");
|
||||
}
|
||||
}
|
||||
WorktreeSubcommand::Prune(command) => {
|
||||
let stale_paths = stale_managed_worktree_dirs(&codex_home)?;
|
||||
let response: WorktreePruneResponse = client
|
||||
.request_typed(ClientRequest::WorktreePrune {
|
||||
request_id: next_cli_request_id(&mut next_request_id),
|
||||
params: WorktreePruneParams {
|
||||
dry_run: command.dry_run || command.json,
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
let stale_paths = response
|
||||
.paths
|
||||
.into_iter()
|
||||
.map(PathBuf::from)
|
||||
.collect::<Vec<_>>();
|
||||
if command.json {
|
||||
println!("{}", serde_json::to_string_pretty(&stale_paths)?);
|
||||
} else if stale_paths.is_empty() {
|
||||
@@ -865,7 +908,6 @@ fn run_worktree_command(cli: WorktreeCli) -> anyhow::Result<()> {
|
||||
if command.dry_run {
|
||||
println!("would remove {}", path.display());
|
||||
} else {
|
||||
fs::remove_dir_all(path)?;
|
||||
println!("removed {}", path.display());
|
||||
}
|
||||
}
|
||||
@@ -875,6 +917,133 @@ fn run_worktree_command(cli: WorktreeCli) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn cli_list_worktrees(
|
||||
client: &AppServerClient,
|
||||
cwd: Option<String>,
|
||||
all: bool,
|
||||
next_request_id: &mut i64,
|
||||
) -> anyhow::Result<Vec<WorktreeInfo>> {
|
||||
let response: WorktreeListResponse = client
|
||||
.request_typed(ClientRequest::WorktreeList {
|
||||
request_id: next_cli_request_id(next_request_id),
|
||||
params: WorktreeListParams { cwd, all },
|
||||
})
|
||||
.await?;
|
||||
response
|
||||
.data
|
||||
.into_iter()
|
||||
.map(worktree_info_from_api)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn next_cli_request_id(next: &mut i64) -> RequestId {
|
||||
let request_id = RequestId::Integer(*next);
|
||||
*next += 1;
|
||||
request_id
|
||||
}
|
||||
|
||||
fn api_dirty_policy_from_cli(value: WorktreeDirtyCliArg) -> ApiWorktreeDirtyPolicy {
|
||||
match value {
|
||||
WorktreeDirtyCliArg::Fail => ApiWorktreeDirtyPolicy::Fail,
|
||||
WorktreeDirtyCliArg::Ignore => ApiWorktreeDirtyPolicy::Ignore,
|
||||
WorktreeDirtyCliArg::CopyTracked => ApiWorktreeDirtyPolicy::CopyTracked,
|
||||
WorktreeDirtyCliArg::CopyAll => ApiWorktreeDirtyPolicy::CopyAll,
|
||||
WorktreeDirtyCliArg::MoveTracked => ApiWorktreeDirtyPolicy::MoveTracked,
|
||||
WorktreeDirtyCliArg::MoveAll => ApiWorktreeDirtyPolicy::MoveAll,
|
||||
}
|
||||
}
|
||||
|
||||
async fn worktree_app_server_client(
|
||||
remote: Option<String>,
|
||||
remote_auth_token_env: Option<String>,
|
||||
arg0_paths: Arg0DispatchPaths,
|
||||
) -> anyhow::Result<AppServerClient> {
|
||||
if let Some(remote) = remote {
|
||||
let websocket_url =
|
||||
codex_tui::normalize_remote_addr(&remote).map_err(|err| anyhow::anyhow!("{err}"))?;
|
||||
let auth_token = remote_auth_token_env
|
||||
.map(|name| std::env::var(&name))
|
||||
.transpose()?;
|
||||
return Ok(AppServerClient::Remote(
|
||||
RemoteAppServerClient::connect(RemoteAppServerConnectArgs {
|
||||
websocket_url,
|
||||
auth_token,
|
||||
client_name: "codex-cli-worktree".to_string(),
|
||||
client_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
experimental_api: true,
|
||||
opt_out_notification_methods: Vec::new(),
|
||||
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
|
||||
})
|
||||
.await?,
|
||||
));
|
||||
}
|
||||
|
||||
let config = Config::load_with_cli_overrides(Vec::new()).await?;
|
||||
let local_runtime_paths = ExecServerRuntimePaths::from_optional_paths(
|
||||
arg0_paths.codex_self_exe.clone(),
|
||||
arg0_paths.codex_linux_sandbox_exe.clone(),
|
||||
)?;
|
||||
let config_warnings = config
|
||||
.startup_warnings
|
||||
.iter()
|
||||
.map(
|
||||
|warning| codex_app_server_protocol::ConfigWarningNotification {
|
||||
summary: warning.clone(),
|
||||
details: None,
|
||||
path: None,
|
||||
range: None,
|
||||
},
|
||||
)
|
||||
.collect();
|
||||
Ok(AppServerClient::InProcess(
|
||||
InProcessAppServerClient::start(InProcessClientStartArgs {
|
||||
arg0_paths,
|
||||
config: Arc::new(config),
|
||||
cli_overrides: Vec::new(),
|
||||
loader_overrides: codex_config::LoaderOverrides::default(),
|
||||
cloud_requirements: codex_config::CloudRequirementsLoader::default(),
|
||||
feedback: codex_feedback::CodexFeedback::new(),
|
||||
log_db: None,
|
||||
state_db: None,
|
||||
environment_manager: Arc::new(
|
||||
EnvironmentManager::new(EnvironmentManagerArgs::new(local_runtime_paths)).await,
|
||||
),
|
||||
config_warnings,
|
||||
session_source: codex_protocol::protocol::SessionSource::Cli,
|
||||
enable_codex_api_key_env: false,
|
||||
client_name: "codex-cli-worktree".to_string(),
|
||||
client_version: env!("CARGO_PKG_VERSION").to_string(),
|
||||
experimental_api: true,
|
||||
opt_out_notification_methods: Vec::new(),
|
||||
channel_capacity: DEFAULT_IN_PROCESS_CHANNEL_CAPACITY,
|
||||
})
|
||||
.await?,
|
||||
))
|
||||
}
|
||||
|
||||
fn worktree_info_from_api(
|
||||
info: codex_app_server_protocol::WorktreeInfo,
|
||||
) -> anyhow::Result<WorktreeInfo> {
|
||||
Ok(WorktreeInfo {
|
||||
id: info.id,
|
||||
name: info.name,
|
||||
slug: info.slug,
|
||||
source: serde_json::from_value(serde_json::to_value(info.source)?)?,
|
||||
location: serde_json::from_value(serde_json::to_value(info.location)?)?,
|
||||
repo_name: info.repo_name,
|
||||
repo_root: PathBuf::from(info.repo_root),
|
||||
common_git_dir: PathBuf::from(info.common_git_dir),
|
||||
worktree_git_root: PathBuf::from(info.worktree_git_root),
|
||||
workspace_cwd: PathBuf::from(info.workspace_cwd),
|
||||
original_relative_cwd: PathBuf::from(info.original_relative_cwd),
|
||||
branch: info.branch,
|
||||
head: info.head,
|
||||
owner_thread_id: info.owner_thread_id,
|
||||
metadata_path: PathBuf::from(info.metadata_path),
|
||||
dirty: serde_json::from_value(serde_json::to_value(info.dirty)?)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn print_worktree_list(entries: Vec<WorktreeInfo>, json: bool) -> anyhow::Result<()> {
|
||||
if json {
|
||||
println!("{}", serde_json::to_string_pretty(&entries)?);
|
||||
@@ -959,52 +1128,6 @@ fn find_named_worktree(entries: Vec<WorktreeInfo>, name: &str) -> anyhow::Result
|
||||
}
|
||||
}
|
||||
|
||||
fn stale_managed_worktree_dirs(codex_home: &Path) -> anyhow::Result<Vec<PathBuf>> {
|
||||
let root = codex_worktree::codex_worktrees_root(codex_home);
|
||||
if !root.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
|
||||
let mut stale = Vec::new();
|
||||
for repo_dir in fs::read_dir(&root)? {
|
||||
let repo_dir = repo_dir?;
|
||||
if !repo_dir.file_type()?.is_dir() {
|
||||
continue;
|
||||
}
|
||||
for slug_dir in fs::read_dir(repo_dir.path())? {
|
||||
let slug_dir = slug_dir?;
|
||||
if !slug_dir.file_type()?.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let mut has_repo_dir = false;
|
||||
for repo_root in fs::read_dir(slug_dir.path())? {
|
||||
let repo_root = repo_root?;
|
||||
if !repo_root.file_type()?.is_dir() {
|
||||
continue;
|
||||
}
|
||||
has_repo_dir = true;
|
||||
if !repo_root.path().join(".git").exists() || !git_root_is_valid(&repo_root.path())
|
||||
{
|
||||
stale.push(repo_root.path());
|
||||
}
|
||||
}
|
||||
if !has_repo_dir {
|
||||
stale.push(slug_dir.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
stale.sort();
|
||||
Ok(stale)
|
||||
}
|
||||
|
||||
fn git_root_is_valid(path: &Path) -> bool {
|
||||
std::process::Command::new("git")
|
||||
.args(["rev-parse", "--show-toplevel"])
|
||||
.current_dir(path)
|
||||
.output()
|
||||
.is_ok_and(|output| output.status.success())
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Parser, Clone)]
|
||||
struct FeatureToggles {
|
||||
/// Enable a feature (repeatable). Equivalent to `-c features.<name>=true`.
|
||||
@@ -1135,7 +1258,9 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
|
||||
&mut exec_cli.shared,
|
||||
/*remote*/ None,
|
||||
/*remote_auth_token_env*/ None,
|
||||
)?;
|
||||
arg0_paths.clone(),
|
||||
)
|
||||
.await?;
|
||||
prepend_config_flags(
|
||||
&mut exec_cli.config_overrides,
|
||||
root_config_overrides.clone(),
|
||||
@@ -1324,12 +1449,13 @@ async fn cli_main(arg0_paths: Arg0DispatchPaths) -> anyhow::Result<()> {
|
||||
handle_app_exit(exit_info)?;
|
||||
}
|
||||
Some(Subcommand::Worktree(worktree_cli)) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
root_remote.as_deref(),
|
||||
root_remote_auth_token_env.as_deref(),
|
||||
"worktree",
|
||||
)?;
|
||||
run_worktree_command(worktree_cli)?;
|
||||
run_worktree_command(
|
||||
worktree_cli,
|
||||
root_remote.clone(),
|
||||
root_remote_auth_token_env.clone(),
|
||||
arg0_paths.clone(),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
Some(Subcommand::Login(mut login_cli)) => {
|
||||
reject_remote_mode_for_subcommand(
|
||||
|
||||
@@ -330,6 +330,7 @@ impl App {
|
||||
request_id: worktree_request_id("worktree-list"),
|
||||
params: WorktreeListParams {
|
||||
cwd: Some(self.session_workspace_cwd(app_server).display().to_string()),
|
||||
all: false,
|
||||
},
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -16,6 +16,7 @@ pub use manager::ensure_worktree;
|
||||
pub use manager::list_worktrees;
|
||||
pub use manager::remove_worktree;
|
||||
pub use manager::resolve_worktree;
|
||||
pub use manager::stale_managed_worktree_dirs;
|
||||
pub use metadata::WorktreeMetadata;
|
||||
pub use metadata::WorktreeThreadMetadata;
|
||||
pub use metadata::bind_thread;
|
||||
|
||||
@@ -309,6 +309,51 @@ fn is_git_root(path: &Path) -> bool {
|
||||
path.join(".git").exists()
|
||||
}
|
||||
|
||||
pub fn stale_managed_worktree_dirs(codex_home: &Path) -> Result<Vec<PathBuf>> {
|
||||
let root = paths::codex_worktrees_root(codex_home);
|
||||
if !root.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let mut stale = Vec::new();
|
||||
for repo_dir in fs::read_dir(&root)? {
|
||||
let repo_dir = repo_dir?;
|
||||
if !repo_dir.file_type()?.is_dir() {
|
||||
continue;
|
||||
}
|
||||
for slug_dir in fs::read_dir(repo_dir.path())? {
|
||||
let slug_dir = slug_dir?;
|
||||
if !slug_dir.file_type()?.is_dir() {
|
||||
continue;
|
||||
}
|
||||
let mut has_repo_dir = false;
|
||||
for repo_root in fs::read_dir(slug_dir.path())? {
|
||||
let repo_root = repo_root?;
|
||||
if !repo_root.file_type()?.is_dir() {
|
||||
continue;
|
||||
}
|
||||
has_repo_dir = true;
|
||||
if !repo_root.path().join(".git").exists() || !git_root_is_valid(&repo_root.path())
|
||||
{
|
||||
stale.push(repo_root.path());
|
||||
}
|
||||
}
|
||||
if !has_repo_dir {
|
||||
stale.push(slug_dir.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
stale.sort();
|
||||
Ok(stale)
|
||||
}
|
||||
|
||||
fn git_root_is_valid(path: &Path) -> bool {
|
||||
std::process::Command::new("git")
|
||||
.args(["rev-parse", "--show-toplevel"])
|
||||
.current_dir(path)
|
||||
.output()
|
||||
.is_ok_and(|output| output.status.success())
|
||||
}
|
||||
|
||||
fn worktree_matches_repo(info: &WorktreeInfo, repo: &SourceRepo) -> bool {
|
||||
info.id == repo.id || paths_match(&info.common_git_dir, &repo.common_git_dir)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user