Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Working line: no "getting started" after steps or after a reload (#284)

Oleksandr Ivanchenko416804e170f8
diff --git a/docs/live-activity.md b/docs/live-activity.md
index f233c010..184dfd53 100644
--- a/docs/live-activity.md
+++ b/docs/live-activity.md
@@ -71,6 +71,14 @@ The saved bot reply (message `meta`, a JSON string in the message row) gets:
16,000 thinking characters per reply (the rest is cut with "…"). Titles are cut at 160 characters
and details at 500. Steps still open when the turn ended are saved as `stopped`.
+### Loading mid-turn: `activity` on `GET /api/turns`
+
+A turn that is still running has no saved reply yet. `GET /api/turns` lists each running turn with
+its steps so far under `activity`, in the same shape (`{ "steps": [ <step>, … ] }`). Queued turns
+and turns with no steps yet have no `activity`. Clients seed their live steps from it on load and
+on every reconnect, so the working line shows the open step instead of "getting started". Thinking
+text that streamed before the load is not included; the thinking step's title still shows.
+
### Redaction
Titles, details and thinking text pass through redaction before they leave the server:
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index c83c3a2f..0b60d609 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -17,7 +17,7 @@ import { QuestionCard } from './components/QuestionCard';
import { HumanStepCard } from './components/HumanStepCard';
import { StarAsk } from './components/StarAsk';
import { starAskStore } from './starAsk';
-import { LiveActivity, appendThinking, applyActivity, parseStep } from './activity';
+import { LiveActivity, appendThinking, applyActivity, parseStep, seedActivity } from './activity';
import {
HumanStep,
HumanStepMeta,
@@ -636,6 +636,13 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
turnsRef.current = map;
setTurns(map);
resetTurns(Object.values(map).filter((t) => t.state === 'running'));
+ // A page opened (or back) mid-turn: what each running bot is doing now, not "getting started".
+ let seeded = activityRef.current;
+ for (const t of Object.values(map)) {
+ const next = t.state === 'running' ? seedActivity(seeded[t.turn_id], t.turn_id, t.activity) : null;
+ if (next) seeded = { ...seeded, [t.turn_id]: { ...next, ctx: t.context_id } };
+ }
+ if (seeded !== activityRef.current) setActivityMap(seeded);
const busy = new Set(Object.values(map).map((t) => t.context_id));
for (const ctx of Object.keys(liveRef.current)) {
if (!busy.has(ctx) && !discussionInProgressRef.current) clearLive(ctx);
diff --git a/frontend/src/activity.ts b/frontend/src/activity.ts
index 137e3f58..17867581 100644
--- a/frontend/src/activity.ts
+++ b/frontend/src/activity.ts
@@ -81,6 +81,17 @@ export function applyActivity(prev: LiveActivity | undefined, turnId: string, st
return { ...base, steps };
}
+/**
+ * After a load or reconnect: a running turn's steps so far, from `GET /api/turns` (its `activity`,
+ * shaped like `meta.activity`). Each goes through `applyActivity`, so steps that already came live
+ * keep their place and a settled step never goes back to running. Null when there is nothing to add.
+ */
+export function seedActivity(prev: LiveActivity | undefined, turnId: string, raw: unknown): LiveActivity | null {
+ const saved = parseActivityMeta({ activity: raw });
+ if (!saved?.steps.length) return null;
+ return saved.steps.reduce<LiveActivity>((acc, step) => applyActivity(acc, turnId, step), prev?.turnId === turnId ? prev : { turnId, steps: [], thinking: {} });
+}
+
/** The thinking step text is streaming into right now, if any. */
export function runningThinking(live: LiveActivity | undefined, turnId?: string): ActivityStep | null {
if (!live || (turnId && live.turnId !== turnId)) return null;
diff --git a/frontend/src/threads.ts b/frontend/src/threads.ts
index deb21cb8..a6ea158a 100644
--- a/frontend/src/threads.ts
+++ b/frontend/src/threads.ts
@@ -31,6 +31,8 @@ export interface ActiveTurn {
since?: string;
/** "decide": a consult or decide turn of the decide-first gate. */
purpose?: string;
+ /** A running turn's steps so far (like `meta.activity`), so a page opened mid-turn can show them. */
+ activity?: unknown;
}
export interface Thread {
diff --git a/frontend/src/workingStrip.ts b/frontend/src/workingStrip.ts
index a4bd0dfd..ac46cf80 100644
--- a/frontend/src/workingStrip.ts
+++ b/frontend/src/workingStrip.ts
@@ -22,6 +22,8 @@ export function workingLabel(s: WorkingState): string {
if (t) return lower(t);
}
if (s.writing) return 'writing the reply';
+ // Steps already ran (a tool finished, the next one isn't open yet): still working, not starting.
+ if (s.live?.steps.length) return 'working on it';
return 'getting started';
}
diff --git a/frontend/tests/activity.test.mjs b/frontend/tests/activity.test.mjs
index 3e44cb06..6788a7b1 100644
--- a/frontend/tests/activity.test.mjs
+++ b/frontend/tests/activity.test.mjs
@@ -98,3 +98,21 @@ test('saved list starts collapsed to the summary; the engine note waits inside t
assert.equal(a.hasThinkingText(activity), false);
assert.equal(a.hasThinkingText({ steps: [step({ kind: 'thinking', status: 'done', text: 'hm' })], dropped: 0 }), true);
});
+
+test('a page opened mid-turn seeds the open step from /api/turns (ticket 4)', async () => {
+ const w = await loadBundled(`export * from './src/workingStrip';`);
+ const fromServer = { steps: [step({ id: 'a', status: 'ok', title: 'Running `ls`' }), step({ id: 'b', title: 'Using `web_search`' })] };
+ // Fresh load: nothing came live yet.
+ const seeded = a.seedActivity(undefined, 't1', fromServer);
+ assert.deepEqual(seeded.steps.map((s) => s.id), ['a', 'b']);
+ assert.equal(w.workingLabel({ live: seeded }), 'using web_search');
+ // Reconnect: a step that already settled live stays settled; live order is kept.
+ const live = { turnId: 't1', thinking: { x: 'hm' }, steps: [step({ id: 'b', status: 'ok', title: 'Using `web_search`' })] };
+ const merged = a.seedActivity(live, 't1', fromServer);
+ assert.deepEqual(merged.steps.map((s) => [s.id, s.status]), [['b', 'ok'], ['a', 'ok']]);
+ assert.equal(merged.thinking.x, 'hm');
+ // Nothing to add: no activity, junk, or no steps.
+ assert.equal(a.seedActivity(undefined, 't1', undefined), null);
+ assert.equal(a.seedActivity(undefined, 't1', { steps: [] }), null);
+ assert.equal(a.seedActivity(undefined, 't1', 'nope'), null);
+});
diff --git a/frontend/tests/signature.test.mjs b/frontend/tests/signature.test.mjs
index 8e4c4994..7f6fb906 100644
--- a/frontend/tests/signature.test.mjs
+++ b/frontend/tests/signature.test.mjs
@@ -126,6 +126,18 @@ test('working strip: the label follows the open step, then falls back', () => {
assert.equal(w.workingLabel({ awaitingAnswer: true, awaitingBrowser: true }), 'waiting for you in the browser');
});
+test('working strip: never "getting started" once the turn has steps (ticket 2)', () => {
+ const step = (over = {}) => ({ id: 's1', kind: 'tool', status: 'ok', title: 'Running `ls`', started_at: '2026-11-04T10:00:00Z', ...over });
+ const done = { turnId: 't', thinking: {}, steps: [step(), step({ id: 's2', kind: 'thinking', title: 'Thinking' })] };
+ // Between steps (a finished tool, nothing open yet) the bot is still working, not starting.
+ assert.equal(w.workingLabel({ live: done }), 'working on it');
+ // An open step still wins, and so does the reply once it streams.
+ assert.equal(w.workingLabel({ live: { ...done, steps: [...done.steps, step({ id: 's3', status: 'running', title: 'Using `web_search`' })] } }), 'using web_search');
+ assert.equal(w.workingLabel({ live: done, writing: true }), 'writing the reply');
+ // No steps at all: the turn really is just starting.
+ assert.equal(w.workingLabel({ live: { turnId: 't', thinking: {}, steps: [] } }), 'getting started');
+});
+
test('elapsed time reads m:ss and h:mm:ss, never negative', () => {
assert.equal(w.formatElapsed(0), '0:00');
assert.equal(w.formatElapsed(42_900), '0:42');
diff --git a/src/server/activity.rs b/src/server/activity.rs
index 43c792c9..d76a9131 100644
--- a/src/server/activity.rs
+++ b/src/server/activity.rs
@@ -106,6 +106,18 @@ pub fn approval_settled(turn_id: &str, ticket: &str, status: &'static str) {
}
}
+/// A running turn as `GET /api/turns` lists it, with its steps so far under `activity` (as
+/// `meta.activity`), so a page that loads or reconnects mid-turn shows what the bot is doing now
+/// instead of starting from no steps. Queued turns and turns with no steps yet have none.
+pub fn turn_view(turn: &super::turns::ActiveTurn) -> Value {
+ let mut v = serde_json::to_value(turn).unwrap_or(Value::Null);
+ let steps = TurnActivity::find(&turn.turn_id).and_then(|t| t.with_log(|log| (!log.is_empty()).then(|| log.to_json())));
+ if let (Some(steps), Some(obj)) = (steps, v.as_object_mut()) {
+ obj.insert("activity".into(), steps);
+ }
+ v
+}
+
/// Adds `meta.activity` to a reply's meta.
pub fn with_activity(meta: Option<Value>, activity: Option<Value>) -> Option<Value> {
let Some(activity) = activity else { return meta };
@@ -143,4 +155,29 @@ mod tests {
assert!(TurnActivity::find("turn-activity-test").is_none());
assert_eq!(with_activity(None, Some(json!({"steps": []}))).unwrap()["activity"]["steps"], json!([]));
}
+
+ /// Ticket 4: a page that loads mid-turn gets the open step from `GET /api/turns`.
+ #[test]
+ fn listed_turn_carries_its_steps_so_far() {
+ let active = |turn_id: &str| super::super::turns::ActiveTurn {
+ turn_id: turn_id.into(),
+ kwant_id: "k".into(),
+ context_id: "c".into(),
+ thread_id: None,
+ state: "running".into(),
+ since: chrono::Utc::now(),
+ purpose: None,
+ };
+ let tag = TurnTag { turn_id: "turn-view-test".into(), kwant_id: "k".into(), context_id: "c".into(), thread_id: None };
+ let turn = TurnActivity::start(broadcast::channel(16).0, tag);
+ assert!(turn_view(&active("turn-view-test")).get("activity").is_none(), "no steps yet: no activity");
+ turn.observe(&RuntimeEvent::ToolCallPending { id: "1".into(), name: "Bash".into(), args: json!({"command": "ls"}) });
+ let v = turn_view(&active("turn-view-test"));
+ assert_eq!(v["turn_id"], "turn-view-test");
+ assert_eq!(v["state"], "running");
+ assert_eq!(v["activity"]["steps"][0]["title"], "Running `ls`");
+ assert_eq!(v["activity"]["steps"][0]["status"], "running");
+ assert!(turn_view(&active("some-other-turn")).get("activity").is_none());
+ drop(turn);
+ }
}
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 96e61947..d11dd0c5 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -1503,7 +1503,7 @@ pub async fn list_turns(State(state): State<AppState>, super::spaces::Scope(spac
for t in state.turns.active_turns() {
let of = state.db.space_of_kwant(&t.kwant_id).await.ok().flatten().unwrap_or_else(crate::db::spaces::SpaceId::default_space);
if of == space {
- turns.push(t);
+ turns.push(super::activity::turn_view(&t));
}
}
Json(json!({ "turns": turns, "max_turns_per_agent": per_agent, "max_turns_global": global })).into_response()