diff --git a/FORK.md b/FORK.md index 26c0a7b7639..1386deb2599 100644 --- a/FORK.md +++ b/FORK.md @@ -11,6 +11,10 @@ before changing anything outside the agent crates. ## What is where +Experimental Codex Desktop context and its native command contract are documented in +[docs/codex-desktop.md](docs/codex-desktop.md). The application changes remain in the fork's +agent crates and native startup; launchers and routing are a companion AItoCraft example. + | Path | What | Upstream? | | --- | --- | --- | | `crates/agent/` (`gridcraft-agent`) | The layer: data model, anchors, storage in the `.xlsx`, `agent.*` commands, privacy masking, trace, sensitivity, alternatives and calculation methods (`variants.rs`), worst and best combinations and the risk matrix (`stress.rs`), safe file mode (`safe.rs`), Excel → slide links (`links.rs`), the in-app MCP server | fork only | diff --git a/apps/gridcraft/src/agent.rs b/apps/gridcraft/src/agent.rs index 5094285bffd..882f3325139 100644 --- a/apps/gridcraft/src/agent.rs +++ b/apps/gridcraft/src/agent.rs @@ -71,6 +71,9 @@ pub fn control_port(agent: Option, control: Option) -> Option { pub fn start(agent: Option, control: Option) { let (Some(port), Some(control)) = (agent, control) else { return }; gridcraft_agent_ui::install(); + if gridcraft_agent::context::codex_enabled() { + gridcraft_agent::context::persist(false); + } if !MODE_FROM_FLAG.load(std::sync::atomic::Ordering::Relaxed) { gridcraft_agent::runner::load_saved_mode(); // What a new document's agent knows: the last choice made in the app. diff --git a/crates/agent-ui/src/context.rs b/crates/agent-ui/src/context.rs index 6d672baba60..c058671d873 100644 --- a/crates/agent-ui/src/context.rs +++ b/crates/agent-ui/src/context.rs @@ -21,11 +21,13 @@ pub(crate) enum Step { InstallCode, AskSession, ChooseFolder, + CheckCodex, } impl Step { pub(crate) fn label(self) -> &'static str { match self { + Step::CheckCodex => "Connect Codex", Step::LogIn => "Log in to Claude", Step::InstallDesktop | Step::InstallCode => "Install AItoCraft", Step::AskCowork => "Ask Cowork to collaborate", @@ -35,6 +37,7 @@ impl Step { } pub(crate) fn tip(self) -> &'static str { match self { + Step::CheckCodex => "Connects every open and new document to the shared Codex Desktop server.", Step::LogIn => "Opens a terminal with `claude auth login`", Step::InstallDesktop => "Adds AItoCraft to Claude Desktop, where Cowork runs: one connection for every Craft app", Step::AskCowork => "Copies the phrase for Claude: paste it into your Cowork chat", @@ -109,6 +112,7 @@ pub(crate) struct View { pub steps: Vec<(Step, bool)>, /// The chosen project folder, when it's there. pub folder: Option, + pub route: Option, } impl View { @@ -173,6 +177,17 @@ pub(crate) fn view( let (l, d) = background(if c.web { " It may also search and read the web." } else { " It sees only this document." }); (l, d, login.into_iter().collect()) } + (ContextKind::Codex, _) => { + // Old answers never prove a live connection: only this document's listener does. + let ready = matches!(presence, Presence::Listening { seen_ms, .. } if *seen_ms < 15_000); + let lamp = if ready { Lamp::Ready } else { Lamp::NotReady }; + let detail = if ready { + "Codex Desktop is connected to this document. Ask a question; edits arrive as proposals." + } else { + "Codex is disconnected. Click Connect Codex to reconnect, or restart the Codex GridCraft launcher." + }; + (lamp, detail.to_string(), if ready { vec![] } else { vec![(Step::CheckCodex, false)] }) + } (ContextKind::Cowork, _) => { let (l, d) = listening("Your Cowork chat"); let asked = copied(Step::AskCowork) || l == Lamp::Ready; @@ -211,7 +226,23 @@ pub(crate) fn view( None => (lamp, lamp.label().to_string(), None, detail), }; let detail = format!("{detail}\n\nGridCraft's MCP server: {server}"); - View { ctx: c.clone(), lamp, label, topic, detail, steps, folder } + View { ctx: c.clone(), lamp, label, topic, detail, steps, folder, route: None } +} + +/// Readiness in the Codex edition follows the persistent queue consumer, not a cached ping +/// or an ephemeral model session that has already exited. +fn connection(s: &gridcraft_engine::Session, c: &AgentContext, now: u64) -> Presence { + if c.kind != ContextKind::Codex { + return runner::presence(s); + } + let Some(d) = s.active() else { return Presence::Nobody }; + let listener = gridcraft_agent::docs::listeners(d.uid) + .into_iter() + .find(|l| l.label.starts_with("Codex desktop bridge ·") && now.saturating_sub(l.last_seen) < 15_000); + match listener { + Some(l) => Presence::Listening { label: l.label, seen_ms: now.saturating_sub(l.last_seen), more: 0 }, + None => Presence::Nobody, + } } /// The active document's group. @@ -219,14 +250,60 @@ pub(crate) fn current(st: &AgentUi, app: &SheetApp) -> Option { let d = app.session.active()?; let c = cx::effective(&layer::get(d)); let setup = cx::setup(); - let presence = runner::presence(&app.session); let now = gridcraft_agent::now_ms(); + let presence = connection(&app.session, &c, now); let waiting = st.context.waiting.get(&d.uid).is_some_and(|t| now.saturating_sub(*t) < WAIT_MS); let uid = d.uid; let copied = |s: Step| st.context.copied.contains(&(uid, s)); let w = working(d, now); let answered = answered_recently(d, now); - Some(view(&c, &setup, &presence, waiting, &copied, crate::server_url().unwrap_or("http://127.0.0.1:7980/mcp"), w.as_ref(), answered)) + let mut v = view(&c, &setup, &presence, waiting, &copied, crate::server_url().unwrap_or("http://127.0.0.1:7980/mcp"), w.as_ref(), answered); + if c.kind == ContextKind::Codex { + v.route = cx::codex_route_for(uid); + if let Some(r) = &v.route { + v.detail = format!("{}\n\nИсходный чат: {}\n{}", r.detail, c.codex_thread_title, v.detail); + if r.status == "disconnected" { + v.lamp = Lamp::NotReady; + v.label = "Codex отключён".into(); + } else if v.lamp != Lamp::Working { + match r.status.as_str() { + "attention" => { + v.lamp = Lamp::Waiting; + v.label = "Проверьте доставку".into(); + } + "missing" => { + v.lamp = Lamp::Waiting; + v.label = "Исходный чат недоступен".into(); + } + "linkMissing" => { + v.lamp = Lamp::Waiting; + v.label = "Чат из ссылки недоступен".into(); + } + "linked" => { + v.label = "Чат по ссылке".into(); + } + "fallback" => { + v.lamp = Lamp::Ready; + v.label = "Другой чат".into(); + } + "queued" => { + v.lamp = Lamp::Waiting; + v.label = "Вопрос доставлен в чат".into(); + } + "fresh" => { + v.lamp = Lamp::Ready; + v.label = if c.codex_thread_id.is_empty() { "Новый чат" } else { "Другой чат" }.into(); + } + "unbound" => { + v.lamp = Lamp::Ready; + v.label = "Новый чат по вопросу".into(); + } + _ => {} + } + } + } + } + Some(v) } /// The agent answered a question of this document lately: after its work the lamp says Ready. @@ -282,7 +359,7 @@ pub(crate) fn frame(st: &mut AgentUi, app: &mut SheetApp, ctx: &egui::Context) { let l = layer::get(d); let c = cx::effective(&l); let now = gridcraft_agent::now_ms(); - let presence = runner::presence(&app.session); + let presence = connection(&app.session, &c, now); if listener_ready(&presence) { st.context.waiting.remove(&uid); } @@ -294,7 +371,7 @@ pub(crate) fn frame(st: &mut AgentUi, app: &mut SheetApp, ctx: &egui::Context) { ctx.request_repaint_after(std::time::Duration::from_secs(2)); } // Cowork and my session: something listens but hasn't answered for this document yet. - let listens = matches!(c.kind, ContextKind::Cowork) || (c.kind == ContextKind::Code && c.via == CodeVia::Session); + let listens = matches!(c.kind, ContextKind::Cowork | ContextKind::Codex) || (c.kind == ContextKind::Code && c.via == CodeVia::Session); if listens && !gridcraft_agent::read_only() { let quiet = runner::classify(None, &runner::signals(uid), runner::mode(), now); let unsure = matches!(quiet, Presence::Listener(_)) && !listener_ready(&presence) && !matches!(presence, Presence::Checking { .. }); @@ -319,6 +396,12 @@ pub(crate) fn run(st: &mut AgentUi, app: &mut SheetApp, ctx: &egui::Context, ste st.context.waiting.insert(uid, now); }; match step { + Step::CheckCodex => { + wait(st); + if let Err(e) = app.run("agent.codexConnect", json!({})) { + app.message = Some(("Codex".into(), e.to_string())); + } + } Step::LogIn => match cx::log_in() { Ok(()) => wait(st), Err(e) => app.message = Some(("Log in to Claude".into(), e)), @@ -521,3 +604,23 @@ mod tests { assert!(working(s.active().unwrap(), now() + 11_000).is_none()); } } + +#[cfg(test)] +mod codex_tests { + use super::*; + + #[test] + fn codex_requires_a_live_document_listener_even_after_an_old_answer() { + let c = AgentContext { kind: ContextKind::Codex, ..AgentContext::default() }; + let v = view(&c, &Setup::default(), &Presence::Nobody, true, &|_| false, "url", None, true); + assert_eq!(v.lamp, Lamp::NotReady); + assert_eq!(v.next(), Some(Step::CheckCodex)); + assert!(!v.detail.contains("Claude")); + let stale_ping = Presence::Answering { checked_ms: 0, latency_ms: 10 }; + assert_eq!(view(&c, &Setup::default(), &stale_ping, false, &|_| false, "url", None, true).lamp, Lamp::NotReady); + let p = Presence::Listening { label: "Codex".into(), seen_ms: 0, more: 0 }; + let v = view(&c, &Setup::default(), &p, false, &|_| false, "url", None, false); + assert_eq!(v.lamp, Lamp::Ready); + assert!(v.steps.is_empty()); + } +} diff --git a/crates/agent-ui/src/ribbon.rs b/crates/agent-ui/src/ribbon.rs index a1a3fc2e5ec..a187544b279 100644 --- a/crates/agent-ui/src/ribbon.rs +++ b/crates/agent-ui/src/ribbon.rs @@ -471,7 +471,12 @@ fn context_group(st: &AgentUi, app: &SheetApp, ui: &mut Ui, t: &Tokens, p: &crat let (name, line, _) = kind.label(); let r = mode_button(ui, kind, lamp, &format!("What the agent knows about this document: {name}. {line}")); egui::Popup::menu(&r).show(|ui| { - for k in [ContextKind::None, ContextKind::Cowork, ContextKind::Code] { + let choices: &[ContextKind] = if gridcraft_agent::context::codex_enabled() { + &[ContextKind::Codex, ContextKind::Off] + } else { + &[ContextKind::None, ContextKind::Cowork, ContextKind::Code, ContextKind::Codex] + }; + for &k in choices { if mode_row(ui, k, k == kind).clicked() { if k != kind { acts.push(Act::Run("agent.agentContext", json!({"kind": k.id()}))); @@ -509,12 +514,35 @@ fn context_group(st: &AgentUi, app: &SheetApp, ui: &mut Ui, t: &Tokens, p: &crat { acts.push(Act::Topic(t.clone())); } + if kind == ContextKind::Codex { + let route = v.route.as_ref(); + let id = route.map(|r| r.thread_id.as_str()).filter(|id| !id.is_empty()).unwrap_or(&v.ctx.codex_thread_id); + let title = route.map(|r| r.title.as_str()).filter(|s| !s.is_empty()).unwrap_or(&v.ctx.codex_thread_title); + let mismatch = route.is_some_and(|r| r.status == "fallback" || r.status == "fresh" && !v.ctx.codex_thread_id.is_empty()); + let hint = if mismatch { + format!("Другой чат: {title}") + } else if id.is_empty() { + "Исходный чат не задан".into() + } else { + format!("Чат: {title}") + }; + ui.add( + egui::Label::new(egui::RichText::new(&hint).font(theme::ui_font(10.0)).color(if mismatch { p.open } else { t.text_dim })).truncate(), + ) + .on_hover_text(format!("{hint}\n{id}\n{}", v.detail)); + if !id.is_empty() + && row_button(ui, Icon::Right, "Открыть чат", "Открыть фактический чат этого документа в Codex Desktop", false).clicked() + { + acts.push(Act::Run("agent.codexOpenChat", json!({}))); + } + } if !v.steps.is_empty() { ui.horizontal(|ui| { ui.spacing_mut().item_spacing.x = 0.0; let next = v.next(); let tip = next.map_or(String::new(), |s| format!("Next: {}. {}", s.label(), s.tip())); - if row_button(ui, Icon::Right, "Get ready", &tip, false).clicked() + let action_label = if kind == ContextKind::Codex { "Connect Codex" } else { "Get ready" }; + if row_button(ui, Icon::Right, action_label, &tip, false).clicked() && let Some(s) = next { acts.push(Act::Step(s)); @@ -563,6 +591,7 @@ fn mode_button(ui: &mut Ui, kind: gridcraft_agent::layer::ContextKind, lamp: Col ContextKind::None => "No\ncontext", ContextKind::Cowork => "Claude\nCowork", ContextKind::Code => "Claude\nCode", + ContextKind::Codex => "Codex", ContextKind::Off => "Agent\noff", }; let font = theme::ui_font(11.0); @@ -625,7 +654,7 @@ fn mode_sign(p: &egui::Painter, r: Rect, kind: gridcraft_agent::layer::ContextKi p.circle_filled(pos2(b.center().x + (k as f32 - 1.0) * 4.5, b.center().y), 1.3, color); } } - ContextKind::Code => { + ContextKind::Code | ContextKind::Codex => { let b = r.shrink2(vec2(0.5, 2.5)); p.rect_stroke(b, 3.0, s, egui::StrokeKind::Middle); let x = b.left() + 4.0; diff --git a/crates/agent/src/context.rs b/crates/agent/src/context.rs index 6ee0d96edce..21cc0bde649 100644 --- a/crates/agent/src/context.rs +++ b/crates/agent/src/context.rs @@ -11,6 +11,7 @@ //! choice made in the app. [`sync`] turns the active document's choice into the runner's mode and //! configuration. A person's change is undoable like their other layer actions. +use std::collections::HashMap; use std::path::PathBuf; use std::sync::Mutex; @@ -22,12 +23,18 @@ use crate::commands::{bad, spec, str_p}; use crate::layer::{self, AgentContext, CodeVia, ContextKind, Layer}; use crate::runner::{self, Mode}; -pub static SPECS: &[CommandSpec] = &[spec!( - change "agent.agentContext", - "Agent Context", - "{kind?: none|cowork|code, via?: session|folder, web?: bool, folder?: path} — what the agent knows about this document: only the document (a background client; `web` also allows web search), your Cowork chat, or your Claude Code session or a project folder. A person's choice, saved in the document → the context", - context_cmd -)]; +pub static SPECS: &[CommandSpec] = &[ + spec!( + change "agent.agentContext", + "Agent Context", + "{kind?: none|cowork|code|codex|off, via?: session|folder, web?: bool, folder?: path} — what the agent knows about this document: only the document (a background client; `web` also allows web search), your Cowork chat, or your Claude Code session or a project folder. A person's choice, saved in the document → the context", + context_cmd + ), + spec!(query "agent.codexConnect", "Connect Codex", "{} — connects this app's Codex question worker (a person's action)", codex_connect), + spec!(change "agent.codexOrigin", "Codex Origin Chat", "{threadId?, title?} — records the Desktop chat that created this file; no params reads the saved origin", codex_origin), + spec!(query "agent.codexRoute", "Codex Delivery Status", "{status?, threadId?, title?, detail?} — live Desktop delivery status; not saved in the workbook", codex_route), + spec!(query "agent.codexOpenChat", "Open Codex Chat", "{} — opens this document's actual Desktop chat (a person's action)", codex_open_chat), +]; impl ContextKind { pub fn parse(s: &str) -> Option { @@ -35,6 +42,7 @@ impl ContextKind { "none" | "no context" | "document" => Some(ContextKind::None), "cowork" | "claude cowork" => Some(ContextKind::Cowork), "code" | "claude code" => Some(ContextKind::Code), + "codex" => Some(ContextKind::Codex), "off" => Some(ContextKind::Off), _ => None, } @@ -44,6 +52,7 @@ impl ContextKind { ContextKind::None => "none", ContextKind::Cowork => "cowork", ContextKind::Code => "code", + ContextKind::Codex => "codex", ContextKind::Off => "off", } } @@ -53,6 +62,7 @@ impl ContextKind { ContextKind::None => ("No context", "Only this document. Runs in the background.", &["Document"]), ContextKind::Cowork => ("Claude Cowork", "Your Cowork chat, its project and memory.", &["Document", "Your chat"]), ContextKind::Code => ("Claude Code", "Your Claude Code session or a project folder.", &["Document", "Project folder"]), + ContextKind::Codex => ("Codex", "Codex answers through AItoCraft. New and open documents connect automatically.", &["Document", "Codex"]), ContextKind::Off => ("Agent off", "No agent: its tools refuse, nothing is sent.", &[]), } } @@ -78,7 +88,7 @@ impl CodeVia { pub fn mode_of(c: &AgentContext) -> Mode { match (c.kind, c.via) { (ContextKind::None, _) | (ContextKind::Code, CodeVia::Folder) => Mode::Background, - (ContextKind::Cowork, _) => Mode::Manual, + (ContextKind::Cowork | ContextKind::Codex, _) => Mode::Manual, (ContextKind::Code, CodeVia::Session) => Mode::Channel, (ContextKind::Off, _) => Mode::Off, } @@ -87,6 +97,7 @@ pub fn mode_of(c: &AgentContext) -> Mode { /// The context a runner mode stands for (an app started with `--agent-mode`, or before Context). pub fn from_mode(m: Mode) -> AgentContext { let kind = match m { + _ if codex_enabled() && m != Mode::Off => ContextKind::Codex, Mode::Manual => ContextKind::Cowork, Mode::Channel => ContextKind::Code, Mode::Background => ContextKind::None, @@ -121,7 +132,7 @@ pub fn last() -> AgentContext { fn remember(c: &AgentContext) { // The mode carries over to new documents; a project folder is the document's own. - let keep = AgentContext { folder: String::new(), ..c.clone() }; + let keep = AgentContext { folder: String::new(), codex_thread_id: String::new(), codex_thread_title: String::new(), ..c.clone() }; if let Some(f) = last_file() { if let Some(dir) = f.parent() { let _ = std::fs::create_dir_all(dir); @@ -150,9 +161,21 @@ pub fn forget_last() { } } +/// This app instance is served by Codex, without consulting another client's settings. +pub fn codex_enabled() -> bool { + std::env::var("GRIDCRAFT_AGENT_PROVIDER").is_ok_and(|v| v == "codex") +} + /// The document's context: its own, else the app's last. pub fn effective(l: &Layer) -> AgentContext { - l.context.clone().unwrap_or_else(last) + let mut c = l.context.clone().unwrap_or_else(last); + // The Codex launcher owns the runtime. Legacy saved contexts cannot start another client. + if codex_enabled() && c.kind != ContextKind::Off { + c.kind = ContextKind::Codex; + c.folder.clear(); + c.web = false; + } + c } /// Brings the runner in line with the active document's context: its mode, the folder the @@ -186,7 +209,10 @@ pub fn set(s: &mut Session, p: &Json) -> gridcraft_engine::Result let before = layer::get(d).context.clone(); let mut c = before.clone().unwrap_or_else(last); if let Some(k) = str_p(p, "kind") { - c.kind = ContextKind::parse(k).ok_or_else(|| bad(CMD, "`kind` is none, cowork or code"))?; + c.kind = ContextKind::parse(k).ok_or_else(|| bad(CMD, "`kind` is none, cowork, code, codex or off"))?; + } + if codex_enabled() && !matches!(c.kind, ContextKind::Codex | ContextKind::Off) { + return Err(bad(CMD, "this app instance uses Codex; choose codex or off")); } if let Some(v) = str_p(p, "via") { c.via = CodeVia::parse(v).ok_or_else(|| bad(CMD, "`via` is session or folder"))?; @@ -239,6 +265,8 @@ pub fn context_json(c: &AgentContext) -> Json { "via": c.via.id(), "web": c.web, "folder": c.folder, + "codexThreadId": c.codex_thread_id, + "codexThreadTitle": c.codex_thread_title, "mode": mode_of(c).id(), }) } @@ -249,6 +277,120 @@ fn context_cmd(s: &mut Session, p: &Json) -> gridcraft_engine::Result { Ok(context_json(&c)) } +/// Restrict deep links to a technical local chat UUID, including UUID v7. +pub fn valid_codex_thread(id: &str) -> bool { + id.len() == 36 && id.bytes().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { b == b'-' } else { b.is_ascii_hexdigit() }) +} + +fn codex_origin(s: &mut Session, p: &Json) -> gridcraft_engine::Result { + const CMD: &str = "agent.codexOrigin"; + let d = s.doc()?; + let before = layer::get(d).context.clone(); + let mut c = before.clone().unwrap_or_else(|| from_mode(runner::mode())); + if let Some(id) = str_p(p, "threadId") { + if crate::commands::AGENT_DEPTH.with(std::cell::Cell::get) > 0 || str_p(p, "actor") == Some("agent") { + return Err(bad(CMD, "origin is recorded by the workbook creator, not an answering agent")); + } + if !id.is_empty() && !valid_codex_thread(id) { + return Err(bad(CMD, "threadId must be a local Codex chat UUID")); + } + c.codex_thread_id = id.to_ascii_lowercase(); + c.codex_thread_title = str_p(p, "title").unwrap_or("Codex Desktop").chars().take(160).collect(); + if id.is_empty() { + c.codex_thread_title.clear(); + } + if before.as_ref() != Some(&c) { + crate::topics::record( + s, + "Codex origin chat", + vec![crate::topics::Part::Context(before)], + vec![crate::topics::Part::Context(Some(c.clone()))], + ); + layer::update(s.doc()?, |l| l.context = Some(c.clone())); + } + } + Ok(json!({"threadId": c.codex_thread_id, "title": c.codex_thread_title})) +} + +#[derive(Clone, Debug, Default)] +pub struct CodexRoute { + pub status: String, + pub thread_id: String, + pub title: String, + pub detail: String, + pub updated_at: u64, +} + +static CODEX_ROUTES: Mutex>> = Mutex::new(None); + +pub fn codex_route_for(uid: u64) -> Option { + CODEX_ROUTES.lock().ok()?.as_ref()?.get(&uid).filter(|r| crate::now_ms().saturating_sub(r.updated_at) < 15_000).cloned() +} + +fn codex_route(s: &mut Session, p: &Json) -> gridcraft_engine::Result { + const CMD: &str = "agent.codexRoute"; + let uid = s.doc()?.uid; + if let Some(status) = str_p(p, "status") { + if crate::commands::AGENT_DEPTH.with(std::cell::Cell::get) > 0 || str_p(p, "actor") == Some("agent") { + return Err(bad(CMD, "delivery status is maintained by the Desktop bridge")); + } + if !matches!( + status, + "matched" | "fresh" | "missing" | "unbound" | "disconnected" | "queued" | "attention" | "linked" | "linkMissing" | "fallback" + ) { + return Err(bad(CMD, "invalid delivery status")); + } + let id = str_p(p, "threadId").unwrap_or(""); + if !id.is_empty() && !valid_codex_thread(id) { + return Err(bad(CMD, "invalid chat UUID")); + } + let r = CodexRoute { + status: status.into(), + thread_id: id.into(), + title: str_p(p, "title").unwrap_or("").chars().take(160).collect(), + detail: str_p(p, "detail").unwrap_or("").chars().take(1000).collect(), + updated_at: crate::now_ms(), + }; + if let Ok(mut g) = CODEX_ROUTES.lock() { + let map = g.get_or_insert_with(HashMap::new); + map.retain(|_, old| r.updated_at.saturating_sub(old.updated_at) < 120_000); + map.insert(uid, r); + } + } + let r = codex_route_for(uid).unwrap_or_default(); + Ok(json!({"status": r.status, "threadId": r.thread_id, "title": r.title, "detail": r.detail, "updatedAt": r.updated_at})) +} + +fn codex_open_chat(s: &mut Session, p: &Json) -> gridcraft_engine::Result { + const CMD: &str = "agent.codexOpenChat"; + if crate::commands::AGENT_DEPTH.with(std::cell::Cell::get) > 0 || str_p(p, "actor") == Some("agent") { + return Err(bad(CMD, "only a person opens the Desktop chat")); + } + let d = s.doc()?; + let c = effective(&layer::get(d)); + let id = codex_route_for(d.uid).map(|r| r.thread_id).filter(|id| !id.is_empty()).unwrap_or(c.codex_thread_id); + if !valid_codex_thread(&id) { + return Err(bad(CMD, "no Desktop chat is attached yet")); + } + let url = format!("codex://threads/{id}"); + if !cfg!(test) { + #[cfg(target_os = "macos")] + let result = std::process::Command::new("/usr/bin/open").arg(&url).spawn(); + #[cfg(target_os = "windows")] + let result = std::process::Command::new("explorer.exe").arg(&url).spawn(); + #[cfg(not(any(target_os = "macos", target_os = "windows")))] + let result = std::process::Command::new("xdg-open").arg(&url).spawn(); + let mut child = result.map_err(|e| bad(CMD, e.to_string()))?; + std::thread::Builder::new() + .name("codex-open-chat".into()) + .spawn(move || { + let _ = child.wait(); + }) + .map_err(|e| bad(CMD, e.to_string()))?; + } + Ok(json!({"url": url})) +} + // ---------------------------------------------------------------- is it ready? /// What the app knows about the person's Claude setup, checked in the background. @@ -274,6 +416,9 @@ const SETUP_FRESH_MS: u64 = 60_000; /// The last check of the person's setup; starts a new one when it is old (never in tests). pub fn setup() -> Setup { + if codex_enabled() { + return Setup { checked_at: crate::now_ms(), ..Setup::default() }; + } let s = SETUP.lock().ok().and_then(|g| g.clone()).unwrap_or_default(); if crate::now_ms().saturating_sub(s.checked_at) > SETUP_FRESH_MS { recheck(); @@ -283,7 +428,7 @@ pub fn setup() -> Setup { /// Checks the setup again now, in the background. pub fn recheck() { - if cfg!(test) || CHECKING.swap(true, std::sync::atomic::Ordering::SeqCst) { + if codex_enabled() || cfg!(test) || CHECKING.swap(true, std::sync::atomic::Ordering::SeqCst) { return; } let spawned = std::thread::Builder::new().name("agent-setup-check".into()).spawn(|| { @@ -403,3 +548,37 @@ pub fn log_in() -> Result<(), String> { }; r.map(|_| ()).map_err(|e| format!("Couldn't open a terminal: {e}. Run `{cmd}` in one.")) } + +/// Start the app-scoped worker. Its singleton check prevents duplicate model consumers. +fn codex_connect(_s: &mut Session, p: &Json) -> gridcraft_engine::Result { + const CMD: &str = "agent.codexConnect"; + if str_p(p, "actor") == Some("agent") || crate::commands::AGENT_DEPTH.with(std::cell::Cell::get) > 0 { + return Err(bad(CMD, "only a person connects Codex")); + } + if !codex_enabled() { + return Err(bad(CMD, "start the Codex edition of GridCraft")); + } + let script = std::env::var("GRIDCRAFT_CODEX_BRIDGE").map_err(|_| bad(CMD, "restart the Codex GridCraft launcher to reconnect Codex"))?; + if !std::path::Path::new(&script).is_file() { + return Err(bad(CMD, "the Codex worker script is missing")); + } + let mut cmd = std::process::Command::new("/usr/bin/python3"); + cmd.args([script, "--instance".into(), std::process::id().to_string()]); + if let Some(registry) = std::env::var_os("AITOCRAFT_REGISTRY_DIR") { + cmd.arg("--registry").arg(registry); + } + let mut child = cmd + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::null()) + .stderr(std::process::Stdio::null()) + .spawn() + .map_err(|e| bad(CMD, e.to_string()))?; + let pid = child.id(); + std::thread::Builder::new() + .name("codex-worker".into()) + .spawn(move || { + let _ = child.wait(); + }) + .map_err(|e| bad(CMD, e.to_string()))?; + Ok(json!({"pid": pid, "connecting": true})) +} diff --git a/crates/agent/src/layer.rs b/crates/agent/src/layer.rs index 98b242c7b93..42ad0677553 100644 --- a/crates/agent/src/layer.rs +++ b/crates/agent/src/layer.rs @@ -367,6 +367,8 @@ pub enum ContextKind { Cowork, /// The person's Claude Code session, or a project folder. Code, + /// Codex, connected through the external AItoCraft question worker. + Codex, /// No agent at all (not offered on the tab; `agent.agentMode off`). Off, } @@ -392,6 +394,11 @@ pub struct AgentContext { /// Claude Code, project folder: where the background client runs. #[serde(default, skip_serializing_if = "String::is_empty")] pub folder: String, + /// The Desktop chat that created this document; never inherited by another document. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub codex_thread_id: String, + #[serde(default, skip_serializing_if = "String::is_empty")] + pub codex_thread_title: String, } /// A topic's status, with its free text and who set it. diff --git a/crates/agent/src/registry.rs b/crates/agent/src/registry.rs index be40e553f0f..b02d8f3fbc1 100644 --- a/crates/agent/src/registry.rs +++ b/crates/agent/src/registry.rs @@ -24,6 +24,9 @@ pub fn folder() -> Option { if let Some(p) = OVERRIDE.with(|o| o.borrow().clone()) { return Some(p); } + if let Some(p) = std::env::var_os("AITOCRAFT_REGISTRY_DIR").filter(|p| !p.is_empty()) { + return Some(PathBuf::from(p)); + } let home = std::env::var_os("HOME").map(PathBuf::from); if cfg!(target_os = "macos") { home.map(|h| h.join("Library/Application Support/ArtCraft/agents")) diff --git a/crates/agent/src/tests.rs b/crates/agent/src/tests.rs index 96a429f2e16..a7429fb6f85 100644 --- a/crates/agent/src/tests.rs +++ b/crates/agent/src/tests.rs @@ -1606,6 +1606,38 @@ fn mcp_topics_tools() { /// Context tests change the app-wide runner mode: one at a time. static CONTEXT_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(()); +#[test] +fn codex_origin_roundtrips_but_is_never_inherited_and_routes_are_runtime_only() { + let _g = CONTEXT_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut s = model(); + let id = "11111111-1111-4111-8111-111111111111"; + assert!(s.execute("agent.codexOrigin", json!({"threadId": "../another?prompt=secret"})).is_err()); + assert!(s.execute("agent.codexOrigin", json!({"threadId": id, "actor": "agent"})).is_err()); + assert_eq!(s.execute("agent.codexOrigin", json!({"actor": "agent"})).unwrap()["threadId"], ""); + let saved = s.execute("agent.codexOrigin", json!({"threadId": id, "title": "Origin chat"})).unwrap(); + for status in ["linked", "linkMissing", "fallback"] { + let route = s.execute("agent.codexRoute", json!({"status": status, "threadId": id, "title": "Link chat"})).unwrap(); + assert_eq!(route["status"], status); + assert_eq!(s.execute("agent.codexOrigin", json!({})).unwrap(), saved); + } + s.execute("agent.codexRoute", json!({"status": "fresh", "threadId": id, "title": "New chat"})).unwrap(); + assert!(s.execute("agent.codexRoute", json!({"status": "matched", "actor": "agent"})).is_err()); + let mut wb = (*s.active().unwrap().wb).clone(); + layer::write_into(&mut wb, &layer::get(s.active().unwrap())); + let loaded = layer::read_from(&wb); + assert_eq!(loaded.context.as_ref().unwrap().codex_thread_id, id); + assert_eq!(loaded.context.as_ref().unwrap().codex_thread_title, "Origin chat"); + assert!(!serde_json::to_string(&loaded).unwrap().contains("New chat")); + // Ordinary context changes preserve origin; app defaults for another file clear it. + s.execute("agent.agentContext", json!({"kind": "codex"})).unwrap(); + assert_eq!(s.execute("agent.codexOrigin", json!({})).unwrap(), saved); + s.new_workbook(); + assert_eq!(s.execute("agent.codexOrigin", json!({})).unwrap()["threadId"], ""); + assert!(crate::context::codex_route_for(s.active().unwrap().uid).is_none()); + crate::context::forget_last(); + crate::runner::set_mode(crate::runner::Mode::Manual); +} + #[test] fn context_is_per_document_saved_in_it_and_undoable() { use crate::context; diff --git a/docs/codex-desktop.md b/docs/codex-desktop.md new file mode 100644 index 00000000000..a996c50dcf4 --- /dev/null +++ b/docs/codex-desktop.md @@ -0,0 +1,81 @@ +# Codex Desktop: experimental agent context + +This adds an opt-in **Codex** context to the agent-layer fork. Questions are delivered by an +external bridge to the actual loaded Desktop chat on a shared Codex App Server. Codex reads and +proposes changes through the existing AItoCraft MCP tools; the reader still applies or rejects +the proposal in GridCraft. + +The companion launcher/bridge, URL receiver, skill and installation instructions live in the +[AItoCraft Codex Desktop example](https://github.com/alexey-belkin/aitocraft/tree/codex/desktop-chat-links/examples/codex-desktop). +This GridCraft PR targets **agent-layer**, not the fork's default main branch. + +## Enable one application instance + +The companion launcher sets these environment variables only for its child processes: + +| Variable | Purpose | +| --- | --- | +| `GRIDCRAFT_AGENT_PROVIDER=codex` | Use Codex instead of reading legacy Claude setup; respect an explicit Off context | +| `GRIDCRAFT_CODEX_BRIDGE=/absolute/path/codex_bridge.py` | Worker launched by Connect Codex, using Python 3 and the GUI's instance ID | +| `GRIDCRAFT_NO_PREFS=1` | Isolate this experimental application's preferences | +| `AITOCRAFT_REGISTRY_DIR=/absolute/path/registry` | Use an isolated registry shared with the AItoCraft instances | + +Without `GRIDCRAFT_AGENT_PROVIDER=codex`, existing context choices keep their behavior. The Codex +instance skips Claude setup checks and does not persist its context into global agent defaults. +No global Claude configuration needs to change. + +## Saved origin and live route are separate + +`AgentContext` has two optional, default-empty fields, `codex_thread_id` and +`codex_thread_title`. They record the chat that created a workbook, inside its existing agent +custom XML part. A new workbook does not inherit another workbook's origin through app defaults. +Existing workbooks without these fields still load. An older application that does not recognize +the new `codex` context kind is not a supported reader of the new context metadata. + +The working chat selected by a link is maintained by the companion bridge. It has priority over +origin but does not rewrite provenance or workbook cells. If the selected chat is unavailable, +the bridge can create a new actual Desktop chat on the first question; the panel shows the +mismatch. A copy/Save As retains origin; the bridge's delivery journal and link binding handle +the working route across save, reopen and worker restart. + +## Native commands + +All commands target the selected document; use `agent.onDocument` from the control channel to +avoid changing whichever workbook happens to be frontmost. + +| Command | Parameters / result | +| --- | --- | +| `agent.codexOrigin` | `{}` reads `{threadId,title}`; `{threadId,title}` changes the saved origin as an undoable person action. Empty ID clears it. Accepts a technical UUID only. | +| `agent.codexRoute` | Runtime bridge update `{status,threadId?,title?,detail?}`; `{}` reads it. No workbook mutation. Calls marked as agent are refused. | +| `agent.codexConnect` | Starts the configured external worker for this GUI instance; no CLI model session is started. | +| `agent.codexOpenChat` | Opens `codex://threads/` for the live route, falling back to origin; a person action. | + +Route states are `matched`, `linked`, `fresh`, `fallback`, `missing`, `linkMissing`, `unbound`, +`disconnected`, `queued`, and `attention`. Route information expires after 15 seconds without a +bridge refresh and is not serialized. The Codex Ready lamp requires a recent **Codex desktop +bridge** listener, rather than an old answered connection check. This label/presence convention +is operational status, not authentication. + +## Runtime + +Keep Desktop and its shared App Server running, along with GridCraft and the question worker. +The worker polls AItoCraft without an idle LLM turn; questions go through `turn/steer` when a +Desktop turn is active and `turn/start` when the selected chat is idle. It never substitutes +`codex exec/resume` for a Desktop conversation. HTTP links and the native URL receiver are +optional entry points; they do not need to process answers. + +The native change is Rust only. The multi-runtime experimental example is maintained separately +in AItoCraft. The application uses the existing proposal commands: `agent.applyProposal` and +`agent.rejectProposal` remain person actions. + +## Validation + +The local implementation was built on macOS arm64 with Rust 1.99.1. Agent-layer tests cover +origin round-trip, no origin inheritance, runtime-only routes, UUID validation and refusal of +agent-authored route updates. Agent UI tests cover requiring a live bridge listener. + +In the companion live test, five unique questions reached the same real Desktop chat, including +a rejection comment and a question after reopen. Accepting 60 → 70 changed profit 40 → 30; +rejecting 70 → 90 preserved 70/30. Formula, decisions, answers and origin survived save/reopen. +The final pass used the app's supported person-action API commands, the same commands as the +Apply/Reject buttons; it did not claim fresh UI clicks while Computer Use was unavailable.