Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(society): isolate routine chats and navigate execution history
Ruben Lütke24cf16888767
diff --git a/jarvis/agent_chat/control.py b/jarvis/agent_chat/control.pyindex f8da7af5a4..33cbb6fc9c 100644--- a/jarvis/agent_chat/control.py+++ b/jarvis/agent_chat/control.py@@ -366,7 +366,9 @@ class ChatControls:executor = getattr(brain, "_tool_executor", None)if runtime is None or executor is None:raise ValueError("Agent tools are still starting")- agent_id = sid.removeprefix("society:") if session.surface == "society" else "jarvis"+ from jarvis.society.surface import agent_id_of++ agent_id = (agent_id_of(sid) or "") if session.surface == "society" else "jarvis"tool: Anyif command == "message":match = re.fullmatch(r'@(?P<target>"[^"]+"|\S+)\s+(?P<text>[\s\S]+)', arguments)diff --git a/jarvis/agent_chat/runner_cli.py b/jarvis/agent_chat/runner_cli.pyindex a84f5a48f6..127c99e691 100644--- a/jarvis/agent_chat/runner_cli.py+++ b/jarvis/agent_chat/runner_cli.py@@ -782,7 +782,7 @@ def _agy_catalog_cached() -> list[dict[str, Any]] | None:return rows if isinstance(rows, list) else None-def read_agy_models(timeout_s: float = 8.0) -> list[dict[str, Any]]:+def read_agy_models(timeout_s: float = 8.0, *, required_model: str = "") -> list[dict[str, Any]]:"""``agy --output-format json models`` -> the folded catalog (cached 10 min).Blocking (a ~2 s subprocess) — call it off the event loop. Any failure@@ -792,8 +792,10 @@ def read_agy_models(timeout_s: float = 8.0) -> list[dict[str, Any]]:import subprocessnow = time.monotonic()- if _AGY_CATALOG["rows"] is not None and now - _AGY_CATALOG["at"] < _AGY_CATALOG_TTL_S:- return list(_AGY_CATALOG["rows"])+ cached = _agy_catalog_cached()+ model_known = not required_model or any(row["id"] == required_model for row in cached or [])+ if cached is not None and model_known and now - _AGY_CATALOG["at"] < _AGY_CATALOG_TTL_S:+ return list(cached)raw: list[dict[str, Any]] | None = Nonetry:argv = [*agy_argv_prefix(), "--output-format", "json", "models"]@@ -2652,7 +2654,7 @@ async def _run_cli_once(# A chat can start before the model picker has loaded its catalog.# Resolve the installed CLI's effort ladder off the event loop so# newly available models keep the required model/effort pairing.- await asyncio.to_thread(read_agy_models)+ await asyncio.to_thread(read_agy_models, required_model=session.model)plan: CliPlan = planner(prompt=user_text,cwd=cwd,diff --git a/jarvis/society/routine_runner.py b/jarvis/society/routine_runner.pyindex a459b5a19f..611cfbe525 100644--- a/jarvis/society/routine_runner.py+++ b/jarvis/society/routine_runner.py@@ -1,11 +1,12 @@-"""Run a scheduled task through the owner's canonical chat and current policy."""+"""Run each scheduled execution in its own persisted, unattended owner chat."""from __future__ import annotationsimport asynciofrom typing import Any+from uuid import uuid4-from .chat_binding import ensure_session+from .chat_binding import SURFACE, _workspace, pair_forfrom .routines import agent_id_from_tags@@ -23,7 +24,11 @@ async def guard_owned_routine(runtime: Any, tags: tuple[str, ...]) -> Any:async def run_owned_routine(- runtime: Any, task_id: str, tags: tuple[str, ...], prompt: str, cancel_token: Any = None+ runtime: Any,+ task_id: str,+ tags: tuple[str, ...],+ prompt: str,+ cancel_token: Any = None,) -> str | None:agent = await guard_owned_routine(runtime, tags)if agent is None:@@ -31,16 +36,33 @@ async def run_owned_routine(service = runtime.chat_service()if service is None:raise RuntimeError("The canonical chat service is unavailable")- session = ensure_session(service, runtime.config(), agent)- if service.is_running(session.session_id):- from jarvis.core.protocols import RoutineDeferred+ from jarvis.agent_chat.effort import default_effort- raise RoutineDeferred("The routine owner is busy; waiting for the current turn")+ cfg = runtime.config()+ provider, model, effort = pair_for(cfg, agent)+ session = service.store.create_session(+ session_id=f"{agent.session_id}:routine:{task_id}:{uuid4().hex}",+ surface=SURFACE,+ provider=provider,+ model=model,+ effort=effort or default_effort(provider),+ account_id=agent.account_id,+ cwd=_workspace(cfg, agent),+ permission_mode="bypass",+ title=f"{agent.name} · Routine {task_id}",+ )+ # Persist the link before starting work, including runs that fail or are cancelled.+ task_store, _ = runtime.task_services()+ if task_store is not None:+ await task_store.append_step(+ task_id, "log", {"event": "routine_chat", "session_id": session.session_id}+ )# Legacy tasks contain an identity snapshot. The live briefing owns identity now._, separator, original = prompt.partition("\nRoutine:\n")task = original if separator else prompttask = (- f"Scheduled routine {task_id}. Follow your CURRENT standing instructions and permissions.\n"+ f"Scheduled routine {task_id}. Follow your CURRENT standing instructions.\n"+ "This execution has its own background chat with bypass permissions.\n""Use your memory and conversation archive for prior results. For information watches, ""check sources and dates, remember last-seen items, ""and report only meaningful new findings.\n\n" + task@@ -51,7 +73,6 @@ async def run_owned_routine(turn_id = await service.send(session.session_id, task, direct_user=False)while True:if cancel_token is not None and cancel_token.is_cancelled():- await service.cancel(session.session_id)raise asyncio.CancelledErrortry:event = await asyncio.wait_for(queue.get(), timeout=0.25)@@ -64,11 +85,16 @@ async def run_owned_routine(if event.get("kind") == "assistant_text":answer = str(payload.get("text") or answer)if event.get("kind") == "turn_finished":+ if payload.get("status") == "cancelled":+ raise asyncio.CancelledErrorif payload.get("status") not in {"done", "ok", "completed"}:raise RuntimeError(str(payload.get("error") or "The routine failed"))return answerexcept asyncio.CancelledError:await service.cancel(session.session_id)raise+ except Exception as exc:+ # A started execution must not silently move to another agent/context.+ raise RuntimeError(f"The routine chat failed: {exc}") from excfinally:service.unsubscribe(session.session_id, queue)diff --git a/jarvis/society/surface.py b/jarvis/society/surface.pyindex 0f483abfb9..240dd17321 100644--- a/jarvis/society/surface.py+++ b/jarvis/society/surface.py@@ -168,10 +168,10 @@ your location, use these names."""def agent_id_of(session_id: str) -> str | None:- """``society:<agent_id>`` → ``agent_id``; ``None`` for any other session."""+ """Resolve canonical and per-execution routine chats to their live owner."""if not session_id.startswith(_PREFIX):return None- agent_id = session_id[len(_PREFIX) :].strip()+ agent_id = session_id[len(_PREFIX) :].split(":routine:", 1)[0].strip()return agent_id or None@@ -274,7 +274,7 @@ async def tools_for_cli_session(or session.surface != SURFACEor agent is Noneor str(agent.state) != "active"- or agent.session_id != session_id+ or agent_id_of(session_id) != agent.agent_id):return {}rt.cache_agent(agent)@@ -303,7 +303,9 @@ def society_tools(cfg: Any, brain: Any, session: Any) -> dict[str, Tool]:# kit's tools REPLACE the folder tools (runner_brain.build_override), so the# agent would otherwise have no file hands at all; and the plain folder tools# accept absolute paths, which its workspace rule forbids.- tools[CodingSessionTool.name] = cast(Tool, CodingSessionTool(rt, agent_id))+ tools[CodingSessionTool.name] = cast(+ Tool, CodingSessionTool(rt, agent_id, session_id=str(getattr(session, "session_id", "")))+ )tools.update(_contained_folder_tools(workspace, getattr(session, "permission_mode", "")))tools.update({diff --git a/jarvis/tasks/runner.py b/jarvis/tasks/runner.pyindex 3d5992e689..1a3d2bb5d6 100644--- a/jarvis/tasks/runner.py+++ b/jarvis/tasks/runner.py@@ -774,6 +774,7 @@ def _owner_blocks_fallback(exc: BaseException) -> bool:"the routine owner is unavailable","the routine owner is paused","canonical chat service is unavailable",+ "the routine chat failed",))diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsx b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsxindex 015e927e3d..6bb951d138 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsx+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.test.tsx@@ -42,6 +42,21 @@ describe("tool visual identities", () => {expect(identity.logo).toBeTruthy();});+ it("uses original artwork for every raster and hyphenated catalog brand", () => {+ const cloud = toolIdentity(row({ id: "plugin:google_cloud", brand: "google_cloud", label: "Google Cloud" }));+ expect(cloud.logo).toBeTruthy();+ expect(cloud.mark).toBe("colour");+ const hyphen = toolIdentity(row({ id: "plugin:google-cloud", brand: "google-cloud", label: "Google Cloud" }));+ expect(hyphen.logo).toBeTruthy();+ const flare = toolIdentity(row({ id: "plugin:cloudflare", brand: "cloudflare", label: "Cloudflare" }));+ expect(flare.logo).toBeTruthy();+ expect(flare.mark).toBe("colour");+ const gitlab = toolIdentity(row({ id: "plugin:gitlab", brand: "gitlab", label: "GitLab" }));+ expect(gitlab.mark).toBe("colour");+ const figma = toolIdentity(row({ id: "plugin:figma", brand: "figma", label: "Figma" }));+ expect(figma.mark).toBe("colour");+ });+it("uses the bundled PNG for AgentMail and the AMD arrow for GPU status", () => {const mail = toolIdentity(row({ id: "plugin:agentmail", brand: "agentmail", label: "AgentMail" }));expect(mail.key).toBe("agentmail");diff --git a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.ts b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.tsindex 25e20d8a41..a06d0a51f3 100644--- a/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.ts+++ b/jarvis/ui/web/frontend/src/components/agentchat/toolIdentity.ts@@ -28,7 +28,7 @@ import {} from "lucide-react";import { McpLogo } from "@/components/extensions/McpLogo";import { CLI_VENDOR_LOGOS, cliVendor } from "@/lib/cliVendors";-import { bundledPluginLogo } from "@/lib/pluginLogos";+import { brandIdVariants, bundledPluginLogo, isRasterLogo } from "@/lib/pluginLogos";import type { ToolCategory, ToolChoice } from "./toolChoices";type Palette = readonly [string, string];@@ -70,10 +70,10 @@ const BRANDS: Record<string, Brand> = {todoist: { palette: ["#b12d27", "#ff9c92"] },vercel: { palette: NEUTRAL, mark: "mono" },youtube_music: { palette: ["#bb2424", "#ff9494"], aliases: ["youtube-music", "ytmusic", "youtube"] },- stripe: { palette: VIOLET, mark: "mono" },- cloudflare: { palette: ["#a84c14", "#ffb276"], mark: "mono", aliases: ["wrangler"] },- figma: { palette: ["#9c3a28", "#ffa18e"], mark: "mono" },- gitlab: { palette: ["#a8441a", "#ffad83"], mark: "mono", aliases: ["glab"] },+ stripe: { palette: VIOLET },+ cloudflare: { palette: ["#a84c14", "#ffb276"], aliases: ["wrangler"] },+ figma: { palette: ["#9c3a28", "#ffa18e"] },+ gitlab: { palette: ["#a8441a", "#ffad83"], aliases: ["glab"] },docker: { palette: BLUE, mark: "colour" },aws: { palette: ["#a15b00", "#f0b429"], mark: "mono" },azure: { palette: BLUE, aliases: ["az"] },@@ -94,7 +94,7 @@ const BRANDS: Record<string, Brand> = {openrouter: { palette: NEUTRAL, mark: "mono" },claude: { palette: ["#a04f31", "#e6aa89"], aliases: ["anthropic", "claude-code"] },gemini: { palette: BLUE },- "google-cloud": { palette: BLUE, aliases: ["gcloud", "vertex"] },+ "google-cloud": { palette: BLUE, aliases: ["gcloud", "vertex", "google_cloud"] },antigravity: { palette: BLUE, aliases: ["agy"] },ollama: { palette: NEUTRAL, mark: "mono" },nvidia: { palette: GREEN },@@ -124,19 +124,22 @@ const assets = import.meta.glob("../../assets/{brands,providers,tool-brands,clis}) as Record<string, string>;function assetFor(key: string, preferCli = false): string | undefined {- const cliFile = CLI_VENDOR_LOGOS[key]?.file ?? `${key}.svg`;- const cli = assets[`../../assets/clis/${cliFile}`] || assets[`../../assets/clis/${key}.svg`];- if (preferCli && cli) return cli;- return (- BRANDS[key]?.asset ||- bundledPluginLogo(key) ||- assets[`../../assets/brands/${key}.svg`] ||- assets[`../../assets/brands/${key}.png`] ||- assets[`../../assets/tool-brands/${key}.svg`] ||- assets[`../../assets/providers/${key}.svg`] ||- assets[`../../assets/providers/${key}.png`] ||- cli- );+ for (const id of brandIdVariants(key)) {+ const cliFile = CLI_VENDOR_LOGOS[id]?.file ?? `${id}.svg`;+ const cli = assets[`../../assets/clis/${cliFile}`] || assets[`../../assets/clis/${id}.svg`];+ if (preferCli && cli) return cli;+ const found =+ BRANDS[id]?.asset ||+ bundledPluginLogo(id) ||+ assets[`../../assets/brands/${id}.svg`] ||+ assets[`../../assets/brands/${id}.png`] ||+ assets[`../../assets/tool-brands/${id}.svg`] ||+ assets[`../../assets/providers/${id}.svg`] ||+ assets[`../../assets/providers/${id}.png`] ||+ cli;+ if (found) return found;+ }+ return undefined;}const normalize = (value: string) => value.toLowerCase().replace(/[^a-z0-9]/g, "");@@ -220,7 +223,7 @@ export function toolIdentity(row: ToolChoice) {(row.brand && brandFor(row.brand)) ||[row.id, row.group, row.skill, row.label].map((s) => brandFor(s || "")).find(Boolean) ||cliName;- const brand = key ? BRANDS[key] : undefined;+ const brand = key ? BRANDS[key] ?? BRANDS[key.replace(/-/g, "_")] ?? BRANDS[key.replace(/_/g, "-")] : undefined;const palette = brand?.palette ?? CATEGORY_PALETTES[row.category];const words = `${row.id} ${row.skill} ${row.label}`.toLowerCase().replace(/[_:-]/g, " ");const Glyph =@@ -228,10 +231,16 @@ export function toolIdentity(row: ToolChoice) {? McpLogo: (DETAIL_ICONS.find(([pattern]) => pattern.test(words))?.[1] ??CATEGORY_ICONS[row.category]);- const mark = preferCli && key && CLI_VENDOR_LOGOS[key] ? CLI_VENDOR_LOGOS[key].render : (brand?.mark ?? "colour");+ const logo = key ? assetFor(key, preferCli) : undefined;+ const mark =+ isRasterLogo(logo)+ ? "colour"+ : preferCli && key && CLI_VENDOR_LOGOS[key]+ ? CLI_VENDOR_LOGOS[key].render+ : (brand?.mark ?? "colour");return {key,- logo: key ? assetFor(key, preferCli) : undefined,+ logo,mark,palette,Glyph,diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsxindex 9bcd3975d5..ec219077dd 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.test.tsx@@ -5,20 +5,25 @@ import { AgentRoutineDetail, routineRuns } from "./AgentRoutineDetail";import type { LiveRoutine } from "../cardData";import type { TaskDetail, TaskStep } from "@/views/automations/automationsModel";import en from "@/i18n/locales/society/en.json";+import { RoutineChatHost } from "../chat/RoutineChatHost";+import { useRoutineNavigation } from "../chat/routineNavigation";++// Transcript rendering is covered separately; this suite exercises lazy lifecycle.+vi.mock("@/components/agentchat/AgentTimeline", () => ({ AgentTimeline: () => null }));vi.mock("@/i18n", () => ({useLocaleChunk: () => {},useT: () => (key: string) => key.split(".").reduce<unknown>((value, part) => (value as Record<string, unknown>)?.[part], en) ?? key,}));-afterEach(() => { cleanup(); vi.unstubAllGlobals(); });+afterEach(() => { cleanup(); useRoutineNavigation.getState().close(); vi.unstubAllGlobals(); });-function setup(multiple = false) {+function setup(multiple = false, steps: TaskStep[] = [], host = false) {const trigger = { type: "calendar", local_time: "08:00", timezone: "Europe/Berlin", weekdays: [0, 2] };const member: LiveRoutine = { id: "r1", title: "[agent:Mail] Inbox", prompt: "Read mail.", trigger, schedule: "", state: "scheduled", dueMs: null, lastRunMs: null };const members = multiple ? [member, { ...member, id: "r2" }] : [member];const tasks = new Map(members.map((m) => [m.id, {- ...m, trigger_type: "calendar", spec: { action: { kind: "agent", prompt: "Identity\nRoutine:\nRead mail." } }, steps: [],+ ...m, trigger_type: "calendar", spec: { action: { kind: "agent", prompt: "Identity\nRoutine:\nRead mail." } }, steps,} as unknown as TaskDetail]));const fetcher = vi.fn(async (url: string, init?: RequestInit) => {const method = init?.method ?? "GET";@@ -29,6 +34,7 @@ function setup(multiple = false) {vi.stubGlobal("fetch", fetcher);const onClose = vi.fn();render(<QueryClientProvider client={new QueryClient({ defaultOptions: { queries: { retry: false } } })}>+ {host && <RoutineChatHost agentId="mail" onOpen={() => {}}><p data-testid="main-agent-chat">Main conversation</p></RoutineChatHost>}<AgentRoutineDetail routine={{ ...member, members }} agentId="mail" onClose={onClose} /></QueryClientProvider>);return { fetcher, onClose };@@ -46,6 +52,45 @@ test("loads the instruction and saves all timings under the original ids", asyncexpect(JSON.parse(String(writes[0][1]?.body))).toMatchObject({ title: "Updated inbox", prompt: "Read mail.", schedule: { weekdays: [0, 2] } });});+test("opens only the selected execution socket and releases it on return", async () => {+ const sockets: { url: string; close: ReturnType<typeof vi.fn> }[] = [];+ class Socket {+ close = vi.fn();+ constructor(public url: string) { sockets.push(this); }+ }+ vi.stubGlobal("WebSocket", Socket);+ const sid = "society:mail:routine:r1:proof";+ const events = [{ event: "run_started" }, { event: "routine_chat", session_id: sid }, { event: "run_completed" }];+ const { fetcher } = setup(false, events.map((payload, seq) => ({ seq, kind: "log", timestamp_ns: (seq + 1) * 1e9, payload })), true);+ await screen.findByText("Open latest chat");+ expect(sockets).toHaveLength(0);+ expect(fetcher.mock.calls.some(([url]) => url.includes("agent-chat"))).toBe(false);+ fireEvent.click(screen.getByTestId("routine-run-r1:0"));+ // Cold module transformation includes the real dialog and socket store.+ await screen.findByTestId("routine-chat", {}, { timeout: 10000 });+ expect(screen.queryByRole("dialog")).toBeNull();+ expect(screen.queryByTestId("main-agent-chat")).toBeNull();+ expect(screen.getByTestId("agent-routine-detail")).toBeTruthy();+ expect(sockets).toHaveLength(1);+ expect(decodeURIComponent(sockets[0].url)).toContain(sid);+ fireEvent.click(screen.getByRole("button", { name: "Back to agent chat" }));+ await screen.findByTestId("main-agent-chat");+ expect(sockets[0].close).toHaveBeenCalledOnce();+ expect(fetcher.mock.calls.some(([url]) => url.endsWith("/cancel"))).toBe(false);+}, 15000);++test("latest means the newest execution even when only an older run has a separate chat", async () => {+ const events = [{ event: "run_started" }, { event: "routine_chat", session_id: "society:mail:routine:r1:older" }, { event: "run_completed" }, { event: "run_started" }, { event: "error" }];+ const { fetcher } = setup(false, events.map((payload, seq) => ({ seq, kind: "log", timestamp_ns: (seq + 1) * 1e12, payload })));+ await screen.findByText("Open latest chat");+ expect(useRoutineNavigation.getState().target).toBeNull();+ fireEvent.click(screen.getByText("Open latest chat"));+ expect(useRoutineNavigation.getState().target).toMatchObject({ sessionId: "society:mail", timestamp: 4000000, legacy: { taskId: "r1", startedMs: 4000000, finishedMs: 5000000 } });+ expect(fetcher.mock.calls.some(([url]) => url.includes("agent-chat"))).toBe(false);+ fireEvent.click(screen.getByTestId("routine-run-r1:0"));+ expect(useRoutineNavigation.getState().target?.sessionId).toBe("society:mail:routine:r1:older");+});+test("pauses every timing, tests once, and requires a delete confirmation", async () => {const { fetcher, onClose } = setup(true);await waitFor(() => expect((screen.getByRole("switch") as HTMLButtonElement).disabled).toBe(false));diff --git a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsxindex 158854ea80..dceb4fccc3 100644--- a/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx+++ b/jarvis/ui/web/frontend/src/components/society/card/AgentRoutineDetail.tsx@@ -10,6 +10,7 @@ import type { TaskDetail, TaskStep } from "@/views/automations/automationsModel"import { TriggerBuilder } from "./TriggerBuilder";import { WebhookConnection } from "./WebhookConnection";import { SourceControls } from "./SourceControls";+import { useRoutineNavigation } from "../chat/routineNavigation";const field = "w-full rounded-lg border border-border bg-background px-3 py-2 text-[12px] text-foreground";const button = "rounded-md bg-secondary px-2.5 py-1.5 text-[12px] text-foreground hover:bg-secondary/70 disabled:opacity-50";@@ -17,7 +18,7 @@ const recurring = ["every", "calendar", "cron", "webhook", "event_hook", "sourceconst terminal = ["completed", "failed", "cancelled", "interrupted"];const timeKinds = ["every", "calendar", "cron"];-interface Run { id: string; timestamp: number; status: string; text: string }+interface Run { id: string; taskId: string; timestamp: number; status: string; text: string; sessionId?: string; startedMs?: number; finishedMs?: number }/** New runs have explicit boundaries; retain older result/error records too. */export function routineRuns(taskId: string, steps: TaskStep[]): Run[] {@@ -28,17 +29,19 @@ export function routineRuns(taskId: string, steps: TaskStep[]): Run[] {const text = String(step.payload.message ?? step.payload.text ?? "");if (event === "run_started") {if (current?.status === "running") current.status = "interrupted";- current = { id: `${taskId}:${step.seq}`, timestamp: step.timestamp_ns / 1e6, status: "running", text: "" };+ current = { id: `${taskId}:${step.seq}`, taskId, timestamp: step.timestamp_ns / 1e6, startedMs: step.timestamp_ns / 1e6, status: "running", text: "" };runs.push(current);+ } else if (event === "routine_chat" && current && typeof step.payload.session_id === "string") {+ current.sessionId = step.payload.session_id;} else if (event === "agent_result" && current) {current.text = text;} else if (["run_completed", "run_cancelled", "error", "deferred"].includes(String(event))) {const status = event === "run_completed" ? "completed" : event === "run_cancelled" ? "cancelled" : event === "deferred" ? "pending" : "failed";- if (current) { current.status = status; if (text) current.text = text; current = undefined; }- else runs.push({ id: `${taskId}:${step.seq}`, timestamp: step.timestamp_ns / 1e6, status, text });+ if (current) { current.status = status; current.finishedMs = step.timestamp_ns / 1e6; if (text) current.text = text; current = undefined; }+ else runs.push({ id: `${taskId}:${step.seq}`, taskId, timestamp: step.timestamp_ns / 1e6, finishedMs: step.timestamp_ns / 1e6, status, text });} else if (event === "agent_result") {// Legacy runners persisted the result before the final state transition.- runs.push({ id: `${taskId}:${step.seq}`, timestamp: step.timestamp_ns / 1e6, status: "legacy", text });+ runs.push({ id: `${taskId}:${step.seq}`, taskId, timestamp: step.timestamp_ns / 1e6, finishedMs: step.timestamp_ns / 1e6, status: "legacy", text });}}return runs;@@ -70,6 +73,7 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {const [error, setError] = useState("");const [notice, setNotice] = useState("");const [confirmDelete, setConfirmDelete] = useState(false);+ const openChat = useRoutineNavigation((state) => state.open);const details = queries.map((query) => query.data);const first = details[0];const rawPrompt = String((first?.spec?.action as { prompt?: string } | undefined)?.prompt ?? "");@@ -104,6 +108,14 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {return null;};+ const openRun = (run: Run) => {+ const ownChat = run.sessionId?.startsWith(`society:${agentId}:routine:${run.taskId}:`);+ openChat({ agentId, sessionId: ownChat ? run.sessionId! : `society:${agentId}`,+ title: saved.title, timestamp: run.timestamp, result: run.text,+ ...(!ownChat ? { legacy: { taskId: run.taskId, startedMs: run.startedMs, finishedMs: run.finishedMs } } : {}),+ });+ };+return <section className="min-h-0 flex-1 space-y-4 overflow-y-auto pb-4 text-foreground" data-testid="agent-routine-detail"><button type="button" className="flex items-center gap-1 text-[12px] text-muted-foreground" disabled={pending} onClick={onClose}><ArrowLeft size={14} />{t("society.card.routines")}</button><div className="flex flex-wrap items-center gap-2">@@ -160,13 +172,11 @@ export function AgentRoutineDetail({ agentId, routine, onClose }: {</div><div className="space-y-2"><h4 className="text-[11px] text-muted-foreground">{label("history")}</h4>+ {runs.length > 0 && <button type="button" className={button} onClick={() => openRun(runs[0])}>{label("latest_chat")}</button>}{ready && runs.length === 0 && <p className="text-[12px] text-muted-foreground">{label("no_runs")}</p>}- {runs.map((run) => <details key={run.id} className="text-[12px]">- <summary className="flex cursor-pointer items-center justify-between gap-2 rounded py-1 hover:bg-secondary"><time dateTime={new Date(run.timestamp).toISOString()}>{new Date(run.timestamp).toLocaleString()}</time><span className="flex items-center gap-1" title={run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`)}>+ {runs.map((run) => <button key={run.id} type="button" data-testid={`routine-run-${run.id}`} aria-label={`${label("open_chat")} · ${new Date(run.timestamp).toLocaleString()}`} onClick={() => openRun(run)} className="flex w-full cursor-pointer items-center justify-between gap-2 rounded py-1 text-left text-[12px] hover:bg-secondary focus-visible:outline focus-visible:outline-ring"><time dateTime={new Date(run.timestamp).toISOString()}>{new Date(run.timestamp).toLocaleString()}</time><span className="flex items-center gap-1" title={run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`)}>{run.status === "completed" ? <Check size={15} className="text-success" aria-label={t("tasks_view.state.completed")} /> : run.status === "failed" || run.status === "cancelled" ? <X size={15} className="text-destructive" aria-label={t(`tasks_view.state.${run.status}`)} /> : <Clock size={15} aria-label={run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`)} />}- </span></summary>- <p className="whitespace-pre-wrap break-words rounded bg-secondary p-2">{run.text || (run.status === "legacy" ? label("legacy") : t(`tasks_view.state.${run.status}`))}</p>- </details>)}+ </span></button>)}</div></section>;}diff --git a/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.test.tsx b/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.test.tsxnew file mode 100644index 0000000000..4bb90fc1a3--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.test.tsx@@ -0,0 +1,55 @@+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, expect, test, vi } from "vitest";+import type { TimelineItem } from "@/components/agentchat/reduce";+import RoutineChat from "./RoutineChat";+import type { RoutineChatTarget } from "../chat/routineExecution";++vi.mock("@/i18n", () => ({ useT: () => (key: string) => key }));+vi.mock("@/components/agentchat/ChatMarkdown", () => ({ ChatMarkdown: ({ text }: { text: string }) => <p>{text}</p> }));+vi.mock("@/components/agentchat/AgentTimeline", () => ({ AgentTimeline: ({ items }: { items: TimelineItem[] }) => <pre data-testid="selected-transcript">{JSON.stringify(items)}</pre> }));++afterEach(() => { cleanup(); vi.unstubAllGlobals(); });++const instruction = "Scheduled routine daily. Follow your CURRENT standing instructions and permissions.\nUse your memory and conversation archive for prior results. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings.\n\nRead mail.";+const events = [+ { seq: 1, ts_ms: 10000, kind: "user_message", payload: { text: instruction } },+ { seq: 2, ts_ms: 10001, kind: "turn_started", payload: { turn_id: "first" } },+ { seq: 3, ts_ms: 10500, kind: "assistant_text", payload: { turn_id: "first", text: "FIRST ONLY" } },+ { seq: 4, ts_ms: 11000, kind: "turn_finished", payload: { turn_id: "first", status: "done" } },+ { seq: 5, ts_ms: 20000, kind: "user_message", payload: { text: "PRIVATE MAIN CHAT" } },+];+const target: RoutineChatTarget = { agentId: "mail", sessionId: "society:mail", title: "Inbox", timestamp: 10000,+ legacy: { taskId: "daily", startedMs: 9900, finishedMs: 11100 }, result: "Saved result" };++test("an old execution loads its own turn without opening a writable main chat", async () => {+ const fetcher = vi.fn(async () => new Response(JSON.stringify({ session: { title: "Mail" }, events })));+ const socket = vi.fn();+ vi.stubGlobal("fetch", fetcher);+ vi.stubGlobal("WebSocket", socket);+ render(<RoutineChat target={target} onClose={() => {}} />);+ const transcript = await screen.findByTestId("selected-transcript");+ expect(transcript.textContent).toContain("FIRST ONLY");+ expect(transcript.textContent).not.toContain("PRIVATE MAIN CHAT");+ expect(transcript.textContent).not.toContain("Follow your CURRENT");+ expect(socket).not.toHaveBeenCalled();+ expect(screen.queryByRole("textbox")).toBeNull();+ expect(fetcher).toHaveBeenCalledOnce();+ expect(fetcher.mock.calls[0]).toEqual(["/api/agent-chat/sessions/society%3Amail"]);+ // An old task could succeed through a fallback after its chat attempt failed.+ expect(screen.getByTestId("routine-saved-result").textContent).toContain("Saved result");+});++test("does not duplicate a saved result already present in the selected conversation", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ session: { title: "Mail" }, events }))));+ render(<RoutineChat target={{ ...target, result: "FIRST ONLY" }} onClose={() => {}} />);+ await screen.findByTestId("selected-transcript");+ expect(screen.queryByTestId("routine-saved-result")).toBeNull();+});++test("a missing historical turn shows only that execution's saved result", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response(JSON.stringify({ session: { title: "Mail" }, events }))));+ render(<RoutineChat target={{ ...target, legacy: { taskId: "daily", startedMs: 90000, finishedMs: 91000 } }} onClose={() => {}} />);+ await screen.findByText("Saved result");+ expect(screen.queryByTestId("selected-transcript")).toBeNull();+ expect(screen.queryByRole("textbox")).toBeNull();+});diff --git a/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.tsx b/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.tsxnew file mode 100644index 0000000000..55d131aada--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/card/RoutineChat.tsx@@ -0,0 +1,99 @@+/** The selected execution occupies the agent's chat lane and loads only on navigation. */+import { useEffect, useMemo, useState } from "react";+import { ArrowLeft, Send, Square } from "lucide-react";+import { AgentTimeline } from "@/components/agentchat/AgentTimeline";+import { ChatMarkdown } from "@/components/agentchat/ChatMarkdown";+import { EMPTY_TIMELINE, reduceEvents, runningTurn, type TimelineItem } from "@/components/agentchat/reduce";+import { AgentChatStoreProvider } from "@/components/agentchat/AgentChatStoreContext";+import { fetchAgentChatSession } from "@/lib/agentChatApi";+import { createAgentChatStore } from "@/store/agentChat";+import { useStickToBottom } from "@/hooks/useStickToBottom";+import { useT } from "@/i18n";+import { legacyRoutineEvents, routineTask, type RoutineChatTarget } from "../chat/routineExecution";++function displayItems(items: TimelineItem[]): TimelineItem[] {+ return items.map((item) => item.type === "user" ? { ...item, text: routineTask(item.text) ?? item.text } : item);+}++export default function RoutineChat({ target, onClose }: { target: RoutineChatTarget; onClose: () => void }) {+ const t = useT();+ return <section className="flex h-full min-h-0 flex-1 flex-col bg-background p-4 text-foreground sm:p-6" data-testid="routine-chat" data-session-id={target.sessionId}>+ <header className="flex shrink-0 flex-wrap items-center gap-x-4 gap-y-2 border-b border-border pb-3">+ <button type="button" className="flex items-center gap-1 text-[12px] text-muted-foreground hover:text-foreground" onClick={onClose}><ArrowLeft size={14} />{t("society.routine_detail.back_to_agent")}</button>+ <div className="min-w-0 flex-1"><h3 className="truncate text-sm font-medium">{target.title}</h3>+ <time className="text-[11px] text-muted-foreground" dateTime={new Date(target.timestamp).toISOString()}>{new Date(target.timestamp).toLocaleString()}</time>+ </div>+ <span className="text-[11px] text-muted-foreground">{t("society.routine_detail.background_chat")}</span>+ </header>+ {target.legacy ? <HistoricalExecution target={target} /> : <LiveExecution sessionId={target.sessionId} />}+ </section>;+}++function HistoricalExecution({ target }: { target: RoutineChatTarget }) {+ const t = useT();+ const [snapshot, setSnapshot] = useState<{ name: string; items: TimelineItem[]; resultInChat: boolean } | null>(null);+ const [error, setError] = useState("");+ useEffect(() => {+ let alive = true;+ void fetchAgentChatSession(target.sessionId).then(({ session, events }) => {+ if (!alive) return;+ const selected = legacyRoutineEvents(events, target);+ const items = displayItems(reduceEvents(EMPTY_TIMELINE, selected).items).map((item) => item.type === "turn"+ ? { ...item, blocks: item.blocks.map((block) => block.kind === "tool" ? { ...block, approval: null } : block) } : item);+ const replies = items.flatMap((item) => item.type === "turn" ? item.blocks.flatMap((block) => block.kind === "text" ? [block.text] : []) : []).join("\n");+ setSnapshot({ name: session.title, items, resultInChat: Boolean(target.result?.trim() && replies.includes(target.result.trim())) });+ }).catch((err) => { if (alive) setError(err instanceof Error ? err.message : String(err)); });+ return () => { alive = false; };+ }, [target]);+ return <>+ <div className="min-h-0 flex-1 space-y-4 overflow-y-auto py-4" data-testid="routine-historical-transcript">+ {!snapshot && !error && <p role="status">{t("tasks_view.loading_details")}</p>}+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}+ {snapshot?.items.length ? <AgentTimeline items={snapshot.items} assistantName={snapshot.name} providerLabel={(id) => id} onDecide={async () => { /* Historical approvals are hidden; this transcript cannot act. */ }} /> : null}+ {(snapshot?.items.length === 0 || error) && <>+ <p className="text-sm text-muted-foreground">{t("society.routine_detail.trace_unavailable")}</p>+ </>}+ {(snapshot || error) && target.result && !snapshot?.resultInChat && <section className="space-y-2 border-t border-border pt-3" data-testid="routine-saved-result">+ <h4 className="text-xs font-medium text-muted-foreground">{t("society.routine_detail.saved_result")}</h4>+ <ChatMarkdown text={target.result} />+ </section>}+ </div>+ <p className="shrink-0 border-t border-border pt-3 text-xs text-muted-foreground">{t("society.routine_detail.historical_chat")}</p>+ </>;+}++function LiveExecution({ sessionId }: { sessionId: string }) {+ const t = useT();+ const label = (key: string) => t(`society.routine_detail.${key}`);+ const [store] = useState(() => createAgentChatStore("society", "routine"));+ const timeline = store((state) => state.timeline);+ const visibleItems = useMemo(() => displayItems(timeline.items), [timeline.items]);+ const session = store((state) => state.activeSession);+ const busy = store((state) => state.busy);+ const socketState = store((state) => state.socketState);+ const error = store((state) => state.lastError);+ const [message, setMessage] = useState("");+ const running = Boolean(runningTurn(timeline)) || busy;+ const ready = session?.session_id === sessionId && socketState === "open";+ const scroll = useStickToBottom();+ useEffect(() => {+ store.getState().openSession(sessionId);+ return () => store.getState().disconnect();+ }, [sessionId, store]);+ return <AgentChatStoreProvider store={store}>+ <div ref={scroll.rootRef} className="min-h-0 flex-1 overflow-y-auto py-4"><div ref={scroll.contentRef} className="space-y-3">+ {!ready && !error && <p role="status" className="text-sm">{t("tasks_view.loading_details")}</p>}+ <AgentTimeline items={visibleItems} assistantName={session?.title.split(" · ")[0] ?? ""} providerLabel={(id) => id} onDecide={store.getState().decide} />+ </div></div>+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}+ <form className="mt-3 flex shrink-0 items-end gap-2" onSubmit={(event) => {+ event.preventDefault();+ if (!message.trim() || !ready || running) return;+ void store.getState().send(message).then(() => { if (!store.getState().lastError) setMessage(""); });+ }}>+ <textarea className="min-w-0 flex-1 rounded-lg border border-border bg-background p-2 text-sm" rows={2} aria-label={label("follow_up")} placeholder={label("follow_up")} value={message} onChange={(event) => setMessage(event.target.value)} />+ {running ? <button type="button" className="rounded p-2 hover:bg-secondary" aria-label={label("stop_run")} onClick={() => void store.getState().cancel()}><Square size={16} /></button>+ : <button type="submit" className="rounded p-2 hover:bg-secondary disabled:opacity-50" disabled={!ready || !message.trim()} aria-label={label("send")}><Send size={16} /></button>}+ </form>+ </AgentChatStoreProvider>;+}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsxindex 2fe1d27846..43db3db09d 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.switch.test.tsx@@ -6,6 +6,7 @@ import { EMPTY_TIMELINE, reduceEvents, type Timeline, type UserItem } from "@/coimport type { SocietyAgent } from "../data";import {AgentChatPanel,+ UserBubble,itemsForOpenSession,useSocietyChatStore,setJarvisCardMode,@@ -15,6 +16,7 @@ import { useEventStore } from "@/store/events";import type { AgentChatEvent, AgentChatSession } from "@/lib/agentChatApi";import { useHomeStore } from "@/store/home";import { JarvisHistoryRail } from "./JarvisHistoryRail";+import { useRoutineNavigation } from "./routineNavigation";vi.mock("@/i18n", () => ({ useT: () => (key: string) => key, fill: (text: string) => text }));vi.mock("./AgentModelPicker", () => ({ AgentModelPicker: () => null }));@@ -106,6 +108,7 @@ const visual = agent({ agentId: "visual-qa", name: "Visual QA" });const gmail = agent({ agentId: "gmail-agent", name: "Gmail Agent" });beforeEach(() => {+ useRoutineNavigation.getState().close();seq = 0;useTranscriptViewStore.setState({ boundaries: {} });useHomeStore.setState({ transcript: [], liveReply: "", jarvisCardMode: "voice", freshVoicePending: false });@@ -272,6 +275,17 @@ it.each(["specialist", "lead"] as const)("turns send into stop while the %s is rexpect(screen.queryByTestId("composer-stop")).toBeNull();});+it("routine-check opens the clicked execution instead of folding its instruction", () => {+ const text = "Scheduled routine daily. Follow your CURRENT standing instructions and permissions.\nUse your memory and conversation archive for prior results. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings.\n\nInspect this execution.";+ render(<UserBubble agentId={gmail.agentId} sessionId={gmail.chatSessionId!} item={{ type: "user", id: "u-88", tsMs: 10000, text, attachments: [] }} />);+ expect(useRoutineNavigation.getState().target).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: /routine_check/ }));+ expect(useRoutineNavigation.getState().target).toEqual({+ agentId: gmail.agentId, sessionId: gmail.chatSessionId, title: "Inspect this execution.", timestamp: 10000,+ legacy: { taskId: "daily", messageId: "u-88" },+ });+});+it("shows stop while the send request is in flight, before the turn stream starts", () => {useSocietyChatStore.getState().disconnect();useSocietyChatStore.getState().openSession(gmail.chatSessionId!);diff --git a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsxindex 52e4f10691..9f2ae95edf 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx@@ -22,6 +22,9 @@ import { mergeOutgoingMessages, useOutgoingMessages } from "@/components/agentch* runner can drive. The header says so while voice is showing.*/import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";+import { useRoutineNavigation } from "./routineNavigation";+import { routineTaskId } from "./routineExecution";+import { RoutineChatHost } from "./RoutineChatHost";import { MessageSquare, Mic, Paperclip, Plus, RotateCcw, Send, Square } from "lucide-react";import { ChatMarkdown, MediaPreview, mediaKind } from "@/components/agentchat/ChatMarkdown";@@ -136,7 +139,12 @@ export function itemsForOpenSession(}export function AgentChatPanel(props: AgentChatPanelProps) {- return <PairConversationBoundary key={props.agent.agentId} recipient={{ id: props.agent.agentId, name: props.agent.name }}><AgentChatPanelContent {...props} /></PairConversationBoundary>;+ const disconnect = useCallback(() => {+ (props.agent.tier === "lead" ? useAgentChatStore : useSocietyChatStore).getState().disconnect();+ }, [props.agent.tier]);+ return <PairConversationBoundary key={props.agent.agentId} recipient={{ id: props.agent.agentId, name: props.agent.name }}>+ <RoutineChatHost agentId={props.agent.agentId} onOpen={disconnect}><AgentChatPanelContent {...props} /></RoutineChatHost>+ </PairConversationBoundary>;}function AgentChatPanelContent({ agent, roster }: AgentChatPanelProps) {@@ -574,6 +582,7 @@ export function Transcript({onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;}) {const t = useT();+ const sessionId = useAgentChat((state) => state.activeSessionId);// Follow the newest while the view sits at the end — the rule every// conversation surface shares (hooks/useStickToBottom). This used to scroll// a bottom sentinel into view on `[items.length, busy]` only, so a@@ -613,7 +622,7 @@ export function Transcript({{item.type === "internal" ? (<AgentMessageActivity item={item} roster={roster} />) : item.type === "user" ? (- <UserBubble item={item} />+ <UserBubble item={item} agentId={agent.agentId} sessionId={sessionId ?? agent.chatSessionId ?? undefined} />) : item.type === "turn" ? (<TurnBubble item={item} onDecide={onDecide} />) : item.type === "notice" ? (@@ -841,13 +850,17 @@ function visibleUserText(text: string): string {.trimEnd();}-export function UserBubble({ item }: { item: UserItem }) {+export function UserBubble({ item, agentId, sessionId }: { item: UserItem; agentId?: string; sessionId?: string }) {const t = useT();const choices = messageChoices(item);const text = visibleUserText(item.text);if (item.origin === "control") return <div className="self-start px-1 py-2 text-xs text-muted-foreground">{t("slash.control_turn")}{item.attachments.map((file) => <span key={file.name} className="ml-2">{file.name}</span>)}</div>;const task = routineTask(item.text);- if (task !== null && item.attachments.length === 0) return <RoutineActivity task={task} original={item.text} />;+ if (task !== null && item.attachments.length === 0) return <RoutineActivity task={task} original={item.text}+ onOpen={agentId && sessionId ? () => useRoutineNavigation.getState().open({+ agentId, sessionId, title: task.split(/\r?\n/)[0], timestamp: item.tsMs,+ ...(!sessionId.includes(":routine:") ? { legacy: { taskId: routineTaskId(item.text)!, messageId: item.id } } : {}),+ }) : undefined} />;return (<div className="flex min-w-0 max-w-[min(85%,42rem)] flex-col items-end gap-1 self-end"><div className="min-w-0 rounded-2xl rounded-br-md bg-secondary px-4 py-2.5 text-sm leading-relaxed text-foreground [overflow-wrap:anywhere]">diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsxindex 20dfe0ebc8..e2f91f4cd6 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.test.tsx@@ -14,6 +14,8 @@ it("folds only a full scheduler envelope, preserving ordinary user messages", ()expect(routineTask(envelope + "Check the inbox.\nSummarize changes.")).toBe("Check the inbox.\nSummarize changes.");expect(routineTask("Scheduled routine task-123. Please explain this.")).toBeNull();expect(routineTask("Please quote:\n" + envelope)).toBeNull();+ const background = envelope.replace(" and permissions.\n", ".\nThis execution has its own background chat with bypass permissions.\n");+ expect(routineTask(background + "Check the inbox.")).toBe("Check the inbox.");render(<RoutineActivity task={"Check the inbox.\nSummarize changes."} original={envelope + "Check the inbox.\nSummarize changes."} />);expect(screen.queryByText("Summarize changes.")).toBeNull();fireEvent.click(screen.getByRole("button", { name: "Routine check · Check the inbox." }));diff --git a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsx b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsxindex 12d3232003..e1a0550861 100644--- a/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsx+++ b/jarvis/ui/web/frontend/src/components/society/chat/ChatActivity.tsx@@ -7,6 +7,7 @@ import { useT } from "@/i18n";import { cn } from "@/lib/utils";import { AgentSwatch } from "../AgentSwatch";import type { SocietyAgent } from "../data";+export { routineTask } from "./routineExecution";/** A quiet event in the conversation; details remain keyboard accessible. */export function ChatActivity({ label, icon, children, failed = false }: {@@ -24,15 +25,12 @@ export function ChatActivity({ label, icon, children, failed = false }: {</div>;}-/** Recognize only the scheduler's complete envelope; ordinary messages stay intact. */-export function routineTask(text: string): string | null {- const envelope = /^Scheduled routine [^\s.]+\. Follow your CURRENT standing instructions and permissions\.\r?\nUse your memory and conversation archive for prior results\. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings\.\r?\n\r?\n/;- const match = envelope.exec(text);- return match ? text.slice(match[0].length).trim() : null;-}--export function RoutineActivity({ task, original }: { task: string; original: string }) {+export function RoutineActivity({ task, original, onOpen }: { task: string; original: string; onOpen?: () => void }) {const t = useT();+ if (onOpen) return <button type="button" onClick={onOpen}+ className="mx-auto my-3 flex max-w-[min(100%,36rem)] items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">+ <Clock3 aria-hidden className="h-3.5 w-3.5 shrink-0" /><span className="truncate">{t("society.chat.routine_check")} · {task.split(/\r?\n/)[0]}</span><ChevronRight aria-hidden className="h-3 w-3 shrink-0" />+ </button>;return <ChatActivity label={<>{t("society.chat.routine_check")} · {task.split(/\r?\n/)[0]}</>} icon={<Clock3 aria-hidden className="h-3.5 w-3.5 shrink-0" />}><ChatMarkdown text={task} /><details className="mt-2 text-xs"><summary className="cursor-pointer">{t("society.chat.activity_details")}</summary><p className="mt-2 whitespace-pre-wrap">{original}</p></details>diff --git a/jarvis/ui/web/frontend/src/components/society/chat/RoutineChatHost.tsx b/jarvis/ui/web/frontend/src/components/society/chat/RoutineChatHost.tsxnew file mode 100644index 0000000000..8e60eb50d2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/RoutineChatHost.tsx@@ -0,0 +1,21 @@+import { lazy, Suspense, useEffect, type ReactNode } from "react";+import { useT } from "@/i18n";+import { useRoutineNavigation } from "./routineNavigation";++const RoutineChat = lazy(() => import("../card/RoutineChat"));++export function RoutineChatHost({ agentId, onOpen, children }: {+ agentId: string; onOpen: () => void; children: ReactNode;+}) {+ const t = useT();+ const target = useRoutineNavigation((state) => state.target);+ const close = useRoutineNavigation((state) => state.close);+ const selected = target?.agentId === agentId ? target : null;+ useEffect(() => { if (selected) onOpen(); }, [selected, onOpen]);+ useEffect(() => () => {+ if (useRoutineNavigation.getState().target?.agentId === agentId) close();+ }, [close, agentId]);+ return selected ? <Suspense fallback={<p role="status" className="p-4 text-sm">{t("tasks_view.loading_details")}</p>}>+ <RoutineChat key={`${selected.sessionId}:${selected.legacy?.messageId ?? selected.timestamp}`} target={selected} onClose={close} />+ </Suspense> : children;+}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.test.ts b/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.test.tsnew file mode 100644index 0000000000..73c1c28418--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.test.ts@@ -0,0 +1,46 @@+import { expect, test } from "vitest";+import type { AgentChatEvent } from "@/lib/agentChatApi";+import { legacyRoutineEvents, routineTask, routineTaskId, type RoutineChatTarget } from "./routineExecution";++export const instruction = (id: string) => `Scheduled routine ${id}. Follow your CURRENT standing instructions and permissions.\nUse your memory and conversation archive for prior results. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings.\n\nCheck this run.`;++function run(seq: number, start: number, id: string, answer: string): AgentChatEvent[] {+ const turn = `turn-${seq}`;+ return [+ { seq, ts_ms: start, kind: "user_message", payload: { text: instruction(id) } },+ { seq: seq + 1, ts_ms: start + 10, kind: "turn_started", payload: { turn_id: turn } },+ { seq: seq + 2, ts_ms: start + 20, kind: "tool_call", payload: { turn_id: turn, name: "read", call_id: turn } },+ { seq: seq + 3, ts_ms: start + 30, kind: "assistant_text", payload: { turn_id: turn, text: answer } },+ { seq: seq + 4, ts_ms: start + 1000, kind: "turn_finished", payload: { turn_id: turn, status: "done" } },+ ];+}++const target: RoutineChatTarget = { agentId: "mail", sessionId: "society:mail", title: "Inbox", timestamp: 10000,+ legacy: { taskId: "daily", startedMs: 9900, finishedMs: 11100 } };+const first = run(1, 10000, "daily", "FIRST RUN");+const second = run(10, 100000, "daily", "SECOND RUN");++test("history selects the matching execution, including tools, without other conversations", () => {+ expect(legacyRoutineEvents([...first, ...second], target)).toEqual(first);+});++test("routine-check navigation uses the exact message even for an identical later prompt", () => {+ expect(legacyRoutineEvents([...first, ...second], { ...target, legacy: { taskId: "daily", messageId: "u-10" } })).toEqual(second);+});++test("missing and ambiguous executions never fall back to a different run", () => {+ expect(legacyRoutineEvents(second, target)).toEqual([]);+ expect(legacyRoutineEvents([...first, ...run(20, 10500, "daily", "ambiguous")], target)).toEqual([]);+ expect(legacyRoutineEvents(first, { ...target, legacy: { taskId: "other", messageId: "u-1" } })).toEqual([]);+});++test("old result-only steps match their completion time, not the latest prompt", () => {+ expect(legacyRoutineEvents([...first, ...second], { ...target, legacy: { taskId: "daily", finishedMs: 11020 } })).toEqual(first);+});++test("ordinary messages and notices cannot become execution links", () => {+ expect(routineTaskId("Scheduled routine daily. Explain this text.")).toBeNull();+ expect(routineTask(instruction("daily"))).toBe("Check this run.");+ const notice: AgentChatEvent = { seq: 200, ts_ms: 10500, kind: "notice", payload: { text: "PRIVATE unrelated notice" } };+ expect(legacyRoutineEvents([...first.slice(0, 2), notice, ...first.slice(2), ...second], target)).toEqual(first);+});diff --git a/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.ts b/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.tsnew file mode 100644index 0000000000..6c65dd4fce--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/routineExecution.ts@@ -0,0 +1,59 @@+import type { AgentChatEvent } from "@/lib/agentChatApi";++export interface RoutineChatTarget {+ agentId: string;+ sessionId: string;+ title: string;+ timestamp: number;+ result?: string;+ legacy?: {+ taskId: string;+ messageId?: string;+ startedMs?: number;+ finishedMs?: number;+ };+}++/** Only a complete scheduler envelope is a routine, never a similar user message. */+const envelope = /^Scheduled routine ([^\s.]+)\. Follow your CURRENT standing instructions(?: and permissions)?\.\r?\n(?:This execution has its own background chat with bypass permissions\.\r?\n)?Use your memory and conversation archive for prior results\. For information watches, check sources and dates, remember last-seen items, and report only meaningful new findings\.\r?\n\r?\n/;++export function routineTask(text: string): string | null {+ const match = envelope.exec(text);+ return match ? text.slice(match[0].length).trim() : null;+}++export function routineTaskId(text: string): string | null {+ return envelope.exec(text)?.[1] ?? null;+}++/** Read the exact old turn; never substitute the latest turn or the whole main chat. */+export function legacyRoutineEvents(events: AgentChatEvent[], target: RoutineChatTarget): AgentChatEvent[] {+ const legacy = target.legacy;+ if (!legacy) return [];+ const matches: AgentChatEvent[][] = [];+ for (let index = 0; index < events.length; index += 1) {+ const message = events[index];+ if (message.kind !== "user_message" || routineTaskId(String(message.payload.text ?? "")) !== legacy.taskId) continue;+ if (legacy.messageId && legacy.messageId !== `u-${message.seq || message.ts_ms}`) continue;+ let next = index + 1;+ while (next < events.length && events[next].kind !== "user_message") next += 1;+ const span = events.slice(index + 1, next);+ const turn = span.find((event) => event.kind === "turn_started");+ if (!turn?.payload.turn_id) continue;+ const own = span.filter((event) => event.payload.turn_id === turn.payload.turn_id);+ if (!legacy.messageId) {+ // Task steps and chat messages share the local clock. A small allowance+ // covers timestamp rounding, not another daily run of the same prompt.+ if (legacy.startedMs !== undefined) {+ if (message.ts_ms < legacy.startedMs - 2000) continue;+ if (legacy.finishedMs === undefined || message.ts_ms > legacy.finishedMs + 2000) continue;+ } else {+ const finished = own.find((event) => event.kind === "turn_finished");+ if (!finished || legacy.finishedMs === undefined || Math.abs(finished.ts_ms - legacy.finishedMs) > 5000) continue;+ }+ }+ matches.push([message, ...own]);+ }+ // Ambiguous timestamps are not permission to show a different execution.+ return matches.length === 1 ? matches[0] : [];+}diff --git a/jarvis/ui/web/frontend/src/components/society/chat/routineNavigation.ts b/jarvis/ui/web/frontend/src/components/society/chat/routineNavigation.tsnew file mode 100644index 0000000000..2b4fd8424c--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/society/chat/routineNavigation.ts@@ -0,0 +1,13 @@+import { create } from "zustand";+import type { RoutineChatTarget } from "./routineExecution";++/** Navigation only: opening the selected chat is the host's lazy responsibility. */+export const useRoutineNavigation = create<{+ target: RoutineChatTarget | null;+ open: (target: RoutineChatTarget) => void;+ close: () => void;+}>((set) => ({+ target: null,+ open: (target) => set({ target }),+ close: () => set({ target: null }),+}));diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json b/jarvis/ui/web/frontend/src/i18n/locales/society/de.jsonindex e278deb505..5101c9ab7c 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/de.json@@ -1,6 +1,16 @@{"society": {"routine_detail": {+ "back_to_agent": "Zurück zum Agenten-Chat",+ "saved_result": "Gespeichertes Ausführungsergebnis",+ "historical_chat": "Diese ältere Ausführung wurde im Hauptchat des Agenten gespeichert. Hier siehst du nur diese Ausführung, schreibgeschützt.",+ "trace_unavailable": "Für diese Ausführung ist kein passender Chatverlauf verfügbar. Falls vorhanden, wird unten ihr gespeichertes Ergebnis angezeigt.",+ "latest_chat": "Letzten Chat öffnen",+ "open_chat": "Chat öffnen",+ "background_chat": "Hintergrund-Ausführung",+ "follow_up": "Zu dieser Ausführung nachfragen…",+ "stop_run": "Ausführung stoppen",+ "send": "Senden","test_started": "Testlauf gestartet.","active": "Aktiv","delete": "Löschen",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json b/jarvis/ui/web/frontend/src/i18n/locales/society/en.jsonindex 87ab773c07..53c9731bad 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/en.json@@ -1,6 +1,16 @@{"society": {"routine_detail": {+ "back_to_agent": "Back to agent chat",+ "saved_result": "Saved execution result",+ "historical_chat": "This older execution was stored in the agent's main chat. Only this execution is shown here, read-only.",+ "trace_unavailable": "No matching chat transcript is available for this execution. Its saved result is shown below when available.",+ "latest_chat": "Open latest chat",+ "open_chat": "Open chat",+ "background_chat": "Background execution",+ "follow_up": "Ask about this execution…",+ "stop_run": "Stop execution",+ "send": "Send","test_started": "Test run started.","active": "Active","delete": "Delete",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json b/jarvis/ui/web/frontend/src/i18n/locales/society/es.jsonindex 5d6383328b..266fbf68ff 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/society/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/society/es.json@@ -1,6 +1,16 @@{"society": {"routine_detail": {+ "back_to_agent": "Volver al chat del agente",+ "saved_result": "Resultado guardado de la ejecución",+ "historical_chat": "Esta ejecución antigua se guardó en el chat principal del agente. Aquí se muestra solo esta ejecución, en modo de lectura.",+ "trace_unavailable": "No hay una transcripción coincidente para esta ejecución. Su resultado guardado se muestra abajo, si está disponible.",+ "latest_chat": "Abrir último chat",+ "open_chat": "Abrir chat",+ "background_chat": "Ejecución en segundo plano",+ "follow_up": "Preguntar sobre esta ejecución…",+ "stop_run": "Detener ejecución",+ "send": "Enviar","test_started": "Prueba iniciada.","active": "Activo","delete": "Eliminar",diff --git a/jarvis/ui/web/frontend/src/lib/pluginLogos.test.ts b/jarvis/ui/web/frontend/src/lib/pluginLogos.test.tsindex fb5aaa08c1..4c2630c5ae 100644--- a/jarvis/ui/web/frontend/src/lib/pluginLogos.test.ts+++ b/jarvis/ui/web/frontend/src/lib/pluginLogos.test.ts@@ -13,7 +13,7 @@ it.each(catalog.plugins.map((plugin) => plugin.id))("ships local artwork for %s"expect(logo).not.toMatch(/^https?:/);});-it.each(["onenote", "onedrive", "azure", "google_cloud", "stripe", "cloudflare", "agentmail"])(+it.each(["onenote", "onedrive", "azure", "google_cloud", "google-cloud", "stripe", "cloudflare", "agentmail"])("never substitutes an external glyph for the reported missing %s brand", (id) => {expect(bundledPluginLogo(id)).toMatch(/(?:\.svg|\.png|\.ico|^data:)/);},diff --git a/jarvis/ui/web/frontend/src/lib/pluginLogos.ts b/jarvis/ui/web/frontend/src/lib/pluginLogos.tsindex 491289ce38..68c0d8da78 100644--- a/jarvis/ui/web/frontend/src/lib/pluginLogos.ts+++ b/jarvis/ui/web/frontend/src/lib/pluginLogos.ts@@ -5,10 +5,27 @@ const artwork = import.meta.glob("../assets/brands/*.{svg,png,ico}", {import: "default",}) as Record<string, string>;+/** Catalog ids use underscores (`google_cloud`); some lookups hyphenate them. */+export function brandIdVariants(id: string): string[] {+ const compact = id.replace(/-/g, "_");+ const hyphen = id.replace(/_/g, "-");+ return [...new Set([id, compact, hyphen].filter(Boolean))];+}+export function bundledPluginLogo(pluginId: string): string | undefined {- for (const extension of ["svg", "png", "ico"]) {- const url = artwork[`../assets/brands/${pluginId}.${extension}`];- if (url) return url;+ for (const id of brandIdVariants(pluginId)) {+ for (const extension of ["svg", "png", "ico"]) {+ const url = artwork[`../assets/brands/${id}.${extension}`];+ if (url) return url;+ }}return undefined;}++export function isRasterLogo(url: string | undefined): boolean {+ if (!url) return false;+ return (+ /\.(png|ico|jpe?g)(?:\?|$)/i.test(url) ||+ /^data:image\/(png|jpeg|gif|webp)/i.test(url)+ );+}diff --git a/jarvis/ui/web/frontend/src/store/agentChat.ts b/jarvis/ui/web/frontend/src/store/agentChat.tsindex aa8d948e2e..38f963f47b 100644--- a/jarvis/ui/web/frontend/src/store/agentChat.ts+++ b/jarvis/ui/web/frontend/src/store/agentChat.ts@@ -268,8 +268,8 @@ function onLadder(value: string, ladder: readonly string[], fallback: string): s/** How many left-behind transcripts the store keeps for an instant switch-back. */const TIMELINE_CACHE_LIMIT = 24;-export function createAgentChatStore(surface: AgentChatSurface) {- const DRAFT_KEY = draftKey(surface);+export function createAgentChatStore(surface: AgentChatSurface, draftNamespace = "") {+ const DRAFT_KEY = draftKey(surface) + (draftNamespace ? `:${draftNamespace}` : "");let socket: WebSocket | null = null;let socketSession: string | null = null;diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsxindex 8626881442..d840652eb5 100644--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.test.tsx@@ -2,6 +2,7 @@ import { cleanup, fireEvent, render, screen } from "@testing-library/react";import { afterEach, expect, it, vi } from "vitest";import { useSocietyShell } from "@/store/societyShell";import { setMapFullscreen } from "@/lib/mapFullscreen";+import { LAST_AGENT_STORAGE_KEY } from "./lastAgent";import { SocietyView } from "./SocietyView";vi.mock("@/lib/mapFullscreen", () => ({ setMapFullscreen: vi.fn(async () => undefined) }));@@ -25,7 +26,10 @@ vi.mock("@/components/society/roster/RosterRail", () => ({ RosterRail: () => <divi.mock("@/components/society/card/BuildingCardOverlay", () => ({ BuildingCardOverlay: () => null }));vi.mock("@/components/society/create/CreateAgentDialog", () => ({ CreateAgentDialog: ({ open, onClose }: any) => open ? <button onClick={onClose}>Close creator</button> : null }));-afterEach(cleanup);+afterEach(() => {+ cleanup();+ localStorage.removeItem(LAST_AGENT_STORAGE_KEY);+});it("defaults to the embedded Agents workspace even with a saved legacy ledger preference", () => {localStorage.setItem("jarvis.agents.mode.v2", "ledger");@@ -50,6 +54,17 @@ it("switches to Map and back without losing the selected agent or draft", asyncexpect(draft.value).toBe("Unsent message");});+it("restores the most recently selected agent after the view is remounted", () => {+ const firstVisit = render(<SocietyView />);+ fireEvent.click(screen.getByText("Select specialist"));+ expect(localStorage.getItem(LAST_AGENT_STORAGE_KEY)).toBe("specialist");++ firstVisit.unmount();+ render(<SocietyView />);++ expect(screen.getByText("Specialist")).toBeTruthy();+});+it("opens map selections in Agents and keeps creation available", async () => {render(<SocietyView />);fireEvent.click(screen.getByRole("tab", { name: "society.world.mode_map" }));diff --git a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsxindex 4abb542e65..cec17e67f8 100644--- a/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx+++ b/jarvis/ui/web/frontend/src/views/society/SocietyView.tsx@@ -16,6 +16,7 @@ import { useSocietyRoster } from "@/components/society/data";import { RosterRail } from "@/components/society/roster/RosterRail";import { useModelMenuData } from "@/components/society/chat/useModelMenuData";import { CanvasActivity } from "@/hooks/useCanvasAwake";+import { forgetLastAgentId, rememberLastAgentId, storedLastAgentId } from "./lastAgent";const JarvisAgentsBoard = lazy(() =>import("@/views/JarvisAgentsView").then((m) => ({ default: m.JarvisAgentsView })),@@ -29,7 +30,7 @@ export function SocietyView() {const roster = useSocietyRoster();const agents = useMemo(() => roster.data?.agents ?? [], [roster.data]);const sample = roster.data?.sample ?? true;- const [openAgentId, setOpenAgentId] = useState<string | null>(null);+ const [openAgentId, setOpenAgentId] = useState<string | null>(storedLastAgentId);const [creating, setCreating] = useState(false);const [openPlace, setOpenPlace] = useState<BuildingPlace | null>(null);@@ -38,6 +39,18 @@ export function SocietyView() {[agents, openAgentId],);+ const selectAgent = useCallback((agentId: string | null) => {+ setOpenAgentId(agentId);+ if (agentId) rememberLastAgentId(agentId);+ }, []);++ useEffect(() => {+ if (openAgentId && agents.length > 0 && !agents.some((agent) => agent.agentId === openAgentId)) {+ setOpenAgentId(null);+ forgetLastAgentId();+ }+ }, [agents, openAgentId]);+const onCreated = useCallback(() => {setCreating(false);}, []);@@ -79,10 +92,10 @@ export function SocietyView() {const onIslandSelect = useCallback((agentId: string | null) => {if (agentId) {- setOpenAgentId(agentId);+ selectAgent(agentId);switchMode("agents");}- }, [switchMode]);+ }, [selectAgent, switchMode]);// A building clicked on the island opens its own card: the building// rendered as it stands on the map, and beside it what it does.@@ -138,11 +151,11 @@ export function SocietyView() {<div className={mode === "agents" ? "flex min-h-0 flex-1 flex-col" : "hidden"}>{openAgent ? (<AgentCardOverlay embedded agent={openAgent} roster={agents} rosterLoading={roster.isLoading}- sample={sample} onSelectAgent={setOpenAgentId} onCreate={() => setCreating(true)}+ sample={sample} onSelectAgent={selectAgent} onCreate={() => setCreating(true)}onClose={() => setOpenAgentId(null)} />) : (<RosterRail agents={agents} loading={roster.isLoading} sample={sample}- activeAgentId={null} onOpen={setOpenAgentId} onCreate={() => setCreating(true)} side="left" />+ activeAgentId={null} onOpen={selectAgent} onCreate={() => setCreating(true)} side="left" />)}</div></div>diff --git a/jarvis/ui/web/frontend/src/views/society/lastAgent.ts b/jarvis/ui/web/frontend/src/views/society/lastAgent.tsnew file mode 100644index 0000000000..1c3ccadfd5--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/society/lastAgent.ts@@ -0,0 +1,31 @@+const LAST_AGENT_KEY = "jarvis.society.lastAgent";++/** Read the most recently opened Society agent, if browser storage is available. */+export function storedLastAgentId(): string | null {+ try {+ return window.localStorage.getItem(LAST_AGENT_KEY);+ } catch {+ // A disabled browser storage must not prevent the Agents view from opening.+ return null;+ }+}++/** Persist the latest explicit agent selection across section visits and app launches. */+export function rememberLastAgentId(agentId: string): void {+ try {+ window.localStorage.setItem(LAST_AGENT_KEY, agentId);+ } catch {+ /* The selection remains available for this visit when storage is unavailable. */+ }+}++/** Remove a remembered agent that no longer exists in the roster. */+export function forgetLastAgentId(): void {+ try {+ window.localStorage.removeItem(LAST_AGENT_KEY);+ } catch {+ /* Nothing to do when storage is unavailable. */+ }+}++export const LAST_AGENT_STORAGE_KEY = LAST_AGENT_KEY;diff --git a/tests/contract/test_routine_chats.py b/tests/contract/test_routine_chats.pynew file mode 100644index 0000000000..df60ec3271--- /dev/null+++ b/tests/contract/test_routine_chats.py@@ -0,0 +1,146 @@+"""Background runs keep identity, persistence and cancellation separate from chat."""++import asyncio++import pytest++from jarvis.agent_chat.store import AgentChatStore+from jarvis.society.routine_runner import run_owned_routine+from jarvis.society.routines import build_task_spec+from jarvis.tasks.runner import _owner_blocks_fallback+from jarvis.tasks.store import TaskStore+from tests.contract.test_society_continuity import world as world+++async def test_persisted_run_links_survive_reopening_without_loading_main_chat(world, tmp_path):+ runtime, service, main, _ = world+ store = TaskStore(tmp_path / "tasks.db")+ await store.init()+ runtime.task_services = lambda: (store, None)+ agent = await runtime.roster.get("mailbox")+ spec = build_task_spec(agent, title="Inbox", prompt="Read mail", schedule={"kind": "every"})+ task_id = str(await store.insert(spec))+ try:+ await run_owned_routine(runtime, task_id, spec.tags, spec.action.prompt)+ await run_owned_routine(runtime, task_id, spec.tags, spec.action.prompt)+ row = await store.get(task_id)+ links = [step["payload"]["session_id"] for step in row["steps"]]+ assert len(set(links)) == 2+ reopened = AgentChatStore(tmp_path / "chat.db")+ try:+ for sid in links:+ session = reopened.get_session(sid)+ assert session.permission_mode == "bypass"+ assert session.provider == main.provider+ assert session.cwd == main.cwd+ assert reopened.list_events(sid)[-1]["kind"] == "turn_finished"+ assert reopened.list_events(main.session_id) == []+ assert reopened.get_session(main.session_id).permission_mode == main.permission_mode+ finally:+ reopened.close()+ finally:+ await store.close()+++async def test_busy_main_chat_queues_routine_without_mixing_transcripts(world, monkeypatch):+ runtime, service, main, brain = world+ started = asyncio.Event()+ release = asyncio.Event()+ generate = brain.generate++ async def respond(text, **kwargs):+ if text == "Main conversation":+ started.set()+ await release.wait()+ return await generate(text, **kwargs)++ monkeypatch.setattr(brain, "generate", respond)+ await service.send(main.session_id, "Main conversation")+ await asyncio.wait_for(started.wait(), 2)+ created = asyncio.Event()+ create_session = service.store.create_session++ def record_session(**kwargs):+ session = create_session(**kwargs)+ created.set()+ return session++ monkeypatch.setattr(service.store, "create_session", record_session)+ routine = asyncio.create_task(+ run_owned_routine(runtime, "digest", ("society", "agent:mailbox"), "Read mail")+ )+ try:+ await asyncio.wait_for(created.wait(), 2)+ assert service.is_running(main.session_id)+ release.set()+ assert await asyncio.wait_for(routine, 3) == brain.reply+ messages = [+ e for e in service.store.list_events(main.session_id) if e["kind"] == "user_message"+ ]+ assert [e["payload"]["text"] for e in messages] == ["Main conversation"]+ finally:+ release.set()+ if not routine.done():+ routine.cancel()+ await asyncio.gather(routine, return_exceptions=True)+ await service.cancel(main.session_id)+++async def test_failed_run_stays_in_its_chat_and_cannot_fall_back(world, monkeypatch):+ runtime, service, main, brain = world++ async def fail(*args, **kwargs):+ raise RuntimeError("Synthetic provider outage")++ monkeypatch.setattr(brain, "generate", fail)+ with pytest.raises(RuntimeError, match="The routine chat failed") as failure:+ await run_owned_routine(runtime, "digest", ("society", "agent:mailbox"), "Read mail")+ assert _owner_blocks_fallback(failure.value)+ runs = [+ s for s in service.store.list_sessions(surface="society") if ":routine:" in s.session_id+ ]+ assert len(runs) == 1+ assert service.store.list_events(runs[0].session_id)[-1]["payload"]["status"] == "error"+ assert service.store.list_events(main.session_id) == []++[email protected]("via_chat", [False, True])+async def test_cancelling_routine_preserves_main_chat(world, monkeypatch, via_chat):+ runtime, service, main, brain = world+ started = asyncio.Event()+ release = asyncio.Event()++ async def hold(*args, **kwargs):+ started.set()+ await release.wait()+ return "Finished"++ monkeypatch.setattr(brain, "generate", hold)+ routine = asyncio.create_task(+ run_owned_routine(runtime, "digest", ("society", "agent:mailbox"), "Read mail")+ )+ try:+ await asyncio.wait_for(started.wait(), 2)+ if via_chat:+ session = next(+ s+ for s in service.store.list_sessions(surface="society")+ if ":routine:" in s.session_id+ )+ await service.cancel(session.session_id)+ else:+ routine.cancel()+ with pytest.raises(asyncio.CancelledError):+ await routine+ runs = [+ s for s in service.store.list_sessions(surface="society") if ":routine:" in s.session_id+ ]+ assert len(runs) == 1+ assert not service.is_running(runs[0].session_id)+ assert service.store.list_events(runs[0].session_id)[-1]["payload"]["status"] == "cancelled"+ assert service.store.list_events(main.session_id) == []+ finally:+ release.set()+ if not routine.done():+ routine.cancel()+ await asyncio.gather(routine, return_exceptions=True)diff --git a/tests/contract/test_society_continuity.py b/tests/contract/test_society_continuity.pyindex e6da1b9754..ac9df89659 100644--- a/tests/contract/test_society_continuity.py+++ b/tests/contract/test_society_continuity.py@@ -251,7 +251,14 @@ async def test_routine_uses_current_rules_and_memory(world):briefing = kwargs["turn_override"].system_extraassert "Use plain text and never send mail." in briefing and "Cedar" in briefingassert "Prepare drafts only." not in prompt- assert kwargs["conversation_id"] == session.session_id+ routine_session_id = kwargs["conversation_id"]+ assert routine_session_id.startswith(f"{session.session_id}:routine:{spec.id}:")+ assert svc.store.get_session(routine_session_id).permission_mode == "bypass"+ assert svc.store.list_events(session.session_id) == []++ await run_owned_routine(rt, str(spec.id), spec.tags, spec.action.prompt)+ assert brain.calls[-1][1]["conversation_id"] != routine_session_id+ assert svc.store.list_events(session.session_id) == []async def test_routine_update_preserves_id_and_pause_state(tmp_path):diff --git a/tests/integration/test_coding_supervision_routine.py b/tests/integration/test_coding_supervision_routine.pyindex 7f2b71c19b..04164b40bf 100644--- a/tests/integration/test_coding_supervision_routine.py+++ b/tests/integration/test_coding_supervision_routine.py@@ -100,8 +100,10 @@ async def test_routine_question_and_result_stay_in_real_owner_chat(rig, tmp_pathmonkeypatch.setattr(runner_brain, "brain_manager", lambda: brain)monkeypatch.setattr(runner_brain, "_agent_secret", lambda *args: "synthetic-test-key")+ routine_session_id = ""+async def idle():- running = service._running.get(owner.session_id)+ running = service._running.get(routine_session_id)if running is not None and running.task is not None:await asyncio.wait_for(asyncio.shield(running.task), timeout=5)@@ -109,6 +111,8 @@ async def test_routine_question_and_result_stay_in_real_owner_chat(rig, tmp_pathanswer = await run_owned_routine(runtime, "routine-proof", ("society", agent_tag(owner.agent_id)), "Inspect the branch")+ routine_session_id = identities[0][0]+ assert routine_session_id.startswith(f"{owner.session_id}:routine:")assert answer == "Assignment started under supervision."await idle()key = runtime.coding_supervision.key(opened)@@ -120,11 +124,12 @@ async def test_routine_question_and_result_stay_in_real_owner_chat(rig, tmp_pathawait runtime.coding_supervision.tick(key)await idle()assert runtime.coding_supervision.rows[key]["state"] == "finished"- assert identities == [(owner.session_id, False)] * 3- events = service.store.list_events(owner.session_id)+ assert identities == [(routine_session_id, False)] * 3+ assert service.store.list_events(owner.session_id) == []+ events = service.store.list_events(routine_session_id)assert len([e for e in events if e["kind"] == "agent_message"]) == 2assert len([e for e in events if e["kind"] == "turn_started"]) == 3finally:- await service.cancel(owner.session_id)+ await service.cancel(routine_session_id)await idle()service.store.close()diff --git a/tests/unit/agent_chat/test_agent_chat_ladders.py b/tests/unit/agent_chat/test_agent_chat_ladders.pyindex 5a4dca6823..8ea8173421 100644--- a/tests/unit/agent_chat/test_agent_chat_ladders.py+++ b/tests/unit/agent_chat/test_agent_chat_ladders.py@@ -67,7 +67,7 @@ def test_new_agy_gemini_base_keeps_required_effort_without_a_catalog():async def test_agy_cold_chat_resolves_catalog_before_building_command(tmp_path, monkeypatch):seen = []- def catalog():+ def catalog(**kwargs):seen.append("catalog")return []@@ -93,6 +93,50 @@ async def test_agy_cold_chat_resolves_catalog_before_building_command(tmp_path,assert result.error == "stop before process launch"+def test_agy_refreshes_a_cached_fallback_missing_the_scheduled_model(monkeypatch):+ import subprocess+ import time++ monkeypatch.setattr(+ runner_cli,+ "_AGY_CATALOG",+ {+ "at": time.monotonic(),+ "rows": [{"id": "old-model", "efforts": []}],+ },+ )+ monkeypatch.setattr(runner_cli, "agy_argv_prefix", lambda: ["agy"])+ calls = []++ def models(*args, **kwargs):+ calls.append(args)+ return SimpleNamespace(+ stdout=json.dumps(+ {+ "command": {+ "data": {+ "models": [+ {"id": "current-model-low"},+ {"id": "current-model-high"},+ ]+ }+ }+ }+ ).encode()+ )++ monkeypatch.setattr(subprocess, "run", models)+ rows = runner_cli.read_agy_models(required_model="current-model")+ assert agy_model_args("current-model", "high", rows) == [+ "--model",+ "current-model",+ "--effort",+ "high",+ ]+ runner_cli.read_agy_models(required_model="current-model")+ assert len(calls) == 1++@pytest.mark.parametrize("runner", ["agy-cli", "codex-cli", "grok-cli"])async def test_society_cli_effort_is_chosen_for_each_turn(tmp_path, monkeypatch, runner):seen = []@@ -103,7 +147,7 @@ async def test_society_cli_effort_is_chosen_for_each_turn(tmp_path, monkeypatch,monkeypatch.setitem(runner_cli._PLANNERS, runner, planner)if runner == "agy-cli":- monkeypatch.setattr(runner_cli, "read_agy_models", lambda: [])+ monkeypatch.setattr(runner_cli, "read_agy_models", lambda **kwargs: [])handle = SimpleNamespace(session=SimpleNamespace(session_id="society:scout",