Include linked worktrees in TUI session discovery (#43279)

## Why

Directory-scoped session lookup misses conversations in linked worktrees of the same repository. Managed worktree creation also runs synchronous Git work on the TUI event loop.

## What changed

- With `worktrees` enabled for local sessions, include corresponding directories across linked checkouts in resume and fork pickers and `--last` lookup. Group them together in the agents overview and show checkout paths for picker entries from another worktree.
- Validate shared Git metadata and backlinks, preserve relative working directories and logical path aliases, and reject directory symlink escapes. Keep the expanded directory filter stable across pagination until the listing restarts.
- Fall back to the originally requested directory when an older daemon rejects an array-valued `cwd` filter.
- Create managed worktrees on a blocking worker, check transition blockers before allocation, and revalidate the source session before switching. Report retained checkout paths and cleanup instructions if the transition cannot complete.
- Start the in-session picker server in a separate task to avoid exhausting the TUI event future's stack.

## Testing

Add coverage for linked-checkout discovery, feature gating, picker selection and rendering, project grouping, pagination stability, and legacy daemon fallback. Extend worktree lifecycle tests to cover running-agent blockers and recovery after the source session changes during creation.

GitOrigin-RevId: 4a8a36c0dba3d32d72600f2edf8258a29fb4cb07
This commit is contained in:
Benjamin Carlsson authored and copyberry committed 2026-09-06 20:52:29 +00:00
1 parent ad931a45b2
commit d30f9cc72a
27 files changed
+1511 -144

No files matched your search

@@ -0,0 +1,41 @@
//! Session listing preserves grouped filters while tolerating older single-CWD daemons.
use super::*;
use codex_app_server_protocol::ThreadListCwdFilter;
impl AppServerSession {
pub(crate) async fn thread_list(
&mut self,
mut params: ThreadListParams,
) -> Result<ThreadListResponse> {
loop {
let request_id = self.next_request_id();
let response = self
.client
.request_typed(ClientRequest::ThreadList {
request_id,
params: params.clone(),
})
.await;
if let Err(TypedRequestError::Server { source, .. }) = &response
&& matches!(
source.code,
JSONRPC_INVALID_REQUEST | JSONRPC_INVALID_PARAMS
)
&& source.message.contains("invalid type: sequence")
&& source.message.contains("expected a string")
&& let Some(ThreadListCwdFilter::Many(cwds)) = &params.cwd
&& let Some(cwd) = cwds.first()
{
// Repository discovery puts the originally requested CWD first.
params.cwd = Some(ThreadListCwdFilter::One(cwd.clone()));
continue;
}
return response.wrap_err("thread/list failed during TUI session lookup");
}
}
}
#[cfg(test)]
#[path = "thread_list_tests.rs"]
mod tests;
@@ -0,0 +1,77 @@
//! Public-RPC compatibility keeps modern grouping and narrows only legacy array errors.
use super::*;
use codex_app_server_protocol::JSONRPCMessage;
use futures::SinkExt;
use futures::StreamExt;
use pretty_assertions::assert_eq;
use serde_json::json;
use tokio::net::TcpListener;
use tokio_tungstenite::tungstenite::Message;
#[tokio::test]
async fn thread_list_preserves_filters_and_retries_only_legacy_cwd_errors() -> Result<()> {
let legacy_message = "invalid type: sequence, expected a string";
for (code, message, retry) in [
(0, "", false),
(-32600, legacy_message, true),
(-32602, legacy_message, true),
(-32603, legacy_message, false),
(-32602, "invalid cursor", false),
] {
let listener = TcpListener::bind("127.0.0.1:0").await?;
let endpoint = crate::resolve_remote_addr(&format!("ws://{}", listener.local_addr()?))?;
let server = tokio::spawn(async move {
let (stream, _) = listener.accept().await?;
let mut socket = tokio_tungstenite::accept_async(stream).await?;
let mut requests = Vec::new();
while let Some(Ok(Message::Text(text))) = socket.next().await {
let JSONRPCMessage::Request(request) = serde_json::from_str(&text)? else {
continue;
};
let mut reply = match request.method.as_str() {
"initialize" => json!({"result": {"userAgent": "thread-list-test/1.0"}}),
"thread/list" => {
requests.push(request.params.unwrap());
if code != 0 && requests.len() == 1 {
json!({"error": {"code": code, "message": message}})
} else {
json!({"result": {"data": [], "nextCursor": "next"}})
}
}
method => panic!("unexpected request: {method}"),
};
reply["id"] = json!(request.id);
socket.send(Message::Text(reply.to_string().into())).await?;
}
Ok::<_, color_eyre::Report>(requests)
});
let params: ThreadListParams = serde_json::from_value(json!({
"cwd": ["/requested/nested", "/linked/nested"], "cursor": "cursor", "limit": 3,
"sortKey": "created_at", "modelProviders": ["provider"], "archived": true,
"searchTerm": "needle"
}))?;
let mut expected = vec![serde_json::to_value(&params)?];
if retry {
let mut fallback = expected[0].clone();
fallback["cwd"] = json!("/requested/nested");
expected.push(fallback);
}
let mut session = AppServerSession::new(
crate::connect_remote_app_server(endpoint).await?,
ThreadParamsMode::Embedded,
);
let result = session.thread_list(params).await;
if code == 0 || retry {
assert_eq!(
serde_json::to_value(result?)?,
json!({"data": [], "nextCursor": "next", "backwardsCursor": null})
);
} else {
assert!(format!("{:#}", result.unwrap_err()).contains(message));
}
session.shutdown().await?;
assert_eq!(server.await??, expected);
}
Ok(())
}