Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: sign in to an agent from the chat

leepokai8f04e5da111b
diff --git a/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx b/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx
index cf2640b0..86dbea0d 100644
--- a/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/AgentSheet.tsx
@@ -77,7 +77,9 @@ export function NodeNotice({ onAdd }: { onAdd: () => void }) {
* options come from the agent itself (ACP), plus Codync's own command for
* CLIs it knows. Bots are made from New chat, not here.
*/
-export function AgentSheet({ initial }: { initial: Backend }) {
+/** `recheck`: opened from a chat's sign-in request, whose agent refused a turn, so the agent is
+ * asked again however signed in it looked. */
+export function AgentSheet({ initial, recheck = false }: { initial: Backend; recheck?: boolean }) {
const store = useStore()
const [route, setRoute] = useState<SetupRoute | null>(null)
const [auth, setAuth] = useState<AgentAuth | null>(null)
@@ -127,7 +129,7 @@ export function AgentSheet({ initial }: { initial: Backend }) {
// A known "signed in" needs no agent start; everything else asks the agent (which can't
// start without its Node.js).
useEffect(() => {
- if (backend.signedIn !== true && !nodeMissing) void check()
+ if ((recheck || backend.signedIn !== true) && !nodeMissing) void check()
}, [])
// Back from a terminal or key form: see what changed.
diff --git a/apps/desktop/src/renderer/views/marketplace/ConnectionRequestCard.tsx b/apps/desktop/src/renderer/views/marketplace/ConnectionRequestCard.tsx
index 822c9554..33a18f99 100644
--- a/apps/desktop/src/renderer/views/marketplace/ConnectionRequestCard.tsx
+++ b/apps/desktop/src/renderer/views/marketplace/ConnectionRequestCard.tsx
@@ -1,9 +1,10 @@
import { useState } from 'react'
-import type { Entry } from '@shared/models'
+import type { Backend, Entry } from '@shared/models'
import { Button, Spinner } from '../../components/Controls'
import { Icon } from '../../components/Icon'
import { font } from '../../lib/fonts'
import { useStore } from '../../store/context'
+import { AgentSheet } from './AgentSheet'
import { ComposioConnectSheet } from './ComposioViews'
import { InstallConnectorSheet } from './ConnectorSheets'
import {
@@ -21,12 +22,14 @@ export function ConnectionRequestCard({ entry }: { entry: Entry }) {
const request = entry.data.connectionRequest as unknown as ConnectionRequest
const [app, setApp] = useState<ComposioApp | null>(null)
const [item, setItem] = useState<MarketConnector | null>(null)
+ const [agent, setAgent] = useState<Backend | null>(null)
const [value, setValue] = useState('')
const [username, setUsername] = useState('')
const [busy, setBusy] = useState(false)
const [error, setError] = useState<string | null>(null)
const isLogin = request.kind === 'login'
const isSecret = request.kind === 'secret'
+ const isAgent = request.kind === 'agent'
const connect = async () => {
const client = store.client
@@ -34,7 +37,12 @@ export function ConnectionRequestCard({ entry }: { entry: Entry }) {
setBusy(true)
setError(null)
try {
- if (request.kind === 'app' && request.toolkit) {
+ if (isAgent) {
+ // The host completes the card and resends the messages once the sheet finds it signed in.
+ const backend = store.hello?.backends.find((b) => b.id === request.backend)
+ if (backend) setAgent(backend)
+ else setError(`Open ${request.title} in Extensions to sign in.`)
+ } else if (request.kind === 'app' && request.toolkit) {
setApp({ slug: request.toolkit, name: request.title })
} else if (isLogin) {
await market.finishConnectionRequest(client, entry.id, { value, username })
@@ -93,14 +101,14 @@ export function ConnectionRequestCard({ entry }: { entry: Entry }) {
) : null}
<div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
<Button disabled={busy || ((isSecret || isLogin) && !value)} onClick={() => void connect()}>
- {isLogin ? 'Save login' : isSecret ? 'Save and connect' : 'Connect'}
+ {isAgent ? 'Sign in' : isLogin ? 'Save login' : isSecret ? 'Save and connect' : 'Connect'}
</Button>
<Button kind="secondary" disabled={busy} onClick={() => void cancel()}>Cancel</Button>
{busy ? <Spinner /> : null}
</div>
</>
) : (
- <span style={{ color: 'var(--secondary)' }}>{request.status === 'ready' ? (isLogin ? 'Saved' : 'Connected') : 'Cancelled'}</span>
+ <span style={{ color: 'var(--secondary)' }}>{request.status === 'ready' ? (isAgent ? 'Signed in' : isLogin ? 'Saved' : 'Connected') : 'Cancelled'}</span>
)}
{error ? <span style={{ ...font('footnote'), color: 'var(--danger)' }}>{error}</span> : null}
<FormSheet open={item !== null} onClose={() => setItem(null)}>
@@ -109,6 +117,9 @@ export function ConnectionRequestCard({ entry }: { entry: Entry }) {
<FormSheet open={app !== null} onClose={() => setApp(null)}>
{app ? <ComposioConnectSheet app={app} requestId={entry.id} done={() => setApp(null)} /> : null}
</FormSheet>
+ <FormSheet open={agent !== null} onClose={() => setAgent(null)} width={560} height={560}>
+ {agent ? <AgentSheet key={agent.id} initial={agent} recheck /> : null}
+ </FormSheet>
</div>
)
}
diff --git a/apps/desktop/src/renderer/views/marketplace/market-models.ts b/apps/desktop/src/renderer/views/marketplace/market-models.ts
index e5a22ac6..3bbcb192 100644
--- a/apps/desktop/src/renderer/views/marketplace/market-models.ts
+++ b/apps/desktop/src/renderer/views/marketplace/market-models.ts
@@ -123,6 +123,8 @@ export interface ConnectionRequest {
location?: string | null
/** Login requests: the website's domain or the app's name. */
site?: string | null
+ /** Agent sign-in requests: the agent (backend id) to sign in to. */
+ backend?: string | null
}
/** A saved website or app login; the password stays on the computer. */
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Market.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Market.swift
index acec260d..3aed642b 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Market.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Market.swift
@@ -246,6 +246,8 @@ public struct ConnectionRequest: Codable, Hashable, Sendable {
public var location: String?
/// Login requests: the website's domain or the app's name.
public var site: String?
+ /// Agent sign-in requests: the agent (backend id) to sign in to.
+ public var backend: String?
}
/// A saved website or app login; the password stays on the computer.
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift
index de23229b..8c8cba32 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/AgentSheet.swift
@@ -44,6 +44,9 @@ struct NodeNotice: View {
/// plus Codync's own command for CLIs it knows. Bots are made from New chat, not here.
struct AgentSheet: View {
let initial: Backend
+ /// Opened from a chat's sign-in request, whose agent refused a turn: the agent is asked
+ /// again however signed in it looked.
+ var recheck = false
@Environment(BotStore.self) private var model
@State private var route: SetupRoute?
@State private var auth: AgentAuth?
@@ -72,7 +75,7 @@ struct AgentSheet: View {
.frame(minWidth: 0, minHeight: 0)
// A known "signed in" needs no agent start; everything else asks the agent (which
// can't start without its Node.js).
- .task { if backend.signedIn != true, !backend.needsNode { await check() } }
+ .task { if recheck || backend.signedIn != true, !backend.needsNode { await check() } }
.onChange(of: route) { old, new in
// Back from a terminal or key form: see what changed.
if new == nil, old != nil { Task { await check() } }
diff --git a/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift b/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift
index 26203d47..3ff75068 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Marketplace/ConnectionRequestCard.swift
@@ -11,6 +11,7 @@ struct ConnectionRequestCard: View {
@Environment(\.openURL) private var openURL
@State private var app: ComposioApp?
@State private var item: MarketConnector?
+ @State private var agent: Backend?
@State private var value = ""
@State private var username = ""
@State private var busy = false
@@ -38,14 +39,14 @@ struct ConnectionRequestCard: View {
.font(.caption).foregroundStyle(Palette.secondary)
}
HStack {
- Button(request.kind == "login" ? "Save login" : request.kind == "secret" ? "Save and connect" : "Connect") { connect() }
+ Button(connectTitle) { connect() }
.buttonStyle(PrimaryButtonStyle())
.disabled(busy || (["secret", "login"].contains(request.kind) && value.isEmpty))
Button("Cancel") { cancel() }.buttonStyle(SecondaryButtonStyle()).disabled(busy)
if busy { Spinner() }
}
} else {
- Text(request.status == "ready" ? (request.kind == "login" ? "Saved" : "Connected") : "Cancelled").foregroundStyle(Palette.secondary)
+ Text(request.status == "ready" ? doneTitle : "Cancelled").foregroundStyle(Palette.secondary)
}
if let error { Text(error).font(.footnote).foregroundStyle(Palette.danger) }
}
@@ -58,9 +59,27 @@ struct ConnectionRequestCard: View {
.codyncSheet(item: $app) { app in
ComposioConnectSheet(app: app, requestId: entry.id) { self.app = nil }
}
+ .codyncSheet(item: $agent) { AgentSheet(initial: $0, recheck: true) }
.onDisappear { value = ""; username = "" }
}
+ private var connectTitle: String {
+ switch request.kind {
+ case "agent": "Sign in"
+ case "login": "Save login"
+ case "secret": "Save and connect"
+ default: "Connect"
+ }
+ }
+
+ private var doneTitle: String {
+ switch request.kind {
+ case "agent": "Signed in"
+ case "login": "Saved"
+ default: "Connected"
+ }
+ }
+
private func connect() {
guard let client = model.client else { return }
busy = true
@@ -68,7 +87,14 @@ struct ConnectionRequestCard: View {
Task {
defer { busy = false }
do {
- if request.kind == "app", let toolkit = request.toolkit {
+ if request.kind == "agent" {
+ // The host completes the card and resends the messages once the sheet finds it signed in.
+ if let backend = model.hello?.backends.first(where: { $0.id == request.backend }) {
+ withAnimation(Motion.layout) { agent = backend }
+ } else {
+ error = "Open \(request.title) in Extensions to sign in."
+ }
+ } else if request.kind == "app", let toolkit = request.toolkit {
withAnimation(Motion.layout) { app = ComposioApp(slug: toolkit, name: request.title) }
} else if request.kind == "login" {
try await client.finishConnectionRequest(entry.id, value: value, username: username)
diff --git a/apps/ios/WhatsNew.md b/apps/ios/WhatsNew.md
index f28b281f..ef0d0cea 100644
--- a/apps/ios/WhatsNew.md
+++ b/apps/ios/WhatsNew.md
@@ -10,7 +10,9 @@ a version without one gets a generic "Bug fixes and improvements" line. Delete o
### zh-Hant
- 在輸入框打 / 就會列出所有指令:快速模式、開新工作階段,以及 bot 的 skills,每一項都附上說明。快速模式改從這裡開關,不再放在 + 選單。
+- Claude Code 等 agent 需要重新登入時,對話裡會出現登入卡片,點「Sign in」就能直接登入;登入後,剛才沒回覆的訊息會自動重送。
### en-US
- Type / in the composer to see every command with what it does: Fast mode, New session and the bot's skills. Fast mode now switches from here instead of the + menu.
+- When Claude Code or another agent needs you to sign in again, a card in the chat lets you sign in right there, and the messages it couldn't answer go out again once you're signed in.
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index 66cbf56c..20048eb2 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -126,7 +126,9 @@ and states.
- TUI **C** opens a pending connection request in the current lane; selecting a request
and pressing Enter opens that request. Credentials, connector installation/sign-in
and hosted apps use the secure setup APIs. Ctrl+X cancels the request; Escape closes
- the editor without cancelling. Secrets are masked and never sent as chat text.
+ the editor without cancelling. Secrets are masked and never sent as chat text. An
+ agent sign-in request opens that agent's sign-in sheet instead (it always checks the
+ sign-in again); Ctrl+X there cancels the request.
- A bot-to-bot exchange is a compact centered row ("Messaged [avatar] Owen" / "Message from
[avatar] Egan"; same verbs for asks; the TUI draws one ` · ` line), never a bubble. Only a
failure is marked: danger color, a warning mark (triangle icon; the TUI uses a
diff --git a/docs/features/connector-credentials.md b/docs/features/connector-credentials.md
index a2365716..9a05fc62 100644
--- a/docs/features/connector-credentials.md
+++ b/docs/features/connector-credentials.md
@@ -63,6 +63,15 @@ acknowledgement in the original conversation/thread. Repeated completed submissi
return the completed entry. Cancelled requests reject submissions. Verification
failures remain pending so the user can correct credentials and retry.
+The host posts one more kind itself, `agent`: when a bot's own agent (Claude Code…)
+refuses a turn because it needs signing in, the chat gets a card naming the agent
+(`backend`) and the user messages it couldn't answer (`entryIds`) instead of an
+error. A bot keeps one such card; messages that fail later join it. The card's
+Sign in opens the agent's sign-in sheet from Extensions. As soon as a sign-in check
+(`agentAuth`, `agentAuthenticate`, `setAgentEnv`, or connectorRequestFinish on the
+card) finds the agent signed in, every pending card for it completes and its
+messages go out again; a card older than 24 hours only completes.
+
MCP connection requests and runtime secret retrieval are loopback-only. Authorized
Control devices may submit or cancel requests. No endpoint exposes a generic
credential getter to a device. Existing local-process trust boundaries still apply.
diff --git a/host/src/agent/bot/mod.rs b/host/src/agent/bot/mod.rs
index c153f430..02628c3c 100644
--- a/host/src/agent/bot/mod.rs
+++ b/host/src/agent/bot/mod.rs
@@ -136,6 +136,7 @@ pub fn spawn(hub: Arc<Hub>, cfg: BotConfig) -> BotHandle {
applied_system: HashMap::new(),
keeper,
turn_text: None,
+ turn_entries: Vec::new(),
memory_session: None,
memory_warned: false,
turn_memory_revision: String::new(),
@@ -229,6 +230,8 @@ struct Actor {
keeper: mpsc::UnboundedSender<memory::KeeperEvent>,
/// The user's words for this turn (None for a hidden turn or one not from the user); feeds memory.
turn_text: Option<String>,
+ /// The user messages this turn answers (none when it isn't the user's).
+ turn_entries: Vec<String>,
memory_session: Option<String>,
/// The user was told memory is unavailable.
memory_warned: bool,
diff --git a/host/src/agent/bot/queue.rs b/host/src/agent/bot/queue.rs
index 103dc200..2778162c 100644
--- a/host/src/agent/bot/queue.rs
+++ b/host/src/agent/bot/queue.rs
@@ -3,6 +3,7 @@
use super::{Actor, CANCEL_GRACE, Cmd, Done, NoticeStyle, Queued, RESUME_PROMPT, RoutineCompletion, inflight_key};
use crate::chat::memory;
use crate::hub::BotStatus;
+use crate::market::requests;
use crate::store::{Lane, now_ms};
use anyhow::{Result, anyhow};
use serde_json::json;
@@ -240,9 +241,10 @@ impl Actor {
self.finish_routine(crate::routines::Status::Failed, Some(format!("Could not start routine: {e:#}")), None);
self.complete_request(Err(anyhow!("couldn't start recipient: {e:#}")), false);
self.complete_group(Err(anyhow!("couldn't start: {e:#}")));
- // `{:#}` keeps the reason ("starting `npx …`: EACCES"), not just "agent process exited".
- let msg = self.ask_to_sign_in(e).unwrap_or_else(|| format!("Couldn't start the agent: {e:#}"));
- self.notice(&msg, NoticeStyle::Error);
+ if !self.invite_sign_in(e) {
+ // `{:#}` keeps the reason ("starting `npx …`: EACCES"), not just "agent process exited".
+ self.notice(&format!("Couldn't start the agent: {e:#}"), NoticeStyle::Error);
+ }
self.turn = None;
if self.routine_completion.is_none() {
self.set_inflight(false);
@@ -256,15 +258,21 @@ impl Actor {
self.hub.team.cancel_from(&self.cfg.id);
}
- /// When `e` asks for signing in: marks the harness signed out, so Extensions offers to sign
- /// in again, and returns what to tell the user.
- pub(super) fn ask_to_sign_in(&self, e: &anyhow::Error) -> Option<String> {
- if !crate::agent::acp::needs_sign_in(e) {
- return None;
- }
- let h = crate::agent::backends::harness(&self.cfg.backend)?;
- crate::agent::backends::set_signed_in(&self.cfg.backend, Some(false));
- Some(format!("{0} needs you to sign in. Open {0} in Extensions to sign in.", h.name))
+ /// When `e` asks for signing in: marks the harness signed out and puts a sign-in card in the
+ /// chat, which sends this turn's messages again once the user has signed in. Whether it did.
+ pub(super) fn invite_sign_in(&self, e: &anyhow::Error) -> bool {
+ let backend = &self.cfg.backend;
+ let Some(h) = crate::agent::backends::harness(backend).filter(|_| crate::agent::acp::needs_sign_in(e)) else {
+ return false;
+ };
+ crate::agent::backends::set_signed_in(backend, Some(false));
+ let invited =
+ requests::invite_agent_sign_in(&self.hub, &self.cfg.id, &self.lane, backend, h.name, &self.turn_entries);
+ invited
+ .inspect_err(
+ |error| tracing::warn!(bot = %self.cfg.id, error = format!("{error:#}"), "couldn't ask to sign in"),
+ )
+ .is_ok()
}
pub(super) fn complete_request(&mut self, result: Result<String>, cancelled: bool) {
diff --git a/host/src/agent/bot/turn.rs b/host/src/agent/bot/turn.rs
index 260ca312..ff15eaa3 100644
--- a/host/src/agent/bot/turn.rs
+++ b/host/src/agent/bot/turn.rs
@@ -49,6 +49,7 @@ impl Actor {
let from_user =
!hidden && self.active_request.is_none() && self.active_group.is_none() && self.active_routine.is_none();
self.turn_text = from_user.then(|| text.to_owned());
+ self.turn_entries = if from_user { entry_ids.to_vec() } else { Vec::new() };
self.turn_memory_revision = memory::maintenance::revision(&self.hub.store, &self.cfg.id);
self.announce = None;
self.stop_requested = false;
@@ -244,11 +245,10 @@ impl Actor {
match (&done, stop_reason.as_str()) {
(Err(e), _) if !self.stop_requested => {
let tail = self.exit_tail.take().filter(|t| !t.is_empty());
- let msg = self.ask_to_sign_in(e).unwrap_or_else(|| {
+ if !self.invite_sign_in(e) {
let detail = tail.map(|t| format!("\n\n{}", acp::truncate(&t, 1200))).unwrap_or_default();
- format!("The agent failed: {e}{detail}")
- });
- self.notice(&msg, NoticeStyle::Error);
+ self.notice(&format!("The agent failed: {e}{detail}"), NoticeStyle::Error);
+ }
}
(_, "cancelled") | (Err(_), _) => self.notice("Stopped.", NoticeStyle::Info),
(_, "max_tokens") => self.notice("The agent hit its output limit.", NoticeStyle::Info),
diff --git a/host/src/api/bots.rs b/host/src/api/bots.rs
index 21a9d4b2..d2658f1e 100644
--- a/host/src/api/bots.rs
+++ b/host/src/api/bots.rs
@@ -172,23 +172,15 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr
None => None,
};
let lane = Lane { chat: bot.to_owned(), thread };
- let (mut paths, mut attachments) = (Vec::new(), Vec::new());
+ let mut attachments = Vec::new();
if !uploads.is_empty() {
let root = crate::chat::uploads::root(&row.config);
for id in uploads {
- let (path, meta) = crate::chat::uploads::resolve(&root, id)?;
- paths.push(path);
- attachments.push(meta);
+ attachments.push(crate::chat::uploads::resolve(&root, id)?.1);
}
}
// `/skill …` reaches the agent as "read this skill first"; the chat keeps what was typed.
- let asked = market::expand_command(&hub.store, &row.config.skills, text);
- let asked = asked.as_deref().unwrap_or(text);
- let prompt = if paths.is_empty() {
- asked.to_owned()
- } else {
- format!("{asked}{}", crate::chat::uploads::prompt_suffix(&paths))
- };
+ let prompt = crate::chat::prompt::of_message(&hub.store, &row.config, text, &attachments);
let turn = hub.store.max_turn(bot) + 1;
// A group has no agent of its own to queue behind: its message is simply sent.
let status = if row.config.is_group() { "sent" } else { "queued" };
diff --git a/host/src/api/host.rs b/host/src/api/host.rs
index b62a0c95..bd053415 100644
--- a/host/src/api/host.rs
+++ b/host/src/api/host.rs
@@ -102,13 +102,23 @@ pub(super) async fn call(hub: &Arc<Hub>, caller: &Caller, method: &str, b: Value
json!({"term": hub.terms.start(backend, step, b["method"].as_str(), cols, rows).await?})
}
"agentModels" => crate::agent::auth::models(&hub.store, str_arg(&b, "backend")?).await?,
- "agentAuth" => crate::agent::auth::check(&hub.store, str_arg(&b, "backend")?).await?,
- "agentAuthenticate" => {
- crate::agent::auth::authenticate(&hub.store, str_arg(&b, "backend")?, str_arg(&b, "method")?).await?
- }
- "setAgentEnv" => {
- let vars = b["vars"].as_object().ok_or_else(|| anyhow!("`vars` is required"))?;
- crate::agent::auth::set_env(&hub.store, str_arg(&b, "backend")?, vars).await?
+ "agentAuth" | "agentAuthenticate" | "setAgentEnv" => {
+ let backend = str_arg(&b, "backend")?;
+ let status = match method {
+ "agentAuth" => crate::agent::auth::check(&hub.store, backend).await?,
+ "agentAuthenticate" => {
+ crate::agent::auth::authenticate(&hub.store, backend, str_arg(&b, "method")?).await?
+ }
+ _ => {
+ let vars = b["vars"].as_object().ok_or_else(|| anyhow!("`vars` is required"))?;
+ crate::agent::auth::set_env(&hub.store, backend, vars).await?
+ }
+ };
+ // Chats that asked the user to sign in get their messages answered now.
+ if status["signedIn"] == true {
+ crate::market::requests::agent_signed_in(hub, backend)?;
+ }
+ status
}
"termInput" => {
hub.terms.write(str_arg(&b, "term")?, str_arg(&b, "data")?)?;
diff --git a/host/src/chat/mod.rs b/host/src/chat/mod.rs
index fe7c3426..c94de594 100644
--- a/host/src/chat/mod.rs
+++ b/host/src/chat/mod.rs
@@ -7,5 +7,6 @@ pub mod group;
pub mod memory;
pub mod naming;
pub mod outbox;
+pub mod prompt;
pub mod team;
pub mod uploads;
diff --git a/host/src/chat/prompt.rs b/host/src/chat/prompt.rs
new file mode 100644
index 00000000..520359fe
--- /dev/null
+++ b/host/src/chat/prompt.rs
@@ -0,0 +1,16 @@
+//! What a user message asks the agent: its text with a `/skill …` command expanded, then the
+//! paths of the files attached to it.
+
+use crate::chat::uploads;
+use crate::store::{BotConfig, Store};
+use serde_json::Value;
+use std::path::PathBuf;
+
+/// `attachments`: the message's `{id, name}` upload metadata, as saved in the chat.
+pub fn of_message(store: &Store, cfg: &BotConfig, text: &str, attachments: &[Value]) -> String {
+ let asked = crate::market::expand_command(store, &cfg.skills, text);
+ let asked = asked.as_deref().unwrap_or(text);
+ let root = uploads::root(cfg);
+ let paths: Vec<PathBuf> = attachments.iter().filter_map(|meta| uploads::path_of(&root, meta)).collect();
+ if paths.is_empty() { asked.to_owned() } else { format!("{asked}{}", uploads::prompt_suffix(&paths)) }
+}
diff --git a/host/src/market/requests.rs b/host/src/market/requests.rs
index bc5e4c20..78bf8d97 100644
--- a/host/src/market/requests.rs
+++ b/host/src/market/requests.rs
@@ -2,6 +2,7 @@
//! tools receive status, never credential values.
use super::connectors;
use crate::{
+ LockExt,
agent::bot::Cmd,
hub::Hub,
store::{Entry, EntryKind, Lane, now_ms},
@@ -19,6 +20,8 @@ enum RequestKind {
Secret,
App,
Login,
+ /// The bot's own agent (Claude Code…) needs signing in; posted by the host, not a tool.
+ Agent,
}
#[derive(Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
@@ -35,6 +38,71 @@ fn has_status(request: &Value, status: RequestStatus) -> bool {
const MAX_AGE: i64 = 24 * 60 * 60 * 1000;
static MUTATION: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
+/// Agent sign-in cards change from bot actors and API calls alike (no `.await` while held).
+static SIGN_IN: std::sync::Mutex<()> = std::sync::Mutex::new(());
+
+/// `bot`'s turn failed because agent `backend` (`name`) needs signing in: a card in `lane`
+/// asks the user to, and `entries` (the user messages it couldn't answer) go out again once
+/// they have. A bot keeps one such card; messages that fail later join it.
+pub fn invite_agent_sign_in(
+ hub: &Hub,
+ bot: &str,
+ lane: &Lane,
+ backend: &str,
+ name: &str,
+ entries: &[String],
+) -> Result<()> {
+ let _guard = SIGN_IN.locked();
+ if let Some(card) = hub.store.pending_sign_ins(backend)?.into_iter().find(|card| card.bot_id == bot) {
+ let mut data = card.data;
+ let mut ids = data["connectionRequest"]["entryIds"].as_array().cloned().unwrap_or_default();
+ for id in entries {
+ if !ids.iter().any(|v| v == id.as_str()) {
+ ids.push(json!(id));
+ }
+ }
+ data["connectionRequest"]["entryIds"] = Value::Array(ids);
+ hub.set_entry(&card.id, &data).ok_or_else(|| anyhow!("Could not update the sign-in request"))?;
+ return Ok(());
+ }
+ let request = json!({"kind": RequestKind::Agent, "status": RequestStatus::Pending, "title": name, "botId": bot,
+ "backend": backend, "entryIds": entries});
+ let text = format!("{name} needs you to sign in. Your message goes out again once you're signed in.");
+ hub.add_entry(
+ lane,
+ EntryKind::Notice,
+ hub.store.max_turn(bot),
+ &json!({"text": text, "connectionRequest": request}),
+ )
+ .ok_or_else(|| anyhow!("Could not save the sign-in request"))?;
+ Ok(())
+}
+
+/// Agent `backend` is signed in now: its sign-in cards complete, and the messages they hold go
+/// out again (a card older than a day only completes).
+pub fn agent_signed_in(hub: &Hub, backend: &str) -> Result<()> {
+ let _guard = SIGN_IN.locked();
+ for card in hub.store.pending_sign_ins(backend)? {
+ let mut data = card.data.clone();
+ data["connectionRequest"]["status"] = serde_json::to_value(RequestStatus::Ready)?;
+ hub.set_entry(&card.id, &data).ok_or_else(|| anyhow!("Could not complete the sign-in request"))?;
+ let Some(bot) = hub.store.bot(&card.bot_id)?.filter(|b| !b.deleted) else { continue };
+ if now_ms() - card.created_at > MAX_AGE {
+ continue;
+ }
+ let ids = data["connectionRequest"]["entryIds"].as_array().cloned().unwrap_or_default();
+ for mut entry in ids.iter().filter_map(Value::as_str).filter_map(|id| hub.store.entry(id)) {
+ let attachments = entry.data["attachments"].as_array().cloned().unwrap_or_default();
+ let text = entry.data["text"].as_str().unwrap_or_default();
+ let prompt = crate::chat::prompt::of_message(&hub.store, &bot.config, text, &attachments);
+ entry.data["status"] = "queued".into();
+ hub.set_entry(&entry.id, &entry.data);
+ let lane = Lane { chat: entry.bot_id.clone(), thread: entry.thread_id.clone() };
+ hub.send_cmd(&card.bot_id, Cmd::Send { lane, entry_id: entry.id, text: prompt })?;
+ }
+ }
+ Ok(())
+}
pub fn tools() -> Value {
json!([
@@ -162,6 +230,14 @@ pub async fn finish(hub: &Arc<Hub>, args: &Value) -> Result<Value> {
data["connectionRequest"]["status"] = serde_json::to_value(RequestStatus::Cancelled)?;
return Ok(json!({"entry":hub.set_entry(id, &data).ok_or_else(|| anyhow!("Could not cancel request"))?}));
}
+ if kind == RequestKind::Agent {
+ let backend = text(request, "backend")?;
+ if crate::agent::auth::check(&hub.store, backend).await?["signedIn"] != true {
+ bail!("{} isn't signed in yet.", request["title"].as_str().unwrap_or("The agent"));
+ }
+ agent_signed_in(hub, backend)?;
+ return Ok(json!({"entry": hub.store.entry(id)}));
+ }
if kind == RequestKind::Login {
let login = super::logins::save(
&hub.store,
@@ -329,6 +405,31 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
+ #[tokio::test]
+ async fn signing_in_completes_the_card_and_sends_its_messages_again() {
+ let (hub, dir) = fixture();
+ let lane = Lane::main("bot");
+ let user =
+ |text: &str| hub.add_entry(&lane, EntryKind::User, 1, &json!({"text":text,"status":"sent"})).unwrap().id;
+ let (first, second) = (user("alpha-7"), user("bravo-9"));
+ invite_agent_sign_in(&hub, "bot", &lane, "fixture", "Fixture", std::slice::from_ref(&first)).unwrap();
+ invite_agent_sign_in(&hub, "bot", &lane, "fixture", "Fixture", &[second.clone(), first.clone()]).unwrap();
+ let cards = hub.store.pending_sign_ins("fixture").unwrap();
+ assert_eq!(cards.len(), 1, "a bot keeps one sign-in card");
+ assert_eq!(cards[0].data["connectionRequest"]["entryIds"], json!([first, second]));
+ agent_signed_in(&hub, "fixture").unwrap();
+ assert_eq!(hub.store.entry(&cards[0].id).unwrap().data["connectionRequest"]["status"], "ready");
+ let prompts = dir.join("prompts.jsonl");
+ let sent = tokio::time::timeout(std::time::Duration::from_secs(20), async {
+ while !std::fs::read_to_string(&prompts).is_ok_and(|p| p.contains("alpha-7") && p.contains("bravo-9")) {
+ tokio::time::sleep(std::time::Duration::from_millis(50)).await;
+ }
+ });
+ sent.await.expect("both messages go out again");
+ hub.shutdown().await;
+ std::fs::remove_dir_all(dir).unwrap();
+ }
+
#[tokio::test]
async fn cancellation_rejects_later_secret_submission() {
let (hub, dir) = fixture();
diff --git a/host/src/store/entries.rs b/host/src/store/entries.rs
index ca606575..d01cf9d8 100644
--- a/host/src/store/entries.rs
+++ b/host/src/store/entries.rs
@@ -138,6 +138,20 @@ impl Store {
Ok(rows)
}
+ /// Cards still waiting for the user to sign in to agent `backend`, oldest first.
+ // ponytail: scans notices without an index; sign-ins are rare, add one if it shows up in profiles.
+ pub fn pending_sign_ins(&self, backend: &str) -> Result<Vec<Entry>> {
+ let c = self.db.locked();
+ let mut st = c.prepare(&format!(
+ "SELECT {ENTRY_COLS} FROM entries WHERE kind = 'notice'
+ AND json_extract(data, '$.connectionRequest.kind') = 'agent'
+ AND json_extract(data, '$.connectionRequest.status') = 'pending'
+ AND json_extract(data, '$.connectionRequest.backend') = ?1
+ ORDER BY rev"
+ ))?;
+ Ok(st.query_map([backend], row_entry)?.collect::<rusqlite::Result<_>>()?)
+ }
+
/// Chat-visible messages (the user's, final replies) in any of `bot_id`'s lanes that
/// contain every term (case-insensitive for ASCII), newest first.
// ponytail: substring scan, no index (CJK needs no tokenizer this way); an FTS5 trigram table if it gets slow.
diff --git a/host/src/tui/app/forms.rs b/host/src/tui/app/forms.rs
index 481a4983..6aab6625 100644
--- a/host/src/tui/app/forms.rs
+++ b/host/src/tui/app/forms.rs
@@ -222,7 +222,7 @@ impl App {
KeyCode::Enter if field == Field::Agent => {
let backend = f.backend.clone();
self.overlays.push(Overlay::Form(f));
- self.open_agent(&backend);
+ self.open_agent(&backend, None);
return None;
}
KeyCode::Char('i') if field == Field::Skills => {
diff --git a/host/src/tui/connections.rs b/host/src/tui/connections.rs
index ec2c7f21..dc0eb719 100644
--- a/host/src/tui/connections.rs
+++ b/host/src/tui/connections.rs
@@ -99,7 +99,13 @@ impl App {
})
.cloned();
if let Some(entry) = entry {
- self.overlays.push(Overlay::Fields(Box::new(fields(&entry))));
+ let request = &entry.data["connectionRequest"];
+ if request["kind"] == "agent" {
+ // The host completes the request and resends the messages once a check finds it signed in.
+ self.open_agent(request["backend"].as_str().unwrap_or_default(), Some(entry.id.clone()));
+ } else {
+ self.overlays.push(Overlay::Fields(Box::new(fields(&entry))));
+ }
} else {
self.flash("No pending connection request here");
}
@@ -393,6 +399,41 @@ mod tests {
server.abort();
}
+ #[tokio::test]
+ async fn agent_sign_in_request_opens_the_agent_sheet_and_cancels_from_it() {
+ use crossterm::event::{KeyCode, KeyModifiers};
+ let (mut app, mut rx, calls, server) = fixture().await;
+ let request = json!({"kind":"agent","status":"pending","title":"Claude Code","backend":"claude"});
+ let e = Entry {
+ id: "card".into(),
+ seq: 1,
+ turn: 1,
+ kind: Kind::Notice,
+ data: json!({"connectionRequest":request}),
+ created_at: 0,
+ thread_id: None,
+ };
+ app.entries.entry("bot".into()).or_default().insert(1, e);
+ app.selected = Some("bot".into());
+ // Looking signed in doesn't skip the check: this agent just refused a turn.
+ app.backends = vec![json!({"id":"claude","signedIn":true})];
+ app.open_connection();
+ let Some(Overlay::Agent(a)) = app.overlays.last() else { panic!("agent sheet") };
+ assert_eq!((a.backend.as_str(), a.request.as_deref(), a.busy), ("claude", Some("card"), true));
+ reply(&mut app, &mut rx).await;
+ key(&mut app, KeyCode::Char('x'), KeyModifiers::CONTROL);
+ assert!(app.overlays.is_empty());
+ let cancel = json!({"method":"connectorRequestFinish","body":{"entryId":"card","cancel":true}});
+ let sent = tokio::time::timeout(std::time::Duration::from_secs(3), async {
+ while !calls.lock().unwrap().contains(&cancel) {
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ });
+ sent.await.expect("the request is cancelled");
+ assert_eq!(calls.lock().unwrap()[0], json!({"method":"agentAuth","body":{"backend":"claude"}}));
+ server.abort();
+ }
+
#[test]
fn login_fields_mask_the_password_and_keep_it_out_of_chat() {
let e = Entry {
diff --git a/host/src/tui/manage/agent.rs b/host/src/tui/manage/agent.rs
index 6a7979dc..655a7afe 100644
--- a/host/src/tui/manage/agent.rs
+++ b/host/src/tui/manage/agent.rs
@@ -7,11 +7,14 @@ use super::super::app::{After, App, Editor, Overlay};
use super::{AgentSetup, Fields, Input, Reply, SetupRow, Submit, ctrl, s};
impl App {
- pub fn open_agent(&mut self, backend: &str) {
+ /// `request`: the chat's sign-in request it's opened from, whose agent refused a turn: that
+ /// always asks the agent again, however signed in it looked.
+ pub fn open_agent(&mut self, backend: &str, request: Option<String>) {
let b = self.backends.iter().find(|b| b["id"] == backend);
// An agent without its Node.js can't start, so there's nothing to ask it yet.
- let known = b.is_some_and(|b| b["signedIn"] == true || b["node"] == "missing");
- let mut a = AgentSetup { backend: backend.to_owned(), auth: None, busy: false, cursor: 0, error: None };
+ let known = b.is_some_and(|b| (b["signedIn"] == true && request.is_none()) || b["node"] == "missing");
+ let mut a =
+ AgentSetup { backend: backend.to_owned(), auth: None, busy: false, cursor: 0, error: None, request };
if !known {
a.busy = true;
self.sheet("agentAuth", json!({"backend": backend}), Reply::Auth(backend.to_owned()));
@@ -46,6 +49,12 @@ impl App {
let rows = self.agent_rows(&a);
match k.code {
KeyCode::Esc | KeyCode::Char('q') => return None,
+ KeyCode::Char('x') if ctrl(k) && a.request.is_some() => {
+ let entry = a.request.take();
+ self.call("connectorRequestFinish", json!({"entryId": entry, "cancel": true}), After::Nothing);
+ self.flash("Sign-in request cancelled");
+ return None;
+ }
KeyCode::Down | KeyCode::Char('j') => a.cursor = (a.cursor + 1).min(rows.len().saturating_sub(1)),
KeyCode::Up | KeyCode::Char('k') => a.cursor = a.cursor.saturating_sub(1),
KeyCode::Enter if !a.busy => {
diff --git a/host/src/tui/manage/market.rs b/host/src/tui/manage/market.rs
index c57e793b..db89f449 100644
--- a/host/src/tui/manage/market.rs
+++ b/host/src/tui/manage/market.rs
@@ -168,7 +168,7 @@ impl App {
}
Act::Agent(id) => {
self.overlays.push(Overlay::Market(m));
- self.open_agent(&id);
+ self.open_agent(&id, None);
return None;
}
Act::SignIn(id) => {
diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rs
index 1f98ef15..84e69f93 100644
--- a/host/src/tui/manage/mod.rs
+++ b/host/src/tui/manage/mod.rs
@@ -143,6 +143,8 @@ pub struct AgentSetup {
pub busy: bool,
pub cursor: usize,
pub error: Option<String>,
+ /// The chat's sign-in request this was opened from (Ctrl+X cancels it).
+ pub request: Option<String>,
}
pub enum SetupRow {
diff --git a/host/src/tui/sheets.rs b/host/src/tui/sheets.rs
index 561c3f04..7a1a18ad 100644
--- a/host/src/tui/sheets.rs
+++ b/host/src/tui/sheets.rs
@@ -325,7 +325,12 @@ pub fn agent(buf: &mut Buffer, area: Rect, app: &App, a: &AgentSetup) {
);
y += 1;
}
- footer(buf, inner, a.error.as_deref(), "↑↓ move · ↵ run · esc back");
+ let keys = if a.request.is_some() {
+ "↑↓ move · ↵ run · ^x cancel request · esc back"
+ } else {
+ "↑↓ move · ↵ run · esc back"
+ };
+ footer(buf, inner, a.error.as_deref(), keys);
}
pub fn fields(buf: &mut Buffer, area: Rect, f: &Fields) {
diff --git a/host/src/tui/view/transcript.rs b/host/src/tui/view/transcript.rs
index 9e500a9e..8f18d90b 100644
--- a/host/src/tui/view/transcript.rs
+++ b/host/src/tui/view/transcript.rs
@@ -288,11 +288,16 @@ fn entry_lines(
return;
}
let text = if let Some(status) = e.data["connectionRequest"]["status"].as_str() {
+ let hint = if e.data["connectionRequest"]["kind"] == "agent" {
+ "C signs in / cancels"
+ } else {
+ "C connects / cancels"
+ };
format!(
"{} · {} · {}",
e.data["connectionRequest"]["title"].as_str().unwrap_or("Connect service"),
e.notice_text(),
- if status == "pending" { "C connects / cancels" } else { status }
+ if status == "pending" { hint } else { status }
)
} else {
e.notice_text()