Skip to content

The agent that grows with you

feat(onboarding): a new launch starts an unfinished onboarding over

alt-glitch0e90cc79854f
diff --git a/agent/onboarding_record.py b/agent/onboarding_record.py
index ab0b6ac6b57..ebe88bfd809 100644
--- a/agent/onboarding_record.py
+++ b/agent/onboarding_record.py
@@ -86,7 +86,8 @@ def _close_install_flag() -> None:
def start(db, session_id: str, facts: Facts) -> dict:
"""Write a fresh run record (the row must exist) and mark the install as mid-onboarding, so a
- crash before the end reopens this chat on the next launch."""
+ crash or a quit before the end runs onboarding again on the next launch (which starts over:
+ ``onboarding.start`` with ``fresh_launch``)."""
from hermes_cli.onboarding_run import set_run
record = new_record(facts, now=time.time(), run_id=uuid.uuid4().hex)
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index 72dce57a64c..4bb64229e28 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -54,7 +54,12 @@ import { $interfaceMode, shownInMode } from '@/store/interface-mode'
import { $pinnedSessionIds, pinSession, restoreWorktree, unpinSession } from '@/store/layout'
import { notifyError } from '@/store/notifications'
import { markOnboardingDecided } from '@/store/onboarding-presence'
-import { $onboardingChatOpener, decideOnboarding } from '@/store/onboarding-run'
+import {
+ $onboardingChatOpener,
+ decideOnboarding,
+ type OnboardingRequest,
+ type OnboardingResume
+} from '@/store/onboarding-run'
import { $poolLimitsSettingsRequest } from '@/store/pool-limits'
import { $previewTarget } from '@/store/preview'
import {
@@ -215,6 +220,29 @@ function useRouteRequestNavigation(navigate: ReturnType<typeof useNavigate>): vo
}, [navigate, routeRequest])
}
+// The main window asks the backend whether first-run onboarding is due and opens it with main's
+// intro around it; every other window never runs it, so its first-run surfaces are free at once.
+// Settings' Run onboarding again opens its chat through the same opener.
+function useFirstRunOnboarding(request: OnboardingRequest, open: OnboardingResume, gatewayOpen: boolean): void {
+ useEffect(() => {
+ if (!isMainWindow()) {
+ markOnboardingDecided()
+ } else if (gatewayOpen) {
+ void decideOnboarding(request, open, { intro: firstRunIntro() })
+ }
+ }, [gatewayOpen, open, request])
+
+ useEffect(() => {
+ if (!isMainWindow()) {
+ return
+ }
+
+ $onboardingChatOpener.set(open)
+
+ return () => $onboardingChatOpener.set(null)
+ }, [open])
+}
+
// Recovery actions raised by toast buttons (Restart Hermes, Open Billing, pool
// caps, cron review) fire from stores with no router context. Each counter is
// consumed here: the ref skips the initial mount value, and only a fresh
@@ -624,26 +652,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {
[navigate, resumeSession]
)
- // The main window asks the backend whether first-run onboarding is due and opens it with main's
- // intro around it; every other window never runs it, so its first-run surfaces are free at once.
- useEffect(() => {
- if (!isMainWindow()) {
- markOnboardingDecided()
- } else if (gatewayState === 'open') {
- void decideOnboarding(requestGateway, adoptSessionRoute, { intro: firstRunIntro() })
- }
- }, [adoptSessionRoute, gatewayState, requestGateway])
-
- // Settings' Run onboarding again opens its chat the way the launch does.
- useEffect(() => {
- if (!isMainWindow()) {
- return
- }
-
- $onboardingChatOpener.set(adoptSessionRoute)
-
- return () => $onboardingChatOpener.set(null)
- }, [adoptSessionRoute])
+ useFirstRunOnboarding(requestGateway, adoptSessionRoute, gatewayState === 'open')
// "New project" DRAG completion: the dialog created a project that was
// dropped onto a chat zone (tab-strip slot / pane edge / pane center). Open
diff --git a/apps/desktop/src/components/onboarding/first-run/kickoff.ts b/apps/desktop/src/components/onboarding/first-run/kickoff.ts
index 07a290b8338..625dd50ee92 100644
--- a/apps/desktop/src/components/onboarding/first-run/kickoff.ts
+++ b/apps/desktop/src/components/onboarding/first-run/kickoff.ts
@@ -10,7 +10,7 @@ import { $sessionStates } from '@/store/session-states'
import { $chatOnboardingThreadIds, openDemoLayout } from './assembly'
import { $introTurnSent, failIntro, leaveIntro, openIntro, startIntro } from './intro'
-// The opening turn writes the scripted greeting; a chat that already shows it (a relaunch) skips the copy.
+// The opening turn writes the scripted greeting; a chat that already shows it (a resumed run) skips the copy.
function hasAssistantWords(runtimeId: null | string): boolean {
const messages = runtimeId ? ($sessionStates.get()[runtimeId]?.messages ?? []) : []
@@ -21,7 +21,8 @@ function hasAssistantWords(runtimeId: null | string): boolean {
* Main's first-run start around `onboarding.start`: the boot overlay holds, the window takes the demo
* layout once the start answers, and the intro opens once the returned chat is the one on screen.
* `onboarding.start` has no deadline: past the boot budget the starting screen offers a way out, which
- * counts as Skip setup. A resumed run (a relaunch mid-run) reopens as a normal chat at normal size.
+ * counts as Skip setup. A resumed run (a start that found the run in progress) reopens as a normal chat
+ * at normal size; the launch and a rerun always start a new one.
*/
export function firstRunIntro(): OnboardingIntroHooks {
let offerExit: ReturnType<typeof setTimeout> | undefined
diff --git a/apps/desktop/src/store/onboarding-run.test.ts b/apps/desktop/src/store/onboarding-run.test.ts
index 2c7df972500..7aca6d88a0e 100644
--- a/apps/desktop/src/store/onboarding-run.test.ts
+++ b/apps/desktop/src/store/onboarding-run.test.ts
@@ -13,7 +13,7 @@ import {
} from './onboarding-run'
import { isOnboardingChat } from './onboarding-session'
import { $activeGatewayProfile, $freshSessionRequest, $newChatProfile } from './profile'
-import { $connection, $selectedStoredSessionId } from './session'
+import { $connection, $gatewayState, $selectedStoredSessionId } from './session'
import { $sessionTiles } from './session-states'
const ensureProfile = async (): Promise<void> => undefined
@@ -24,17 +24,22 @@ const resume = vi.fn(async (storedId: string) => $selectedStoredSessionId.set(st
// `runId`: the run onboarding.state reports open; null once something ended it.
function backend(state: { eligible: boolean; run: boolean }, runId: null | string = 'run-1') {
const calls: string[] = []
+ const starts: unknown[] = []
const started = { resumed: false, run_id: 'run-1', session_id: 'rt-1', stored_session_id: 'st-1' }
const read = { ...state, run_id: runId, session_id: runId && 'st-1' }
- const request = async <T,>(method: string): Promise<T> => {
+ const request = async <T,>(method: string, params?: unknown): Promise<T> => {
calls.push(method)
+ if (method === 'onboarding.start') {
+ starts.push(params)
+ }
+
// SAFETY: the fake answers onboarding.state and onboarding.start with their contract result shapes.
return (method === 'onboarding.state' ? read : started) as T
}
- return { calls, request }
+ return { calls, request, starts }
}
beforeEach(() => {
@@ -50,18 +55,35 @@ describe('onboarding run', () => {
it('opens the onboarding chat when due and never shows a clear moment before it', async () => {
const clear: boolean[] = []
const stop = $onboardingSurfaceClear.subscribe(value => clear.push(value))
- const { calls, request } = backend({ eligible: true, run: true })
+ const { calls, request, starts } = backend({ eligible: true, run: true })
await decideOnboarding(request, resume, { ensureProfile })
stop()
// The last read checks for an end sent while the chat was opening.
expect(calls).toEqual(['onboarding.state', 'onboarding.start', 'onboarding.state'])
+ // A new launch: a run the app was closed on does not count, so the backend starts over.
+ expect(starts).toEqual([expect.objectContaining({ fresh_launch: true })])
expect(resume).toHaveBeenCalledWith('st-1', true)
expect($onboardingDecided.get()).toBe(true)
expect(clear).not.toContain(true)
})
+ it('keeps the run on a reconnect in the same launch: it is re-read, never started again', async () => {
+ const { calls, request, starts } = backend({ eligible: true, run: true })
+ await startOnboarding(request, resume, { ensureProfile })
+ calls.length = 0
+
+ $gatewayState.set('closed')
+ $gatewayState.set('open')
+ // The wiring effect runs the launch decision again on every open socket; it answered once already.
+ await decideOnboarding(request, resume, { ensureProfile })
+
+ await vi.waitFor(() => expect(calls).toEqual(['onboarding.state']))
+ expect(starts).toEqual([expect.not.objectContaining({ fresh_launch: true })])
+ expect($onboardingPhase.get()).toBe('shown')
+ })
+
it('ends once when the backend reports the run done, and frees the first-run surfaces', async () => {
const { request } = backend({ eligible: true, run: true })
diff --git a/apps/desktop/src/store/onboarding-run.ts b/apps/desktop/src/store/onboarding-run.ts
index 88700be9d57..eecd895b23c 100644
--- a/apps/desktop/src/store/onboarding-run.ts
+++ b/apps/desktop/src/store/onboarding-run.ts
@@ -101,15 +101,18 @@ export interface OnboardingIntroHooks {
interface StartOptions {
/** Points the window's gateway at the profile onboarding runs in (`store/profile.ts::ensureGatewayProfile`). */
ensureProfile?: (profile: string) => Promise<void>
+ /** The launch's start: a run the app was closed on does not count, so the backend deletes its chat
+ * and starts over (`decideOnboarding` only). */
+ freshLaunch?: boolean
intro?: OnboardingIntroHooks
rerun?: boolean
}
-/** Open the onboarding chat (a new one for a rerun, else the run in progress or a new one). */
+/** Open the onboarding chat (a new one for a rerun or a launch, else the run in progress or a new one). */
export async function startOnboarding(
request: OnboardingRequest,
resume: OnboardingResume,
- { ensureProfile = ensureGatewayProfile, intro, rerun = false }: StartOptions = {}
+ { ensureProfile = ensureGatewayProfile, freshLaunch = false, intro, rerun = false }: StartOptions = {}
): Promise<boolean> {
// A rerun withdraws the old run's card; its skipped_all must not match this window's session.
$onboardingSession.set(null)
@@ -131,7 +134,7 @@ export async function startOnboarding(
// The request stays alive past the way out: its answer names the run the skip ends.
const started = await request<OnboardingStartResult>(
'onboarding.start',
- { facts_source: factsSource(), locale: getRuntimeI18nLocale(), rerun },
+ { facts_source: factsSource(), fresh_launch: freshLaunch, locale: getRuntimeI18nLocale(), rerun },
intro ? NO_DEADLINE : undefined
)
@@ -187,7 +190,8 @@ let decision: null | Promise<void> = null
/**
* The main window's boot check, once per launch: open onboarding when the backend says it is due on
- * this install and the free tier can drive it. First-run surfaces wait until this has answered; the
+ * this install and the free tier can drive it. The launch starts the run over (`freshLaunch`); a
+ * reconnect later in the launch only re-reads it (`watchRunEnd`). First-run surfaces wait until this has answered; the
* presence surface is set before the answer is published, so they never see a clear moment in between.
*/
export function decideOnboarding(
@@ -206,7 +210,7 @@ async function readAndStart(request: OnboardingRequest, resume: OnboardingResume
const state = await request<OnboardingRunStateResult>('onboarding.state', undefined, ONBOARDING_DECIDE_DEADLINE_MS)
if (state.run && state.eligible) {
- await startOnboarding(request, resume, options)
+ await startOnboarding(request, resume, { ...options, freshLaunch: true })
}
} catch (error) {
console.warn('[onboarding] state could not be read', error)
diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.ts
index 96582abe8d1..37b055f69d7 100644
--- a/apps/shared/src/gateway-contract.generated.ts
+++ b/apps/shared/src/gateway-contract.generated.ts
@@ -2214,9 +2214,10 @@ export interface OnboardingSetRunParams {
run: boolean
mark_profile_offered?: boolean
}
-/** ``rerun``: start a new onboarding chat even when one is in progress (Settings, Run onboarding again). ``facts_source``: whether the backend runs on the user's own computer. ``locale``: the desktop's UI language, preferred over the backend OS locale. */
+/** ``rerun``: start a new onboarding chat even when one is in progress (Settings, Run onboarding again). ``fresh_launch``: the app's once-per-launch start; a run the app was closed on does not count, so its chat is deleted and the run starts over. ``facts_source``: whether the backend runs on the user's own computer. ``locale``: the desktop's UI language, preferred over the backend OS locale. */
export interface OnboardingStartParams {
rerun?: boolean
+ fresh_launch?: boolean
facts_source?: OnboardingFactsSource
locale?: string | null
}
diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.json
index b3bbdb22c01..a52eaf1dfc1 100644
--- a/apps/shared/src/gateway-contract.openrpc.json
+++ b/apps/shared/src/gateway-contract.openrpc.json
@@ -20649,13 +20649,18 @@
},
"OnboardingStartParams": {
"additionalProperties": false,
- "description": "``rerun``: start a new onboarding chat even when one is in progress (Settings, Run onboarding\nagain). ``facts_source``: whether the backend runs on the user's own computer. ``locale``: the\ndesktop's UI language, preferred over the backend OS locale.",
+ "description": "``rerun``: start a new onboarding chat even when one is in progress (Settings, Run onboarding\nagain). ``fresh_launch``: the app's once-per-launch start; a run the app was closed on does not\ncount, so its chat is deleted and the run starts over. ``facts_source``: whether the backend runs\non the user's own computer. ``locale``: the desktop's UI language, preferred over the backend OS\nlocale.",
"properties": {
"rerun": {
"default": false,
"title": "Rerun",
"type": "boolean"
},
+ "fresh_launch": {
+ "default": false,
+ "title": "Fresh Launch",
+ "type": "boolean"
+ },
"facts_source": {
"$ref": "#/components/schemas/OnboardingFactsSource",
"default": "local"
diff --git a/tests/tui_gateway/test_onboarding_fresh_launch.py b/tests/tui_gateway/test_onboarding_fresh_launch.py
new file mode 100644
index 00000000000..cb7a373137a
--- /dev/null
+++ b/tests/tui_gateway/test_onboarding_fresh_launch.py
@@ -0,0 +1,110 @@
+"""Closing the app before onboarding finishes does not count: the next launch's ``onboarding.start``
+(``fresh_launch``) deletes the unfinished chat and starts over at the name beat, while a second window
+or a reconnect in the same launch (no flag) keeps the run."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from agent import onboarding_record
+from agent.onboarding_flow import PENDING, Answered, Facts, Shown
+from hermes_cli.config import read_user_config_raw
+from tui_gateway import server
+
+FACTS = Facts(os="macos", arch="arm64", machine_kind="Mac", plugins=())
+
+
+def root(tmp_path, monkeypatch) -> Path:
+ home = tmp_path / ".hermes"
+ home.mkdir()
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ monkeypatch.setenv("HERMES_HOME", str(home))
+ monkeypatch.setattr(server, "_hermes_home", str(home))
+ monkeypatch.setattr(server, "_db", None)
+ monkeypatch.setattr("agent.onboarding_facts.read_facts", lambda **kw: FACTS)
+ return home
+
+
+def client(root, monkeypatch) -> list:
+ """session.resume and prompt.submit as a recorder; a submit stores its user turn, as the real turn does."""
+ calls = []
+
+ def resume(rid, params):
+ calls.append(("resume", params))
+ return {"result": {"session_id": f"rt-{params['session_id']}"}}
+
+ def submit(rid, params):
+ calls.append(("submit", params))
+ server._get_db().append_message(params["session_id"].removeprefix("rt-"), "user", params["text"])
+ return {"result": {"status": "streaming"}}
+
+ monkeypatch.setitem(server._methods, "session.resume", resume)
+ monkeypatch.setitem(server._methods, "prompt.submit", submit)
+ return calls
+
+
+def ended(monkeypatch) -> list[dict]:
+ told: list[dict] = []
+ monkeypatch.setattr(onboarding_record, "_ended_listeners", [told.append])
+ return told
+
+
+def _start(params: dict | None = None) -> dict:
+ response = server.handle_request({"jsonrpc": "2.0", "id": 7, "method": "onboarding.start", "params": params or {}})
+ assert "result" in response, response
+ return response["result"]
+
+
+def _run_flag(root: Path) -> bool:
+ return read_user_config_raw(root / "config.yaml")["onboarding"]["run"]
+
+
+def test_a_new_launch_deletes_the_unfinished_chat_and_starts_over_at_the_name_beat(root, client, ended):
+ first = _start({"fresh_launch": True})
+ old = first["stored_session_id"]
+ db = server._get_db()
+ old_title = db.get_session(old)["title"]
+ # The user got past the name card, then quit the app.
+ onboarding_record.advance(db, old, Shown("name"))
+ onboarding_record.advance(db, old, Answered("name", {"name": "Sid"}))
+ assert onboarding_record.load(db, old)["beats"]["name"] != PENDING
+
+ again = _start({"fresh_launch": True})
+ new = again["stored_session_id"]
+
+ assert new != old and again["resumed"] is False and again["run_id"] != first["run_id"]
+ assert db.get_session(old) is None
+ assert [(e["stored_session_id"], e["outcome"]) for e in ended] == [(old, "deleted")]
+ record = onboarding_record.load(db, new)
+ assert onboarding_record.active_session_id(db) == new and record["beats"]["name"] == PENDING
+ # The fresh chat plays the opening again, under the title the deleted chat had.
+ assert [kind for kind, _ in client] == ["resume", "submit", "resume", "submit"]
+ assert db.get_session(new)["title"] == old_title
+ assert _run_flag(root) is True
+
+
+def test_a_second_window_or_a_reconnect_keeps_the_run(root, client, ended):
+ first = _start({"fresh_launch": True})
+
+ again = _start()
+
+ assert again["stored_session_id"] == first["stored_session_id"] and again["resumed"] is True
+ assert again["run_id"] == first["run_id"] and ended == []
+
+
+def test_a_new_launch_closes_the_unfinished_chat_still_live_here_before_deleting_it(root, client, ended, monkeypatch):
+ old = _start({"fresh_launch": True})["stored_session_id"]
+ closed = []
+ monkeypatch.setitem(server._sessions, "rt-live", {"session_key": old})
+ monkeypatch.setattr(server, "_close_session_by_id",
+ lambda sid, **kw: closed.append((sid, server._get_db().get_session(old) is not None)))
+
+ _start({"fresh_launch": True})
+
+ assert closed == [("rt-live", True)]
+ assert server._get_db().get_session(old) is None
diff --git a/tests/tui_gateway/test_onboarding_session.py b/tests/tui_gateway/test_onboarding_session.py
index ce9f3523563..0de3c4905e9 100644
--- a/tests/tui_gateway/test_onboarding_session.py
+++ b/tests/tui_gateway/test_onboarding_session.py
@@ -68,7 +68,8 @@ def test_start_creates_one_onboarding_chat_and_plays_the_opening_once(client):
assert "first-run onboarding" in submitted["text"] and "setup_beat" in submitted["text"]
assert _call("onboarding.state")["result"]["session_id"] == stored
- # A relaunch reopens the same chat without a second opening; rerun starts a new one.
+ # A start without fresh_launch (a second window, a reconnect) reopens the same chat without a
+ # second opening; rerun starts a new one.
again = _call("onboarding.start")["result"]
assert again["stored_session_id"] == stored and again["resumed"] is True and len(client) == 3
assert _call("onboarding.start", {"rerun": True})["result"]["stored_session_id"] != stored
diff --git a/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py b/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py
index 9bf7004f641..c9841005003 100644
--- a/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py
+++ b/tui_gateway/contracts/profiles_vault_complete_foreign_subagents.py
@@ -433,10 +433,13 @@ class OnboardingFactsSource(WireEnum):
class OnboardingStartParams(Params):
"""``rerun``: start a new onboarding chat even when one is in progress (Settings, Run onboarding
- again). ``facts_source``: whether the backend runs on the user's own computer. ``locale``: the
- desktop's UI language, preferred over the backend OS locale."""
+ again). ``fresh_launch``: the app's once-per-launch start; a run the app was closed on does not
+ count, so its chat is deleted and the run starts over. ``facts_source``: whether the backend runs
+ on the user's own computer. ``locale``: the desktop's UI language, preferred over the backend OS
+ locale."""
rerun: bool = False
+ fresh_launch: bool = False
facts_source: OnboardingFactsSource = OnboardingFactsSource.local
locale: str | None = None
diff --git a/tui_gateway/methods_onboarding.py b/tui_gateway/methods_onboarding.py
index 0b743cbf99c..4463198c1af 100644
--- a/tui_gateway/methods_onboarding.py
+++ b/tui_gateway/methods_onboarding.py
@@ -97,6 +97,9 @@ def _(rid, params: dict) -> dict:
from agent.onboarding_flow import End, Facts
from agent.onboarding_record import advance, load, open_session_ids, start
from agent.onboarding_text import CHAT_TITLE, opening_prompt
+ # The app's once-per-launch start: closing the app mid-run does not count, so that run's chat goes
+ # and the run starts over. A second window or a reconnect sends no flag and gets the run back.
+ fresh_launch = bool(params.get("fresh_launch"))
# Held through the opening submit: two windows pressing start at once get one chat and one opening.
with _onboarding_start_lock:
try:
@@ -104,7 +107,7 @@ def _(rid, params: dict) -> dict:
if db is None:
return _db_unavailable_error(rid, code=5000)
open_ids = open_session_ids(db)
- stored = None if params.get("rerun") else next(iter(open_ids), None)
+ stored = None if params.get("rerun") or fresh_launch else next(iter(open_ids), None)
created = stored is None
if created:
# The tours setting is the default profile's, whichever profile launched the backend.
@@ -113,7 +116,6 @@ def _(rid, params: dict) -> dict:
hydrate_secrets=False):
facts = read_facts(facts_source=params.get("facts_source") or "local", locale=params.get("locale"))
stored = db.create_session(new_session_id(), "desktop")
- db.set_session_title(stored, db.get_next_title_in_lineage(CHAT_TITLE))
# The record exists before the agent is built, so the build folds the onboarding toolset in.
start(db, stored, facts)
else:
@@ -122,14 +124,20 @@ def _(rid, params: dict) -> dict:
# One open run at a time. The kept run is open before the others end, so the install
# flag never closes in between; finishing it closes the flag.
replaced = [sid for sid in open_ids if sid != stored]
- for old in replaced:
- advance(db, old, End("replaced"))
+ if fresh_launch:
+ _discard_unfinished_runs(db, replaced)
+ else:
+ for old in replaced:
+ advance(db, old, End("replaced"))
+ if created:
+ # After the discard, so a run started over keeps the title its deleted chat had.
+ db.set_session_title(stored, db.get_next_title_in_lineage(CHAT_TITLE))
# A chat with no messages never got its opening (a restart between start and the first turn).
opening = None if (db.get_session(stored) or {}).get("message_count") else opening_prompt(facts)
except Exception as e:
logger.exception("onboarding.start failed")
return _err(rid, 5078, str(e))
- _withdraw_setup_cards(replaced)
+ _withdraw_setup_cards([] if fresh_launch else replaced)
resumed = _methods["session.resume"](rid, {**_ONBOARDING_PROFILE, "session_id": stored, "source": "desktop"})
if "error" in resumed:
return resumed
@@ -160,17 +168,42 @@ def _(rid, params: dict) -> dict:
return _ok(rid, {"skipped": bool(step.result.get("skipped_all"))})
-def _withdraw_setup_cards(stored_ids: list[str]) -> None:
- """Close the card still waiting in a chat whose run just ended; its answer would be refused."""
+def _live_session_ids(stored_ids: list[str]) -> list[str]:
+ """The live sessions here that show one of *stored_ids*."""
if not stored_ids:
- return
+ return []
with _sessions_lock:
- live = [sid for sid, sess in _sessions.items()
+ return [sid for sid, sess in _sessions.items()
if (getattr(sess.get("agent"), "session_id", None) or sess.get("session_key")) in stored_ids]
- for sid in live:
+
+
+def _withdraw_setup_cards(stored_ids: list[str]) -> None:
+ """Close the card still waiting in a chat whose run just ended; its answer would be refused."""
+ for sid in _live_session_ids(stored_ids):
_cancel_session_requests(sid, "resolved", method="setup_beat")
+def _discard_unfinished_runs(db, stored_ids: list[str]) -> None:
+ """A new launch's start: the runs the app was closed on never count as done. Each chat is closed if
+ still live here (a backend that outlived the app), then deleted the way ``session.delete`` deletes
+ it, which ends its run (``deleted``) and tells every window. A chat the delete refuses keeps its
+ messages, and its run ends as ``replaced`` so it is never resumed."""
+ from agent.onboarding_flow import End
+ from agent.onboarding_record import advance, delete_chat
+ for sid in _live_session_ids(stored_ids):
+ _close_session_by_id(sid, end_reason="onboarding_restart")
+ sessions_dir = Path(_profile_home("default") or get_hermes_home()) / "sessions"
+ for old in stored_ids:
+ try:
+ deleted = delete_chat(db, old, lambda old=old: db.delete_session(
+ old, sessions_dir=sessions_dir, exclude_active_write_guards=True))
+ except Exception:
+ logger.exception("onboarding.start could not delete unfinished chat %s", old)
+ deleted = False
+ if not deleted:
+ advance(db, old, End("replaced"))
+
+
def _setup_beat_request(sid: str, payload: dict) -> dict | None:
from agent.onboarding_flow import CARD_TIMEOUT_S
from tui_gateway import server_requests