Skip to content

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.

fix(agents): failed turns say why with Retry, names keep underscores, readable trace labels, short approval paths, cost-safe starter seat (#932)

Ruben Lütke2e492063b971
diff --git a/dodaios/agent_chat/approval_card.py b/dodaios/agent_chat/approval_card.py
index 9165583a99..09d4c9b426 100644
--- a/dodaios/agent_chat/approval_card.py
+++ b/dodaios/agent_chat/approval_card.py
@@ -14,7 +14,9 @@ event has none of them and the card falls back to the tool name and summary.
``source`` ``{kind, app?, verb?}``. ``kind`` is one of :data:`SOURCE_KINDS`;
``app`` names the connector or MCP server a ``connector`` call goes
to, ``verb`` the one-word action it performs there (``send``).
-``where`` the folder, site or machine the action runs at.
+``where`` the folder, site or machine the action runs at: the chat's own
+ folder as its name ("workspace"), a path inside it relative.
+``where_full`` that folder in full, for the card's details only.
``why`` the agent's own reason, when its runner passes one (Claude's Bash
``description``, a Codex ``reason``).
``caution`` ``""`` or one of :data:`CAUTIONS`: an action that cannot be undone,
@@ -177,6 +179,8 @@ def _describe(
fields: dict[str, Any] = {
"source": source,
"where": display_paths(_where(kind, args, cwd), cwd),
+ # The card's details name the whole folder; the line above stays short.
+ "where_full": _where(kind, args, cwd),
"why": display_paths(_why(args), cwd),
"caution": caution_of(kind, command, verb),
"detail": "" if kind == "plan" else request_detail(args, command),
@@ -223,8 +227,12 @@ def display_paths(text: str, cwd: str = "", home: str | None = None) -> str:
if len(folder) > 3 and not (home_dir and _same_folder(folder, home_dir)):
inside = _path_pattern(folder)
if inside is not None:
- # "<cwd>/src/x" -> "src/x"; the folder alone stays and is shortened below.
+ # "<cwd>/src/x" -> "src/x"; the folder alone reads as its own name
+ # ("workspace"), never as the long path the agent happens to live at.
out = re.sub(inside.pattern + _SEP + r"+(?=\S)", "", out, flags=inside.flags)
+ name = re.split(r"[\\/]", folder)[-1]
+ if name:
+ out = inside.sub(lambda _m: name, out)
if len(home_dir) > 3:
at_home = _path_pattern(home_dir)
if at_home is not None:
@@ -244,7 +252,16 @@ _NARROW_COMMAND_CHARS: Final[int] = 400
def _call_paths(args: dict[str, Any]) -> list[str]:
- return [v.strip() for k in _PATH_KEYS if isinstance(v := args.get(k), str) and v.strip()]
+ # A runtime's permission request nests the tool's own arguments
+ # ({"tool": "write_file", "arguments": {"path": ...}}).
+ nested = args.get("arguments")
+ pool = [args, nested] if isinstance(nested, dict) else [args]
+ return [
+ v.strip()
+ for part in pool
+ for k in _PATH_KEYS
+ if isinstance(v := part.get(k), str) and v.strip()
+ ]
def _absolute(path: str, cwd: str) -> str:
diff --git a/dodaios/agent_chat/runner_cli.py b/dodaios/agent_chat/runner_cli.py
index c1bfccc391..431614d3ce 100644
--- a/dodaios/agent_chat/runner_cli.py
+++ b/dodaios/agent_chat/runner_cli.py
@@ -4363,6 +4363,17 @@ async def _drive_cli(
elif (runner in {"claude-cli", "glm-cli"} or plan.acp is not None) and not state.saw_result:
status = "error"
error_text = f"{runner} exited without a terminal result; its output may be incomplete."
+ if (
+ status == "done"
+ and not getattr(state, "emitted_text", False)
+ and not str(getattr(state, "result_text", "") or "").strip()
+ ):
+ # The runtime swallowed a recoverable gateway failure (it may retry)
+ # and then ended with no answer: the turn failed, and says why.
+ from dodaios.agent_runtimes import gateway
+
+ if swallowed := gateway.last_failure(plan.provider_failure):
+ status, error_text = "error", swallowed
usage = dict(state.usage)
cost_usd = getattr(state, "cost_usd", None)
diff --git a/dodaios/agent_runtimes/acp.py b/dodaios/agent_runtimes/acp.py
index abeeccdc86..42943b50c2 100644
--- a/dodaios/agent_runtimes/acp.py
+++ b/dodaios/agent_runtimes/acp.py
@@ -509,6 +509,9 @@ class AcpTurn:
return
name = normalize_tool_name(_tool_name(update))
args = update.get("rawInput") if isinstance(update.get("rawInput"), dict) else {}
+ if not args and (path := _location_path(update)):
+ # Hermes sends no input for its own file tools, only where they act.
+ args = {"path": path}
self.emitted_tool_ids.add(call_id)
self._tool_names[call_id] = name
self._tool_started[call_id] = time.perf_counter()
@@ -635,6 +638,18 @@ def _tool_name(update: dict[str, Any]) -> str:
return str(update.get("kind") or "tool")
+def _location_path(update: dict[str, Any]) -> str:
+ """The first file a tool call says it acts on (ACP ``locations``), or ""."""
+ locations = update.get("locations")
+ if not isinstance(locations, list):
+ return ""
+ for location in locations:
+ path = location.get("path") if isinstance(location, dict) else None
+ if isinstance(path, str) and path:
+ return path
+ return ""
+
+
def _failure_reason(text: str, patterns: tuple[re.Pattern[str], ...]) -> str:
"""The reason in ``text`` when it is one of the runtime's failure replies ("" otherwise)."""
stripped = text.strip()
diff --git a/dodaios/agent_runtimes/gateway.py b/dodaios/agent_runtimes/gateway.py
index d247f10de9..5481d125c3 100644
--- a/dodaios/agent_runtimes/gateway.py
+++ b/dodaios/agent_runtimes/gateway.py
@@ -37,6 +37,7 @@ import secrets
import threading
import time
import uuid
+import weakref
from collections import OrderedDict
from collections.abc import AsyncIterator, Iterator
from concurrent.futures import Future
@@ -107,6 +108,10 @@ _METADATA_TTL_S: Final[float] = 15 * 60
_METADATA: dict[tuple[str, str, str], tuple[float, Any]] = {}
_METADATA_REFRESH: dict[tuple[str, str, str], asyncio.Task[Any]] = {}
_FAILURES: dict[Grant, Future[str]] = {}
+#: The last recoverable failure of each watched turn. The runtime keeps such
+#: a failure (it may retry or compress); when the turn then ends without an
+#: answer, the runner reports this instead of a silent empty turn.
+_LAST_FAILURES: weakref.WeakKeyDictionary[Future[str], str] = weakref.WeakKeyDictionary()
_TURN_EFFORTS: dict[Grant, str] = {}
_COOLDOWNS: OrderedDict[tuple[str, str, str], float] = OrderedDict()
_DEFAULT_COOLDOWN_S: Final = 30.0
@@ -445,6 +450,21 @@ def watch_failure(token: str, *, effort: str = "") -> Future[str]:
return signal
+def last_failure(signal: Future[str] | None) -> str:
+ """The last recoverable failure the gateway saw for this turn ("" for none)."""
+ if signal is None:
+ return ""
+ with _LOCK:
+ return _LAST_FAILURES.get(signal, "")
+
+
+def _answered(signal: Future[str] | None) -> None:
+ """A later request of the turn got its answer: an earlier failure was recovered."""
+ if signal is not None:
+ with _LOCK:
+ _LAST_FAILURES.pop(signal, None)
+
+
def unwatch_failure(token: str, signal: Future[str]) -> None:
with _LOCK:
grant = _GRANTS.get(token)
@@ -551,6 +571,9 @@ def _report_failure(
failure = _limited(grant.provider, seconds)
from dodaios.agent_runtimes.provider_errors import is_terminal
+ if signal is not None and not is_terminal(failure.code):
+ with _LOCK:
+ _LAST_FAILURES[signal] = str(failure)
# Recoverable failures stay with the runtime for retry or compression.
if signal is not None and is_terminal(failure.code):
# A request captures its turn's signal before awaiting the provider.
@@ -706,6 +729,7 @@ async def stream_response(
yield _sse(event)
if not completed:
raise GatewayError("ChatGPT ended before completion.", status=502, code="incomplete")
+ _answered(signal)
except (SubscriptionReasoningError, SubscriptionAuthError, GatewayError) as exc:
log.info("runtime gateway: %s turn failed (%s)", grant.agent_id, type(exc).__name__)
failure = _report_failure(grant, model, _subscription_failure(grant, exc), signal)
@@ -777,6 +801,7 @@ async def complete_response(
if event.get("type") == "response.completed" and isinstance(finished, dict):
# ChatGPT's backend streams the output items and sends the
# completed response with an empty ``output``.
+ _answered(signal)
return {**finished, "output": finished.get("output") or items}
except (SubscriptionReasoningError, SubscriptionAuthError, GatewayError) as exc:
raise _report_failure(grant, model, _subscription_failure(grant, exc), signal) from exc
@@ -1443,6 +1468,8 @@ async def _chat_chunks(
payload = {"error": {"message": str(failure), "type": failure.code, "code": failure.code}}
yield f"data: {json.dumps(payload)}\n\n".encode()
return
+ else:
+ _answered(signal)
finally:
# The runner stops on a provider failure; a closed HTTP client must
# also release the plugin task if it was suspended between deltas.
@@ -1505,6 +1532,7 @@ async def complete_chat(
)
except Exception as exc: # noqa: BLE001 — becomes the runtime's HTTP error; _failure logs it
raise _report_failure(grant, model, _failure(grant.provider, exc, model), signal) from exc
+ _answered(signal)
message: dict[str, Any] = {"role": "assistant", "content": "".join(text) or None}
if calls:
message["tool_calls"] = [{k: v for k, v in call.items() if k != "index"} for call in calls]
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx b/dodaios/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx
index 538a15e7fd..34c9bba0b5 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/InternalMessageBubble.tsx
@@ -7,6 +7,7 @@ import { AgentSwatch } from "@/components/society/AgentSwatch";
import type { FigureRecipe } from "@/components/society/figures/figureRecipe";
import { useT } from "@/i18n";
import { cn } from "@/lib/utils";
+import { flattenMarks } from "@/lib/plainMarks";
import type { InternalMessageItem } from "./reduce";
@@ -23,11 +24,7 @@ export interface InternalParticipant {
* as a sentence, never as a wall.
*/
export function internalPreview(text: string, max = 140): string {
- const flat = text
- .replace(/```[\s\S]*?```/g, " ")
- .replace(/[`*_#>~|]+/g, "")
- .replace(/\s+/g, " ")
- .trim();
+ const flat = flattenMarks(text);
if (!flat) return "";
const first = flat.split(/(?<=[.!?…])\s/)[0] ?? flat;
const sentence = first.trim();
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx b/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx
index 610c5c29c3..2bd46e53b7 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/MessengerTurn.tsx
@@ -1,5 +1,5 @@
import { memo, useEffect, useMemo, useState, type ReactNode } from "react";
-import { BookmarkPlus, CircleAlert, Clock3, Feather, NotebookPen, SlidersHorizontal } from "lucide-react";
+import { BookmarkPlus, CircleAlert, Clock3, Feather, NotebookPen, RotateCcw, SlidersHorizontal } from "lucide-react";
import { ChatMarkdown } from "./ChatMarkdown";
import { CredentialCard } from "./CredentialCard";
import { QuestionCard } from "./QuestionCard";
@@ -28,7 +28,7 @@ import { turnErrorText } from "./turnError";
* quiet line under the turn (WorkDisclosure) opens the whole trace in the
* work inspector.
*/
-export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color, onDecide, memoryLinks, nameOf, peerFace, onShowWork, workOpen = false }: {
+export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color, onDecide, memoryLinks, nameOf, peerFace, onShowWork, workOpen = false, onRetry }: {
turn: TurnItem;
/** The agent's face at 30 px; it plays the scenes. */
avatar: ReactNode;
@@ -45,12 +45,17 @@ export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color,
onShowWork?: () => void;
/** The inspector shows this turn right now. */
workOpen?: boolean;
+ /** Sends the person's last message again; a failed turn offers it as "Retry". */
+ onRetry?: () => void;
}) {
const t = useT();
const textLength = useMemo(() => turn.blocks.reduce((n, block) => n + (block.kind === "text" ? block.text.length : 0), 0), [turn.blocks]);
const hasText = textLength > 0 && turn.blocks.some((block) => block.kind === "text" && block.text.trim());
const flourish = useDoneFlourish(turn.status === "running", turn.status === "done");
const running = turn.status === "running";
+ // A turn the runtime ended with an error, or that ended silent with an
+ // error on record, failed: it says why, whatever runtime ran it.
+ const failed = turn.status === "error" || (turn.status === "done" && !hasText && Boolean(turn.error));
const work = onShowWork ? <WorkDisclosure turn={turn} open={workOpen} onOpen={onShowWork} /> : null;
let noteIndex = 0;
return <div className="flex min-w-0 flex-col gap-1.5" data-testid="messenger-turn" data-status={turn.status}>
@@ -77,14 +82,9 @@ export const MessengerTurn = memo(function MessengerTurn({ turn, avatar, color,
<ActivityLine turn={turn} avatar={avatar} color={color} nameOf={nameOf} peerFace={peerFace} />
{work}
</div> : flourish ? <BotStage presence="done" seed={turn.id} avatar={avatar} color={color} /> : null}
- {turn.status === "error" && (
- <p role="alert" className="mx-auto flex max-w-[85%] items-center gap-1.5 py-1 text-center text-xs text-destructive">
- <CircleAlert aria-hidden className="h-3.5 w-3.5 shrink-0" />
- <span>{turnErrorText(turn.error, t) || t("thread_turn.failed")}</span>
- </p>
- )}
+ {failed && <TurnFailure reason={turnErrorText(turn.error, t) || t("thread_turn.failed_no_reason")} onRetry={onRetry} />}
{turn.status === "cancelled" && <SystemLine>{t("thread_turn.stopped")}</SystemLine>}
- {turn.status === "done" && !hasText && !flourish && <SystemLine>{t("thread_turn.no_answer")}</SystemLine>}
+ {turn.status === "done" && !failed && !hasText && !flourish && <SystemLine>{t("thread_turn.no_answer")}</SystemLine>}
{!running ? work : null}
</div>;
});
@@ -119,6 +119,24 @@ export function MessageBubble({ text }: { text: string }) {
</div>;
}
+/** A failed turn: the reason the runtime gave, and one click to send the message again. */
+export function TurnFailure({ reason, onRetry }: { reason: string; onRetry?: () => void }) {
+ const t = useT();
+ return <div role="alert" data-testid="turn-failure"
+ className="flex min-w-0 max-w-[min(85%,42rem)] items-start gap-2 rounded-2xl border border-destructive/30 bg-destructive/10 px-3 py-2 text-xs text-destructive">
+ <CircleAlert aria-hidden className="mt-px h-3.5 w-3.5 shrink-0" />
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5">
+ <span className="font-medium">{t("thread_turn.failed_title")}</span>
+ <span className="[overflow-wrap:anywhere] text-destructive/90" data-testid="turn-failure-reason">{reason}</span>
+ </div>
+ {onRetry ? <button type="button" onClick={onRetry} data-testid="turn-retry"
+ className="flex shrink-0 items-center gap-1 rounded-md border border-destructive/40 px-2 py-0.5 font-medium transition-colors hover:bg-destructive/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">
+ <RotateCcw aria-hidden className="h-3 w-3" />
+ {t("thread_turn.retry")}
+ </button> : null}
+ </div>;
+}
+
function SystemLine({ children }: { children: ReactNode }) {
return <p className="py-1 text-center text-xs text-muted-foreground">{children}</p>;
}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/TraceTimeline.tsx b/dodaios/ui/web/frontend/src/components/agentchat/TraceTimeline.tsx
index 8d4d518c23..3e07812c56 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/TraceTimeline.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/TraceTimeline.tsx
@@ -9,6 +9,7 @@ import { ToolChoiceIcon } from "./ToolChoiceChips";
import type { ToolChoice } from "./toolChoices";
import { toolIdentity, toolIdentityStyle } from "./toolIdentity";
import { traceToolIdentity } from "./traceActivity";
+import { flattenMarks } from "@/lib/plainMarks";
import type { TraceMessage } from "./turnMessages";
import {
buildTimeline, readableOutput, traceDuration, tr,
@@ -250,7 +251,7 @@ function CallDetails({ call, renderers }: { call: Call; renderers: TimelineRende
export function TraceMessageLine({ message }: { message: TraceMessage }) {
const t = useT();
const [open, setOpen] = useState(false);
- const preview = message.text.replace(/[`*_#>]/g, "").replace(/\s+/g, " ").trim();
+ const preview = flattenMarks(message.text);
return <div className="min-w-0" data-trace-entry="message" data-outgoing={message.outgoing ? "" : undefined}>
<button type="button" className={lineButton} aria-expanded={open} onClick={() => setOpen(!open)}>
<MessagesSquare aria-hidden className={glyph} strokeWidth={1.75} />
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/WorkTrace.tsx b/dodaios/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
index 1386835aba..5db7ae264a 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/WorkTrace.tsx
@@ -21,6 +21,7 @@ import { timelineItems, useTimeline, type TimelineRenderers } from "./TraceTimel
import { traceDuration } from "./traceEntries";
import "./WorkTrace.css";
import { turnErrorText } from "./turnError";
+import { flattenMarks } from "@/lib/plainMarks";
export type Decide = (id: string, decision: ApprovalDecision) => void | Promise<void>;
type Group = { id: string; blocks: TurnBlock[]; family: string | null };
@@ -302,7 +303,7 @@ export function ReasoningTrace({ block, turnLive, compact = false }: { block: Re
const duration = live ? elapsed : block.durationMs;
const label = duration === null ? t("work_trace.thought")
: t(live ? "work_trace.thinking_for" : "work_trace.thought_for").replace("{duration}", traceDuration(duration));
- const gist = text.replace(/```[\s\S]*?```/g, " ").replace(/[`*_#>~]/g, "").replace(/\s+/g, " ").trim();
+ const gist = flattenMarks(text);
const showGist = !compact && !turnLive && gist;
if (rail) return <Disclosure label={<Live on={live}>{label}</Live>}
live={live} forced={live} initiallyOpen={compact ? live : turnLive}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx
index b3261be1c9..ccd3301a42 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/ApprovalActionCard.tsx
@@ -8,7 +8,7 @@ import type { ApprovalState, ToolBlock } from "../reduce";
import { ToolChoiceIcon } from "../ToolChoiceChips";
import type { ToolChoice } from "../toolChoices";
import { ActionCard, type ActionSpec, type SettledSpec } from "./ActionCard";
-import { approvalTitle, cardInfoOf, narrowSentence, outcomeLabel, outcomeTone, ruleSentence, savedRuleSentence, shownSummary, sourceLabel } from "./approvalCopy";
+import { approvalTitle, cardInfoOf, disclosureText, narrowSentence, outcomeLabel, outcomeTone, ruleSentence, savedRuleSentence, shownSummary, sourceLabel } from "./approvalCopy";
import type { ApprovalCardInfo, ApprovalRuleOffer, RuleBreadth, RuleNarrow, RuleScope } from "./approvalInfo";
import { claimKeyboardTarget, TARGET_PRIORITY } from "./keyboardTarget";
@@ -63,7 +63,8 @@ function subtitleLines(info: ApprovalCardInfo, approval: ApprovalState, title: s
const lines: ReactNode[] = [];
const { kind } = info.source;
if (info.where) {
- lines.push(fill(t(kind === "browser" ? "action_card.field.on" : "action_card.field.in"), { where: info.where }));
+ const line = fill(t(kind === "browser" ? "action_card.field.on" : "action_card.field.in"), { where: info.where });
+ lines.push(info.whereFull && info.whereFull !== info.where ? <span title={info.whereFull}>{line}</span> : line);
}
// A command is read in its own block below; a summary that only repeats it says nothing new.
const what = shownSummary(info, approval.summary);
@@ -137,6 +138,7 @@ function OpenApproval({ block, approval, info, onDecide }: {
{ id: "deny", label: t("action_card.deny"), tone: "tertiary", onSelect: () => void decide("deny"), disabled: !onDecide, reason: elsewhere, hint: t("action_card.deny_esc"), keyShortcut: "Escape", testId: "action-card-deny" },
];
const plan = isPlan ? planText(block) : "";
+ const disclosure = disclosureText(info, t);
return <ActionCard
id={approval.approvalId}
testId="thread-approval"
@@ -145,8 +147,8 @@ function OpenApproval({ block, approval, info, onDecide }: {
title={title}
ariaLabel={`${t("action_card.needs_approval")}: ${title}`}
lines={subtitleLines(info, approval, title, t)}
- disclosure={info.detail ? {
- text: info.detail,
+ disclosure={disclosure ? {
+ text: disclosure,
showLabel: t(kind === "terminal" ? "action_card.show_command" : "action_card.show_details"),
hideLabel: t(kind === "terminal" ? "action_card.hide_command" : "action_card.hide_details"),
defaultOpen: kind === "terminal" && info.detail.length <= 400,
@@ -322,8 +324,8 @@ function SettledApproval({ block, approval, info }: { block: ToolBlock; approval
title={title}
ariaLabel={`${settled.label}: ${title}`}
lines={subtitleLines(info, approval, title, t)}
- disclosure={info.detail ? {
- text: info.detail,
+ disclosure={disclosureText(info, t) ? {
+ text: disclosureText(info, t),
showLabel: t(info.source.kind === "terminal" ? "action_card.show_command" : "action_card.show_details"),
hideLabel: t(info.source.kind === "terminal" ? "action_card.hide_command" : "action_card.hide_details"),
} : undefined}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/actionCardUnits.test.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/actionCardUnits.test.ts
index 84d3fd11ed..839e9d383c 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/actionCardUnits.test.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/actionCardUnits.test.ts
@@ -4,7 +4,7 @@ import type { AgentChatEvent } from "@/lib/agentChatApi";
import { claimKeyboardTarget, TARGET_PRIORITY } from "./keyboardTarget";
import { maskedRequest, maskText } from "./redact";
import { parseApprovalCard, parseSavedRule } from "./approvalInfo";
-import { shortenHome } from "./approvalCopy";
+import { disclosureText, shortenHome } from "./approvalCopy";
let seq = 0;
const ev = (kind: string, payload: Record<string, unknown>): AgentChatEvent => ({ seq: ++seq, ts_ms: seq, kind, payload } as AgentChatEvent);
@@ -149,3 +149,24 @@ describe("short paths and narrow rules", () => {
expect(parseSavedRule({ rule_kind: "always_allow", scope: "chat", narrow: "planet" })?.narrow).toBeUndefined();
});
});
+
+
+describe("the approval card's paths", () => {
+ const t = (key: string) => (key === "action_card.field.in" ? "In {where}" : key);
+ const full = "C:\\Users\\me\\data\\society\\agent-1\\workspace";
+
+ it("shows the workspace short and names it in full only in the details", () => {
+ const info = parseApprovalCard({
+ source: { kind: "files" }, where: "workspace", where_full: full,
+ detail: "{\"path\": \"qa_note.txt\"}", brief: "Approve edit: qa_note.txt",
+ })!;
+ expect(info.where).toBe("workspace");
+ expect(info.brief).toBe("Approve edit: qa_note.txt");
+ expect(disclosureText(info, t)).toBe(`In ${full}\n\n{"path": "qa_note.txt"}`);
+ });
+
+ it("adds nothing when the line already shows the whole folder", () => {
+ const info = parseApprovalCard({ source: { kind: "terminal" }, where: "~/proj", detail: "ls" })!;
+ expect(disclosureText(info, t)).toBe("ls");
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts
index 1114b6b1b0..89eba5ea2b 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalCopy.ts
@@ -40,6 +40,7 @@ export function cardInfoOf(block: ToolBlock): ApprovalCardInfo {
return {
source: { kind, app, verb: typeof input.action === "string" && /^[a-z][a-z0-9_.-]{0,39}$/.test(input.action) ? input.action : "" },
where,
+ whereFull: "",
why,
caution: null,
detail: kind === "plan" ? "" : maskedRequest(block.input),
@@ -117,6 +118,18 @@ export function shortenHome(text: string): string {
return text.replace(WIN_HOME, "~").replace(POSIX_HOME, "$1~");
}
+/**
+ * What a card's details disclosure says: the folder in full when the line
+ * above shows it short, then the exact request. "" when there is nothing.
+ */
+export function disclosureText(info: ApprovalCardInfo, t: T): string {
+ const full = info.whereFull.trim();
+ const folder = full && full !== info.where
+ ? fill(t(info.source.kind === "browser" ? "action_card.field.on" : "action_card.field.in"), { where: full })
+ : "";
+ return [folder, info.detail].filter(Boolean).join("\n\n");
+}
+
/** The summary a card shows: the backend's short-path brief, else the summary with `~`. */
export function shownSummary(info: ApprovalCardInfo, summary: string): string {
return (info.brief || shortenHome(summary)).trim();
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts
index 5135a8f27e..af6ddad8ba 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/actionCard/approvalInfo.ts
@@ -39,6 +39,8 @@ export interface ApprovalCardInfo {
/** What is asking; `verb` is the one-word action a connector call performs ("send"). */
source: { kind: ApprovalSourceKind; app: string; verb: string };
where: string;
+ /** `where` in full (the card's details only); "" when it is the same or unknown. */
+ whereFull: string;
why: string;
caution: ApprovalCaution | null;
/** The exact command or request, secrets masked by the backend. */
@@ -80,6 +82,7 @@ export function parseApprovalCard(payload: Record<string, unknown>): ApprovalCar
return {
source: { kind: KINDS.has(kind) ? kind : "tool", app: text(source.app), verb: text(source.verb) },
where: text(payload.where),
+ whereFull: text(payload.where_full),
why: text(payload.why),
caution: CAUTIONS.has(caution) ? caution : null,
detail: text(payload.detail),
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/activity/activityModel.ts b/dodaios/ui/web/frontend/src/components/agentchat/activity/activityModel.ts
index 20115ac813..67a7be9f9e 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/activity/activityModel.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/activity/activityModel.ts
@@ -83,7 +83,10 @@ export type NameOf = (idOrName: string) => string;
const identity: NameOf = (value) => value;
function record(value: unknown): Record<string, unknown> {
- return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
+ const out = value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
+ // A runtime's permission request nests the tool's own arguments ({ tool, arguments: { path } }).
+ const nested = out.arguments;
+ return nested && typeof nested === "object" && !Array.isArray(nested) ? { ...(nested as Record<string, unknown>), ...out } : out;
}
function firstString(input: Record<string, unknown>, keys: string[]): string {
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspectorRows.ts b/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspectorRows.ts
index 73742bf66c..a966ea92ba 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspectorRows.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/inspector/inspectorRows.ts
@@ -13,7 +13,8 @@
import { isSubagentCall } from "@/components/agentic/threads/subagents";
import type { ReasoningBlock, TextBlock, ToolBlock, TurnBlock, TurnStatus } from "../reduce";
-import { callOf, isPlumbing, readableOutput, type Call, type Translate } from "../traceEntries";
+import { callOf, isPlumbing, outputGist, readableOutput, type Call, type Translate } from "../traceEntries";
+import { stripInlineMarks } from "@/lib/plainMarks";
export type RowKind = "prompt" | "thought" | "reply" | "call" | "question" | "approval" | "credential" | "helper";
export type RowStatus = "running" | "done" | "failed" | "waiting" | "stopped" | "declined";
@@ -45,12 +46,12 @@ export function plainPreview(text: string, max = PREVIEW_MAX): string {
return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean;
}
-/** First meaningful line, markdown marks dropped, capped. */
+/** First meaningful line, markdown marks dropped (underscores in names stay), capped. */
export function previewOf(text: string, max = PREVIEW_MAX): string {
const line = text
.replace(/```[\s\S]*?```/g, " ")
.split(/\r?\n/)
- .map((part) => part.replace(/^[#>*\-\s]+/, "").replace(/[`*_~]/g, "").trim())
+ .map((part) => stripInlineMarks(part.replace(/^[#>*\-\s]+/, "")).trim())
.find(Boolean) ?? "";
const clean = line.replace(/\s+/g, " ");
return clean.length > max ? `${clean.slice(0, max - 1).trimEnd()}…` : clean;
@@ -126,7 +127,7 @@ function callRow(block: ToolBlock, turn: TurnStatus, t: Translate, lang: string)
return {
id: block.callId, kind: "call", status: CALL_STATUS[call.status], label: call.text,
// A call's own words are plain text (ids, paths, queries): only its output reads as markdown.
- preview: tail ? plainPreview(tail) : previewOf(call.kind === "command" ? "" : readableOutput(block)),
+ preview: tail ? plainPreview(tail) : previewOf(call.kind === "command" ? "" : outputGist(readableOutput(block))),
added: call.added, removed: call.removed, durationMs: block.durationMs, block, call,
};
}
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts b/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts
index 3a0c4b0455..1e4b8e8071 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/reduce.ts
@@ -1312,7 +1312,9 @@ export function reduceEvent(tl: Timeline, ev: AgentChatEvent): Timeline {
? (p.usage as Record<string, unknown>)
: turn.liveUsage,
costUsd: num(p.cost_usd),
- error: str(p.error, "") || null,
+ // A runtime's own error event earlier in the turn stays its reason
+ // when the end of the turn names none.
+ error: str(p.error, "") || turn.error || null,
...(Array.isArray(p.background) && p.background.length > 0
? { background: (p.background as unknown[]).map((name) => str(name)) }
: {}),
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.test.ts b/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.test.ts
index d0d48515ea..edfb783ac9 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.test.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.test.ts
@@ -6,7 +6,7 @@ import pt from "@/i18n/locales/pt.json";
import { reduceThinkingSteps, type ThinkingStep } from "@/lib/thinkingSteps";
import type { ToolBlock, TurnBlock } from "./reduce";
import {
- buildTimeline, commandBinary, ownServerTool, shortPath, traceDuration, withoutCd,
+ buildTimeline, callOf, commandBinary, isIdentifier, outputGist, ownServerTool, shortPath, traceDuration, withoutCd,
type ActivityEntry, type Call, type TimelineOptions,
} from "./traceEntries";
import { stepsToBlocks } from "./VoiceWorkTrace";
@@ -204,3 +204,32 @@ describe("trace_report locale parity", () => {
expect(JSON.stringify((en as Dict).trace_report)).not.toContain("{name}");
});
});
+
+
+describe("readable call labels", () => {
+ it("names the file of a runtime's nested permission request, never the tool id", () => {
+ const call = callOf(tool("e", { name: "edit", input: { tool: "write_file", arguments: { path: "qa_note.txt", content: "hi" } }, output: "done" }), "done", t, "en");
+ expect(call.text).toBe("Edited qa_note.txt");
+ });
+
+ it("says what a file tool did when it names no file", () => {
+ expect(callOf(tool("w", { name: "write_file", input: {}, output: "done" }), "done", t, "en").text).toBe("Created a file");
+ expect(callOf(tool("e", { name: "edit", input: {}, output: "done" }), "done", t, "en").text).toBe("Edited a file");
+ });
+
+ it("drops a runtime's receipt words from what a call returned", () => {
+ expect(outputGist("tool_search result")).toBe("");
+ expect(outputGist("tool_describe result\n- **name:** gmail_send")).toBe("- **name:** gmail_send");
+ expect(outputGist("✅ patch completed")).toBe("");
+ expect(outputGist("done")).toBe("");
+ expect(outputGist("Saved qa_note.txt")).toBe("Saved qa_note.txt");
+ const call = callOf(tool("s", { name: "skills_list", input: {}, output: "skills_list result\n- **count:** 3" }), "done", t, "en");
+ expect(call.result).toBe("count: 3");
+ });
+
+ it("tells a tool id from a file", () => {
+ expect(isIdentifier("write_file")).toBe(true);
+ expect(isIdentifier("qa_note.txt")).toBe(false);
+ expect(isIdentifier("src/app.ts")).toBe(false);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.ts b/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.ts
index 34884ce7cc..7aa9c51168 100644
--- a/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.ts
+++ b/dodaios/ui/web/frontend/src/components/agentchat/traceEntries.ts
@@ -24,6 +24,7 @@
import { fill } from "@/i18n";
import { MCP_TOOLS_SERVER_NAMES } from "@/lib/branding";
import { cliVendor } from "@/lib/cliVendors";
+import { stripInlineMarks } from "@/lib/plainMarks";
import { resolveToolBrand } from "@/lib/toolBrand";
import { describeToolStep } from "@/lib/toolStepLabel";
import { isCredentialTool, isQuestionTool, type ReasoningBlock, type TextBlock, type ToolBlock, type TurnBlock, type TurnStatus } from "./reduce";
@@ -127,8 +128,14 @@ function oneLine(text: string, max: number): string {
}
function inputRecord(block: ToolBlock): Record<string, unknown> {
- return block.input && typeof block.input === "object" && !Array.isArray(block.input)
+ const record = block.input && typeof block.input === "object" && !Array.isArray(block.input)
? block.input as Record<string, unknown> : {};
+ // A runtime's permission request nests the tool's own arguments
+ // ({ tool: "write_file", arguments: { path } }): those are what it acts on.
+ const nested = record.arguments;
+ return nested && typeof nested === "object" && !Array.isArray(nested)
+ ? { ...(nested as Record<string, unknown>), ...record }
+ : record;
}
function firstString(record: Record<string, unknown>, keys: string[]): string {
@@ -145,6 +152,22 @@ export function shortPath(path: string): string {
return parts.length > 3 ? `…/${parts.slice(-3).join("/")}` : path;
}
+/** A bare tool identifier ("write_file", "tool_search"), not a file or a sentence. */
+export function isIdentifier(text: string): boolean {
+ return /^[a-z][a-z0-9]*(?:[_-][a-z0-9]+)+$/i.test(text.trim());
+}
+
+/**
+ * What a call's output says, without a runtime's own receipt words: a first
+ * line that only names the tool ("tool_search result", "✅ patch completed")
+ * and a bare "done" or "failed" stand-in for no output at all.
+ */
+export function outputGist(output: string): string {
+ const text = output.trim();
+ if (/^(?:done|failed)$/i.test(text)) return "";
+ return text.replace(/^(?:✅\s*)?[\w.:-]+ (?:result|completed)\s*(?:\r?\n|$)/i, "").trim();
+}
+
/** Plumbing calls draw nothing: loading a tool's schema, polling a question card. */
export function isPlumbing(block: ToolBlock): boolean {
if (isQuestionTool(block.name) && !block.question) return true;
@@ -238,7 +261,7 @@ const GIST_KEYS = ["summary", "message", "result", "status", "title", "answer",
/** A terse result: a count, the tool's own message, or its first line. */
function terseResult(block: ToolBlock, t: Translate, lang: string): string {
- const text = readableOutput(block).trim();
+ const text = outputGist(readableOutput(block));
if (!text) return "";
if (text.startsWith("{") || text.startsWith("[")) {
let parsed: unknown;
@@ -265,7 +288,9 @@ function terseResult(block: ToolBlock, t: Translate, lang: string): string {
const gist = new RegExp(`["'](?:${GIST_KEYS.join("|")})["']\\s*:\\s*["']([^"']{2,})["']`).exec(top);
return gist ? oneLine(gist[1], 120) : "";
}
- return oneLine(text.split(/\r?\n/).find((line) => line.trim()) ?? "", 120);
+ // A runtime's receipt is Markdown ("- **count:** 3"): its words, not its marks.
+ const first = text.split(/\r?\n/).find((line) => line.trim()) ?? "";
+ return oneLine(stripInlineMarks(first.replace(/^\s*(?:[-*+]|#+)\s+/, "")), 120);
}
function diffSize(block: ToolBlock): { added: number; removed: number } {
@@ -427,8 +452,10 @@ export function callOf(block: ToolBlock, turn: TurnStatus, t: Translate, lang: s
return { ...base, kind: "search", text, bucket: "search" };
}
if (action === "edit" || action === "write") {
- const path = shortPath(firstString(record, ACTION_KEYS[action]) || description.detail);
- return { ...base, ...diffSize(block), kind: action, text: tr(t, `call.${action}`, { target: path }), bucket: action };
+ // A runtime that names only its tool ("write_file") never makes that the file.
+ const named = firstString(record, ACTION_KEYS[action]) || (isIdentifier(description.detail) ? "" : description.detail);
+ const text = named ? tr(t, `call.${action}`, { target: shortPath(named) }) : capitalize(tr(t, `act.${action}_one`));
+ return { ...base, ...diffSize(block), kind: action, text, bucket: action };
}
const family = description.family;
const result = status === "done" ? terseResult(block, t, lang) : "";
diff --git a/dodaios/ui/web/frontend/src/components/agentchat/turnFailure.test.tsx b/dodaios/ui/web/frontend/src/components/agentchat/turnFailure.test.tsx
new file mode 100644
index 0000000000..bc4101a096
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/components/agentchat/turnFailure.test.tsx
@@ -0,0 +1,77 @@
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { retryOf } from "@/components/society/chat/AgentChatPanel";
+import { MessengerTurn } from "./MessengerTurn";
+import { EMPTY_TIMELINE, reduceEvents } from "./reduce";
+import type { TextBlock, TimelineItem, TurnItem } from "./reduce";
+
+afterEach(cleanup);
+
+const REASON = "The ChatGPT subscription could not answer this turn.";
+
+function turn(status: TurnItem["status"], error: string | null, blocks: TurnItem["blocks"] = []): TurnItem {
+ return {
+ type: "turn", id: "t1", provider: "p", model: "", effort: "", runner: "api", status, blocks,
+ startedMs: 1, durationMs: 10, usage: null, liveUsage: null, costUsd: null, error,
+ };
+}
+
+const user = (text: string, id = "u1"): TimelineItem => ({ type: "user", id, text, tsMs: 1 }) as TimelineItem;
+const answer: TextBlock = { kind: "text", id: "a", text: "Here it is." };
+
+function draw(item: TurnItem, onRetry?: () => void) {
+ return render(<MessengerTurn turn={item} avatar={<span />} color="#7ab6ef" onDecide={() => undefined} onRetry={onRetry} />);
+}
+
+describe("a failed turn", () => {
+ it("says why in an error box with a Retry that sends the message again", () => {
+ let retried = 0;
+ draw(turn("error", REASON), () => { retried += 1; });
+ expect(screen.getByTestId("turn-failure-reason").textContent).toBe(REASON);
+ expect(screen.queryByText("Finished without an answer")).toBeNull();
+ fireEvent.click(screen.getByTestId("turn-retry"));
+ expect(retried).toBe(1);
+ });
+
+ it("is a failure when a runtime ended silent with an error on record", () => {
+ draw(turn("done", REASON));
+ expect(screen.getByTestId("turn-failure-reason").textContent).toBe(REASON);
+ expect(screen.queryByTestId("turn-retry")).toBeNull();
+ });
+
+ it("says the runtime gave no reason rather than nothing", () => {
+ draw(turn("error", null));
+ expect(screen.getByTestId("turn-failure").textContent).toContain("The agent's runtime reported no reason.");
+ });
+
+ it("keeps a quiet line for a turn that simply did not answer", () => {
+ draw(turn("done", null));
+ expect(screen.queryByTestId("turn-failure")).toBeNull();
+ });
+
+ it("keeps the reason of an error event when the end of the turn names none", () => {
+ const state = reduceEvents(EMPTY_TIMELINE, [
+ { seq: 1, ts_ms: 1, kind: "turn_started", payload: { turn_id: "t1", provider: "p", model: "" } },
+ { seq: 2, ts_ms: 2, kind: "error", payload: { turn_id: "t1", message: REASON } },
+ { seq: 3, ts_ms: 3, kind: "turn_finished", payload: { turn_id: "t1", status: "done", duration_ms: 2 } },
+ ] as never);
+ const finished = state.items.find((item) => item.type === "turn") as TurnItem;
+ expect(finished.error).toBe(REASON);
+ });
+});
+
+describe("retryOf", () => {
+ it("offers the latest failed turn the message that started it", () => {
+ const sent: string[] = [];
+ const retry = retryOf([user("Write qa_note.txt"), turn("error", REASON)], (text) => sent.push(text));
+ expect(retry?.turnId).toBe("t1");
+ retry?.run();
+ expect(sent).toEqual(["Write qa_note.txt"]);
+ });
+
+ it("offers nothing once the latest turn answered or a new message is in", () => {
+ const send = () => undefined;
+ expect(retryOf([user("hi"), turn("done", null, [answer])], send)).toBeNull();
+ expect(retryOf([user("hi"), turn("error", REASON), user("again", "u2")], send)).toBeNull();
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/agentic/sessionTitle.ts b/dodaios/ui/web/frontend/src/components/agentic/sessionTitle.ts
index 9beb4b9d83..4e1c23c132 100644
--- a/dodaios/ui/web/frontend/src/components/agentic/sessionTitle.ts
+++ b/dodaios/ui/web/frontend/src/components/agentic/sessionTitle.ts
@@ -1,4 +1,5 @@
import type { WorkspacePaneRow } from "@/lib/agenticIdeApi";
+import { stripInlineMarks } from "@/lib/plainMarks";
/**
* What a session is called in a list of them: what it is ABOUT, not which
@@ -57,9 +58,7 @@ const SECTION_LABELS = new Set([
/** A line without its heading marks and emphasis, whitespace collapsed. */
function bare(row: string): string {
- return row
- .replace(/^\s*#{1,6}\s*/, "")
- .replace(/[*_`]{1,3}/g, "")
+ return stripInlineMarks(row.replace(/^\s*#{1,6}\s*/, ""))
.replace(/\s+/g, " ")
.trim();
}
diff --git a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
index e82d3bbace..e3e01a23a6 100644
--- a/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/chat/AgentChatPanel.tsx
@@ -320,7 +320,8 @@ function SpecialistChat({ agent, roster, composerExtras }: AgentChatPanelProps)
data-session-ready={sessionReady ? "true" : "false"}
>
<AgentConversationsBar agentId={agent.agentId} agentName={agent.name} displayName={displayName} />
- <Transcript key={`${sessionId ?? agent.agentId}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide} />
+ <Transcript key={`${sessionId ?? agent.agentId}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide}
+ onRetry={sessionReady && !busy ? (text) => void send(text) : undefined} />
{sessionReady && socketState !== "open" && socketState !== "idle" ? (
<p role="status" className="px-4 pb-1 text-xs text-muted-foreground">
{t(socketState === "closed" ? "society.chat.reconnecting" : "society.chat.connecting")}
@@ -451,7 +452,8 @@ function JarvisChat({ agent, roster }: AgentChatPanelProps) {
<div className="flex h-full min-h-0 flex-col bg-background" data-testid="society-chat" data-mode="chat">
{header}
<AgentConversationsBar agentId={agent.agentId} agentName={displayName(agent.agentId, agent.name)} displayName={displayName} />
- <Transcript key={`${activeSessionId ?? ""}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide} />
+ <Transcript key={`${activeSessionId ?? ""}:${view.boundaryId}`} items={view.items} agent={agent} roster={roster} onDecide={decide}
+ onRetry={busy ? undefined : (text) => void send(text)} />
{activeSessionId && socketState !== "open" && socketState !== "idle" ? (
<p role="status" className="px-4 pb-1 text-xs text-muted-foreground">
{t(socketState === "closed" ? "society.chat.reconnecting" : "society.chat.connecting")}
@@ -696,11 +698,14 @@ export function Transcript({
agent,
roster,
onDecide,
+ onRetry,
}: {
items: TimelineItem[];
agent: SocietyAgent;
roster: SocietyAgent[];
onDecide: (approvalId: string, decision: ApprovalDecision) => Promise<void>;
+ /** Sends a message of the person's again (a failed turn's "Retry"). */
+ onRetry?: (text: string) => void;
}) {
const t = useT();
const sessionId = useAgentChat((state) => state.activeSessionId);
@@ -801,6 +806,7 @@ export function Transcript({
}
const displayName = societyDisplayName(agent, assistantName);
+ const retry = onRetry ? retryOf(items, onRetry) : null;
return (
<div ref={setFrame} className="relative flex min-h-0 flex-1">
<div className="relative flex min-h-0 min-w-0 flex-1 flex-col">
@@ -820,7 +826,8 @@ export function Transcript({
<UserBubble item={item} agentId={agent.agentId} sessionId={sessionId ?? agent.chatSessionId ?? undefined} tint={tint} />
) : item.type === "turn" ? (
<TurnBubble item={item} agent={agent} memory={memoryByTurn.get(item.id)} onDecide={onDecide}
- nameOf={nameOf} peerFace={peerFace} workOpen={inspecting === item.id} onShowWork={setInspecting} />
+ nameOf={nameOf} peerFace={peerFace} workOpen={inspecting === item.id} onShowWork={setInspecting}
+ onRetry={retry?.turnId === item.id ? retry.run : undefined} />
) : item.type === "notice" ? (
item.kind === "proposal" ? (
<ProposalCard item={item} />
@@ -1126,6 +1133,34 @@ export function UserBubble({ item, agentId, sessionId, tint }: { item: UserItem;
);
}
+/**
+ * The "Retry" of the transcript: only its latest turn, only when that turn
+ * failed, and it sends the message of the person's that started it again.
+ */
+export function retryOf(items: readonly TimelineItem[], send: (text: string) => void): { turnId: string; run: () => void } | null {
+ let turn: TurnItem | null = null;
+ for (let i = items.length - 1; i >= 0; i -= 1) {
+ const item = items[i];
+ if (!turn) {
+ if (item.type === "turn") {
+ const silent = !item.blocks.some((block) => block.kind === "text" && block.text.trim());
+ if (item.status !== "error" && !(item.status === "done" && silent && item.error)) return null;
+ turn = item;
+ } else if (item.type === "user" && item.origin !== "control") {
+ return null;
+ }
+ continue;
+ }
+ if (item.type === "user" && !item.origin && item.text.trim() && !assignmentOf(item.text) && !item.teamEvent) {
+ const text = item.text;
+ const turnId = turn.id;
+ return { turnId, run: () => send(text) };
+ }
+ if (item.type === "turn") return null;
+ }
+ return null;
+}
+
function TurnBubble({
item,
agent,
@@ -1135,6 +1170,7 @@ function TurnBubble({
peerFace,
workOpen,
onShowWork,
+ onRetry,
}: {
item: TurnItem;
agent: SocietyAgent;
@@ -1145,6 +1181,7 @@ function TurnBubble({
workOpen?: boolean;
/** Opens the work inspector on a turn (by its id). */
onShowWork?: (turnId: string) => void;
+ onRetry?: () => void;
}) {
const t = useT();
const [openId, setOpenId] = useState<string | null>(null);
@@ -1164,7 +1201,7 @@ function TurnBubble({
// the swatch's own "working" dots would only repeat it.
return <>
<MessengerTurn turn={item} avatar={face} color={agentColor(agent)} onDecide={onDecide} memoryLinks={memoryLinks}
- nameOf={nameOf} peerFace={peerFace} onShowWork={showWork} workOpen={workOpen} />
+ nameOf={nameOf} peerFace={peerFace} onShowWork={showWork} workOpen={workOpen} onRetry={onRetry} />
{opened && <MemoryNoticeViewer item={opened} onClose={() => setOpenId(null)} />}
</>;
}
diff --git a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx
index f5330680bc..05f325c29e 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/create/CreateAgentDialog.test.tsx
@@ -82,16 +82,27 @@ afterEach(() => {
});
describe("CreateAgentDialog", () => {
- test("uses the access preference saved by the other model pickers", async () => {
+ test("a remembered access billed per use never beats the plan; a pick here is saved", async () => {
localStorage.setItem(MODEL_ACCESS_KEY, JSON.stringify({ claude: "api" }));
runtimes.value = { ...READY, access: { "claude-api": ["api", "subscription"] } };
menu.options = [CLAUDE];
mount();
act(() => { useCreateAgentDialog.getState().request().catch(() => undefined); });
- const api = await screen.findByRole("radio", { name: "society.create.kind_api" });
- await waitFor(() => expect(api.getAttribute("aria-checked")).toBe("true"));
- fireEvent.click(screen.getByRole("radio", { name: "society.create.kind_subscription" }));
- expect(JSON.parse(localStorage.getItem(MODEL_ACCESS_KEY)!)).toEqual({ claude: "subscription" });
+ const plan = await screen.findByRole("radio", { name: "society.create.kind_subscription" });
+ await waitFor(() => expect(plan.getAttribute("aria-checked")).toBe("true"));
+ fireEvent.click(screen.getByRole("radio", { name: "society.create.kind_api" }));
+ expect(JSON.parse(localStorage.getItem(MODEL_ACCESS_KEY)!)).toEqual({ claude: "api" });
+ await waitFor(() => expect(screen.getByRole("radio", { name: "society.create.kind_api" }).getAttribute("aria-checked")).toBe("true"));
+ });
+
+ test("uses a remembered access that is not billed per use", async () => {
+ localStorage.setItem(MODEL_ACCESS_KEY, JSON.stringify({ claude: "subscription" }));
+ runtimes.value = { ...READY, access: { "claude-api": ["api", "subscription"] } };
+ menu.options = [CLAUDE];
+ mount();
+ act(() => { useCreateAgentDialog.getState().request().catch(() => undefined); });
+ const plan = await screen.findByRole("radio", { name: "society.create.kind_subscription" });
+ await waitFor(() => expect(plan.getAttribute("aria-checked")).toBe("true"));
});
test("creates a named Hermes agent with a provider and a companion", async () => {
const agent = { agentId: "agent-1", name: "Scout" };
@@ -119,6 +130,8 @@ describe("CreateAgentDialog", () => {
expect(screen.getByTestId("create-agent-model")).toBeTruthy();
expect(screen.getByRole("radio", { name: "society.create.kind_local" }).getAttribute("aria-checked")).toBe("true");
expect(screen.queryByTestId("create-agent-access-cost")).toBeNull();
+ // Creation waits until the runtimes said which ways of paying work.
+ await waitFor(() => expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(false));
fireEvent.click(screen.getByTestId("create-agent-submit"));
await waitFor(() => expect(createAgent).toHaveBeenCalled());
expect(createAgent.mock.calls[0][0]).toMatchObject({ runtime: "jarvis", provider: "ollama", model: "qwen3:8b" });
@@ -211,12 +224,22 @@ describe("CreateAgentDialog", () => {
expect(await screen.findByText("society.runtime.provider_unsupported")).toBeTruthy();
});
+ test("creation waits while the runtimes are still read, so no seat billed per use slips through", async () => {
+ runtimes.value = new Promise(() => undefined);
+ menu.options = [CLAUDE, OPENAI];
+ mount();
+ act(() => { useCreateAgentDialog.getState().request().catch(() => undefined); });
+ await screen.findByTestId("create-agent-provider");
+ expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(true);
+ });
+
test("a Jarvis agent with nothing connected still starts on the chat's seat", async () => {
menu.options = [];
createAgent.mockResolvedValue({ agentId: "agent-5" });
mount();
act(() => { useCreateAgentDialog.getState().request().catch(() => undefined); });
await screen.findByText("society.create_agent.no_provider_jarvis");
+ await waitFor(() => expect((screen.getByTestId("create-agent-submit") as HTMLButtonElement).disabled).toBe(false));
fireEvent.click(screen.getByTestId("create-agent-submit"));
await waitFor(() => expect(createAgent).toHaveBeenCalled());
expect(createAgent.mock.calls[0][0]).toMatchObject({ runtime: "jarvis", provider: undefined });
diff --git a/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsx b/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsx
index c489cc2a16..6783f23288 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsx
+++ b/dodaios/ui/web/frontend/src/components/society/create/SeatFields.tsx
@@ -21,7 +21,7 @@ import { modelSeats, runtimeSeats } from "../chat/modelChoices";
import { useModelMenuData } from "../chat/useModelMenuData";
import { accountChoice, accountHint } from "./brainPicker";
import { AccessChoice } from "./AccessChoice";
-import { accessModels, billedPerUse, defaultModel, pickableOption, providerChoices, type AccessBlocked, type AccessOption } from "./seatChoice";
+import { accessModels, billedPerUse, defaultModel, pickableOption, providerChoices, type AccessBlocked, type AccessOption, type ProviderChoice } from "./seatChoice";
/** A model list this long gets a search field. */
const SEARCH_FROM = 12;
@@ -46,6 +46,9 @@ export function useCreateSeat() {
const [executionEnvironment, setExecutionEnvironment] = useState<"local" | "sandbox">("local");
const [providerId, setProviderId] = useState("");
const [access, rememberAccess] = useModelAccess();
+ // The access picked in THIS dialog. A remembered one (from the chat's model
+ // picker) never moves a fresh agent onto a seat billed per use.
+ const [pickedAccess, setPickedAccess] = useState<Record<string, string>>({});
const [model, setModel] = useState("");
const [account, setAccount] = useState("");
const [accountProvider, setAccountProvider] = useState("");
@@ -75,7 +78,7 @@ export function useCreateSeat() {
const chosen = choices.find((choice) => choice.id === providerId)
?? choices.find((choice) => pickableOption(choice)) ?? choices[0] ?? null;
// A refused access is listed with its reason but never picked.
- const option: AccessOption | null = pickableOption(chosen, chosen ? access[chosen.id] : undefined);
+ const option: AccessOption | null = chosen ? startingOption(chosen, pickedAccess[chosen.id], access[chosen.id]) : null;
const models = accessModels(option);
const accounts = accountChoice(option?.seat ?? null);
const modelValue = models.some((entry) => entry.id === model) ? model : defaultModel(option);
@@ -90,10 +93,15 @@ export function useCreateSeat() {
// first turn waits for the setup (agent_runtimes.manager). A Jarvis agent
// with nothing connected yet still starts: it takes the last chat seat.
const needsProvider = external && !option;
+ // The seats are still being read: creating now would leave the provider to
+ // the backend's last chat seat, which may be billed per use.
+ // The runtimes answer which ways of paying work (a plan or only a key), so
+ // the default waits for them on every runtime.
+ const seatsPending = (!option && menu.loading) || runtimes.isLoading;
const accountBlocked = Boolean(account && accountProvider === option?.seat.provider.id
&& (accountValue !== account || menu.loading || menu.failed));
const selectedModelsFailed = Boolean(option && menu.modelErrors?.includes(option.seat.provider.id));
- const ready = !needsProvider && !accountBlocked && !selectedModelsFailed && (!option || models.length > 0);
+ const ready = !needsProvider && !seatsPending && !accountBlocked && !selectedModelsFailed && (!option || models.length > 0);
const pick: SeatPick = {
runtime,
@@ -106,11 +114,17 @@ export function useCreateSeat() {
return {
runtimes, menu, choices, chosen, option, models, accounts, modelValue, accountValue,
- runtime, external, executionEnvironment, ready, accountBlocked, selectedModelsFailed, pick, modelLabel,
+ runtime, external, executionEnvironment, ready, seatsPending, accountBlocked, selectedModelsFailed, pick, modelLabel,
defaultModelLabel,
setRuntime: (next: AgentRuntime) => { setRuntimeState(next); setAccount(""); },
setProvider: (next: string) => { setProviderId(next); setAccount(""); },
- setAccess: (kind: string) => { if (chosen) rememberAccess(chosen.id, kind as ModelAccess); setAccount(""); },
+ setAccess: (kind: string) => {
+ if (chosen) {
+ setPickedAccess((known) => ({ ...known, [chosen.id]: kind }));
+ rememberAccess(chosen.id, kind as ModelAccess);
+ }
+ setAccount("");
+ },
setAccount: (next: string) => { if (option) setAccountProvider(option.seat.provider.id); setAccount(next); setModel(""); },
setModel,
setExecutionEnvironment,
@@ -119,6 +133,20 @@ export function useCreateSeat() {
export type CreateSeat = ReturnType<typeof useCreateSeat>;
+/**
+ * The access a fresh agent starts on: the one picked in this dialog, else a
+ * remembered one unless it bills per use while a plan or a local model is
+ * there, else the cheapest (`pickableOption`). Blank, starter and template
+ * agents all start here, so each gets the same cost-safe default.
+ */
+export function startingOption(choice: ProviderChoice, picked?: string, remembered?: string): AccessOption | null {
+ if (picked) return pickableOption(choice, picked);
+ const cheapest = pickableOption(choice);
+ const recalled = remembered ? pickableOption(choice, remembered) : null;
+ if (recalled && cheapest && billedPerUse(recalled) && !billedPerUse(cheapest)) return cheapest;
+ return recalled ?? cheapest;
+}
+
/** The sentence that explains how the picked access pays. */
function accessHint(t: (key: string) => string, option: AccessOption): string {
return t(option.extraUsage ? "society.create_agent.access_extra_usage" : `society.create_agent.access_hint_${option.kind}`);
@@ -241,7 +269,8 @@ export function SeatSummary({ seat, disabled }: { seat: CreateSeat; disabled: bo
option ? seat.modelLabel : null,
option ? t(`society.create.kind_${option.kind}`) : null,
].filter(Boolean);
- const blocked = !seat.ready;
+ // Still reading the seats: not a missing choice, just a moment.
+ const blocked = !seat.ready && !seat.seatsPending;
return (
<section className="rounded-[10px] border border-border bg-sheen/[0.02]" data-testid="create-agent-seat-summary">
<button
@@ -259,7 +288,7 @@ export function SeatSummary({ seat, disabled }: { seat: CreateSeat; disabled: bo
<span className="min-w-0 flex-1">
<span className="block text-xs text-muted-foreground">{t("agent_create.seat.runs_on")}</span>
<span className={cn("block truncate text-sm", blocked ? "text-warning" : "text-foreground")}>
- {blocked ? t("agent_create.seat.needs_choice") : parts.join(" · ")}
+ {seat.seatsPending ? t("society.create.catalog_loading") : blocked ? t("agent_create.seat.needs_choice") : parts.join(" · ")}
</span>
</span>
<span className="flex shrink-0 items-center gap-1 text-xs text-muted-foreground">
diff --git a/dodaios/ui/web/frontend/src/components/society/create/seatChoice.test.ts b/dodaios/ui/web/frontend/src/components/society/create/seatChoice.test.ts
index ef86e66fbc..79d0c80b75 100644
--- a/dodaios/ui/web/frontend/src/components/society/create/seatChoice.test.ts
+++ b/dodaios/ui/web/frontend/src/components/society/create/seatChoice.test.ts
@@ -199,3 +199,30 @@ describe("defaultModel", () => {
expect(defaultModel(null)).toBe("");
});
});
+
+
+describe("startingOption", () => {
+ // On Hermes / OpenClaw Claude's login is billed as extra usage; the API key per use.
+ const [claudeChoice] = providerChoices([claude], { "claude-api": ["subscription", "api"] }, true);
+
+ it("never starts on a remembered seat billed per use", async () => {
+ const { startingOption } = await import("./SeatFields");
+ const withLocal = { ...claudeChoice, options: [...claudeChoice.options, { kind: "local" as const, seat: ollama, accountId: "", extraUsage: false }] };
+ expect(startingOption(withLocal, undefined, "subscription")?.kind).toBe("local");
+ expect(startingOption(withLocal, undefined, "local")?.kind).toBe("local");
+ });
+
+ it("keeps what the person picked in this dialog, and warns there", async () => {
+ const { startingOption } = await import("./SeatFields");
+ const picked = startingOption(claudeChoice, "subscription");
+ expect(picked?.extraUsage).toBe(true);
+ expect(billedPerUse(picked)).toBe(true);
+ });
+
+ it("starts on the plan when the remembered access is the plan", async () => {
+ const { startingOption } = await import("./SeatFields");
+ const [jarvisClaude] = providerChoices([claude], { "claude-api": ["subscription", "api"] }, false);
+ expect(startingOption(jarvisClaude, undefined, "subscription")?.kind).toBe("subscription");
+ expect(startingOption(jarvisClaude, undefined, "subscription")?.extraUsage).toBe(false);
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.test.ts b/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.test.ts
index 8b4c0409ef..78d7fa87fc 100644
--- a/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.test.ts
+++ b/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.test.ts
@@ -61,7 +61,7 @@ describe("rosterStatus", () => {
describe("previewText", () => {
it("drops ask blocks, routing markers, code and markdown", () => {
const raw = "Here is the **plan**.\n[to jarvis]\n```ts\nconst x = 1;\n```\nSee [the doc](https://example.test).\n```jarvis-ask\n{\"questions\": []}\n```";
- expect(previewText(raw)).toBe("Here is the plan . See the doc.");
+ expect(previewText(raw)).toBe("Here is the plan. See the doc.");
});
it("keeps a line that merely starts with a link", () => {
diff --git a/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.ts b/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.ts
index f4af7d9abd..d6c64871ea 100644
--- a/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.ts
+++ b/dodaios/ui/web/frontend/src/components/society/roster/rosterPreview.ts
@@ -14,6 +14,7 @@
* in the chat header, so the preview keeps saying what was last said.
*/
import { hideAskBlocks } from "@/components/agentchat/askFence";
+import { stripInlineMarks } from "@/lib/plainMarks";
import type { SocietyAgent } from "../data";
@@ -94,7 +95,9 @@ export function previewText(raw: string | null | undefined): string {
.replace(MARKER_LINE, " ")
.replace(/!\[[^\]]*\]\([^)]*\)/g, " ")
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
- .replace(/[*_`>#~|]+/g, " ")
+ .replace(/^\s*(?:[>#]+|[-*+]\s)\s*/gm, " ")
+ .replace(/[^\n]+/g, (line) => stripInlineMarks(line))
+ .replace(/\|/g, " ")
.replace(/\s+/g, " ")
.trim();
return text.length > MAX_PREVIEW ? `${text.slice(0, MAX_PREVIEW - 1)}…` : text;
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/de.json b/dodaios/ui/web/frontend/src/i18n/locales/de.json
index 9c9613e23e..2be2fcf555 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/de.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/de.json
@@ -7645,6 +7645,9 @@
"failed_after": "Nach {duration} fehlgeschlagen",
"no_answer": "Ohne Antwort beendet",
"no_answer_after": "Nach {duration} ohne Antwort beendet",
+ "failed_title": "Dieser Durchgang ist fehlgeschlagen",
+ "failed_no_reason": "Die Laufzeit des Agenten hat keinen Grund genannt.",
+ "retry": "Erneut versuchen",
"thinking": "Denkt nach",
"copy_answer": "Antwort kopieren",
"waiting_answer": "Wartet unten auf deine Antwort",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/en.json b/dodaios/ui/web/frontend/src/i18n/locales/en.json
index fb2333f981..096d821187 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/en.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/en.json
@@ -7645,6 +7645,9 @@
"failed_after": "Failed after {duration}",
"no_answer": "Finished without an answer",
"no_answer_after": "Finished without an answer after {duration}",
+ "failed_title": "This turn failed",
+ "failed_no_reason": "The agent's runtime reported no reason.",
+ "retry": "Retry",
"thinking": "Thinking",
"copy_answer": "Copy answer",
"waiting_answer": "Waiting for your answer below",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/es.json b/dodaios/ui/web/frontend/src/i18n/locales/es.json
index b35cad3d27..8b05e329cc 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/es.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/es.json
@@ -7645,6 +7645,9 @@
"failed_after": "Falló tras {duration}",
"no_answer": "Terminó sin respuesta",
"no_answer_after": "Terminó sin respuesta tras {duration}",
+ "failed_title": "Este turno ha fallado",
+ "failed_no_reason": "El entorno del agente no indicó ningún motivo.",
+ "retry": "Reintentar",
"thinking": "Pensando",
"copy_answer": "Copiar respuesta",
"waiting_answer": "Esperando tu respuesta abajo",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/pt.json b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
index 741b36468b..f5a868a047 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/pt.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/pt.json
@@ -7645,6 +7645,9 @@
"failed_after": "Falhou após {duration}",
"no_answer": "Terminou sem resposta",
"no_answer_after": "Terminou sem resposta após {duration}",
+ "failed_title": "Esta vez falhou",
+ "failed_no_reason": "O ambiente do agente não indicou nenhum motivo.",
+ "retry": "Tentar de novo",
"thinking": "A pensar",
"copy_answer": "Copiar resposta",
"waiting_answer": "À espera da tua resposta abaixo",
diff --git a/dodaios/ui/web/frontend/src/i18n/locales/zh.json b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
index 79839d0df4..55f7959c1b 100644
--- a/dodaios/ui/web/frontend/src/i18n/locales/zh.json
+++ b/dodaios/ui/web/frontend/src/i18n/locales/zh.json
@@ -7645,6 +7645,9 @@
"failed_after": "{duration} 后失败",
"no_answer": "已结束,没有回答",
"no_answer_after": "{duration} 后结束,没有回答",
+ "failed_title": "本轮失败",
+ "failed_no_reason": "智能体的运行时没有给出原因。",
+ "retry": "重试",
"thinking": "思考中",
"copy_answer": "复制回答",
"waiting_answer": "等待你在下方回答",
diff --git a/dodaios/ui/web/frontend/src/lib/plainMarks.test.ts b/dodaios/ui/web/frontend/src/lib/plainMarks.test.ts
new file mode 100644
index 0000000000..563e15f257
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/lib/plainMarks.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from "vitest";
+import { previewOf } from "@/components/agentchat/inspector/inspectorRows";
+import { previewText } from "@/components/society/roster/rosterPreview";
+import { stripInlineMarks } from "./plainMarks";
+
+describe("stripInlineMarks", () => {
+ it("keeps the underscores of file names and identifiers", () => {
+ expect(stripInlineMarks("Wrote qa_note.txt")).toBe("Wrote qa_note.txt");
+ expect(stripInlineMarks("call tool_search then my_long_name")).toBe("call tool_search then my_long_name");
+ expect(stripInlineMarks("2*3*4")).toBe("2*3*4");
+ expect(stripInlineMarks("Edited __init__.py, then ran __main__")).toBe("Edited __init__.py, then ran __main__");
+ });
+
+ it("takes off emphasis, code ticks and strike marks", () => {
+ expect(stripInlineMarks("**Done** with `qa_note.txt`, _really_ ~~not~~ *yet*")).toBe("Done with qa_note.txt, really not yet");
+ expect(stripInlineMarks("__very bold__ and **qa_note.txt**")).toBe("very bold and qa_note.txt");
+ });
+});
+
+describe("plain previews keep file names whole", () => {
+ it("in the roster preview and the chat header", () => {
+ expect(previewText("I saved `qa_note.txt` in the **workspace**.")).toBe("I saved qa_note.txt in the workspace.");
+ expect(previewText("- wrote qa_note.txt\n> quoted")).toBe("wrote qa_note.txt quoted");
+ });
+
+ it("in the work trace rows", () => {
+ expect(previewOf("## Result\nCreated qa_note.txt")).toBe("Result");
+ expect(previewOf("Created *qa_note.txt*")).toBe("Created qa_note.txt");
+ });
+});
diff --git a/dodaios/ui/web/frontend/src/lib/plainMarks.ts b/dodaios/ui/web/frontend/src/lib/plainMarks.ts
new file mode 100644
index 0000000000..46ee0b8c02
--- /dev/null
+++ b/dodaios/ui/web/frontend/src/lib/plainMarks.ts
@@ -0,0 +1,36 @@
+/**
+ * Markdown emphasis taken off a line of text, and nothing else.
+ *
+ * Previews, titles and status lines show a message as one plain line. Their
+ * old filters dropped every `*`, `_` and backtick, which also took the
+ * underscores out of file names and identifiers ("qa_note.txt" became
+ * "qanote.txt" or "qa note.txt"). Here a marker goes only when it opens and
+ * closes emphasis: at a word's edge, never inside a word, and a dunder name
+ * ("__init__.py", "__main__") keeps its underscores.
+ */
+
+/** `text` without code ticks, bold, italics and strike marks; underscores inside words stay. */
+export function stripInlineMarks(text: string): string {
+ return text
+ .replace(/`+/g, "")
+ .replace(/(^|[^\w*])(\*\*|__)(?=\S)(.+?)(?<=\S)\2(?![\w*])/g,
+ (whole: string, lead: string, mark: string, inner: string) =>
+ (mark === "__" && /^\w+$/.test(inner) ? whole : lead + inner))
+ .replace(/(^|[^\w*])\*(?=[^\s*])([^*\n]*?)(?<=[^\s*])\*(?![\w*])/g, "$1$2")
+ .replace(/(^|[^\w])_(?=[^\s_])([^_\n]*?)(?<=[^\s_])_(?!\w)/g, "$1$2")
+ .replace(/~~(?=\S)(.+?)(?<=\S)~~/g, "$1");
+}
+
+/**
+ * A Markdown message as one plain line: code fences, heading, quote and list
+ * marks and inline emphasis gone, whitespace collapsed; file names stay whole.
+ */
+export function flattenMarks(text: string): string {
+ return text
+ .replace(/```[\s\S]*?```/g, " ")
+ .split(/\r?\n/)
+ .map((line) => stripInlineMarks(line.replace(/^\s*(?:[#>]+|[-*+]\s)\s*/, "")).replace(/\|/g, " "))
+ .join(" ")
+ .replace(/\s+/g, " ")
+ .trim();
+}
diff --git a/tests/fakes/fake_acp_agent.py b/tests/fakes/fake_acp_agent.py
index cb9a0b6404..e362378427 100644
--- a/tests/fakes/fake_acp_agent.py
+++ b/tests/fakes/fake_acp_agent.py
@@ -144,6 +144,10 @@ def _prompt(rid: Any, session_id: str, text: str, store: dict[str, list[str]]) -
connection.close()
_send({"jsonrpc": "2.0", "id": rid, "result": {"stopReason": "end_turn"}})
return
+ if "SILENT" in text:
+ # A runtime that swallowed a failed model call and ended with no answer.
+ _send({"jsonrpc": "2.0", "id": rid, "result": {"stopReason": "end_turn"}})
+ return
if "FAIL" in text:
_send({"jsonrpc": "2.0", "id": rid, "error": {"code": -32000, "message": "model down"}})
return
diff --git a/tests/unit/agent_chat/test_approval_card.py b/tests/unit/agent_chat/test_approval_card.py
index 708d6cbdb5..f34a169dbe 100644
--- a/tests/unit/agent_chat/test_approval_card.py
+++ b/tests/unit/agent_chat/test_approval_card.py
@@ -108,7 +108,9 @@ def test_every_source_maps_onto_the_same_card_fields(name, args, kind, app, caut
assert card["source"].get("app", "") == app or kind not in ("connector",)
assert card["caution"] == caution
if kind in ("terminal", "files"):
- assert card["where"] == "C:/work"
+ # The chat's own folder reads as its name; the full path stays in where_full.
+ assert card["where"] == "work"
+ assert card["where_full"] == "C:/work"
if kind == "plan":
assert card["detail"] == "" and card["rule"] is None
@@ -683,8 +685,9 @@ def test_display_paths_shortens_the_workspace_and_the_home_folder():
text = f"Edit {WIN_CWD}\\src\\a.py and C:/Users/ada/Downloads/x.txt"
assert display_paths(text, WIN_CWD, WIN_HOME) == "Edit src\\a.py and ~/Downloads/x.txt"
- # The workspace itself reads from the home folder; no path, no change.
- assert display_paths(WIN_CWD, WIN_CWD, WIN_HOME) == "~\\Desktop\\proj"
+ # The workspace itself reads as its own name, not the long path to it.
+ assert display_paths(WIN_CWD, WIN_CWD, WIN_HOME) == "proj"
+ assert display_paths(f"In {WIN_CWD}", WIN_CWD, WIN_HOME) == "In proj"
assert display_paths("echo hi", WIN_CWD, WIN_HOME) == "echo hi"
assert display_paths("/home/bob/code/x.py", "/home/bob/code", "/home/bob") == "x.py"
assert display_paths("cat /home/bob/notes.md", "", "/home/bob") == "cat ~/notes.md"
@@ -911,3 +914,21 @@ def test_the_home_folder_is_never_offered_as_only_this_folder(tmp_path: Path):
)
assert deeper and deeper[0]["value"] == str(tmp_path / "home" / "proj")
assert deeper[0]["label"].replace("\\", "/") == "~/proj"
+
+
+def test_a_runtime_file_request_reads_inside_the_agents_workspace():
+ """Hermes asks with the tool's own arguments nested; the card stays short."""
+ workspace = "C:/Users/Ada/data/society/agent-1/workspace"
+ args = {"tool": "write_file", "arguments": {"path": "qa_note.txt", "content": "hello"}}
+ card = describe_call("edit", args, "Approve edit: qa_note.txt", cwd=workspace)
+ assert card["where"] == "workspace"
+ assert card["where_full"] == workspace
+ assert card["brief"] == "Approve edit: qa_note.txt"
+ narrow = narrow_options_for(args, workspace)
+ assert narrow and narrow[0]["label"] == "workspace"
+
+
+def narrow_options_for(args, cwd):
+ from dodaios.agent_chat.approval_card import narrow_options
+
+ return narrow_options("files", args, cwd, "C:/Users/Ada")
diff --git a/tests/unit/agent_runtimes/test_acp_failure_replies.py b/tests/unit/agent_runtimes/test_acp_failure_replies.py
index 14ea77baf4..60fd3e9bbb 100644
--- a/tests/unit/agent_runtimes/test_acp_failure_replies.py
+++ b/tests/unit/agent_runtimes/test_acp_failure_replies.py
@@ -105,3 +105,32 @@ def test_a_failure_notice_split_over_chunks_never_leaks_into_the_answer():
assert turn.status == "error"
assert turn.error == "The Gateway disconnected."
assert _texts(io) == []
+
+
+def _tool_start(update: dict) -> list[dict]:
+ turn = AcpTurn(turn_id="t", cwd=".", prompt_text="hi")
+ io = _IO()
+ frame = {
+ "jsonrpc": "2.0",
+ "method": "session/update",
+ "params": {"sessionId": "s", "update": {"sessionUpdate": "tool_call", **update}},
+ }
+ asyncio.run(turn.on_message(frame, io))
+ return [e["payload"] for e in io.events if e.get("kind") == "tool_call"]
+
+
+def test_a_file_tool_without_input_names_its_file_from_the_location():
+ calls = _tool_start({
+ "toolCallId": "tc", "title": "write_file: qa_note.txt", "kind": "edit",
+ "locations": [{"path": "C:/work/qa_note.txt"}],
+ })
+ assert calls[0]["name"] == "write_file"
+ assert calls[0]["input"] == {"path": "C:/work/qa_note.txt"}
+
+
+def test_a_tool_with_its_own_input_keeps_it():
+ calls = _tool_start({
+ "toolCallId": "tc", "title": "tool_search", "kind": "other",
+ "rawInput": {"query": "gmail"}, "locations": [{"path": "C:/x"}],
+ })
+ assert calls[0]["input"] == {"query": "gmail"}
diff --git a/tests/unit/agent_runtimes/test_acp_runner.py b/tests/unit/agent_runtimes/test_acp_runner.py
index 7ae1bcbdaa..b99fe9914f 100644
--- a/tests/unit/agent_runtimes/test_acp_runner.py
+++ b/tests/unit/agent_runtimes/test_acp_runner.py
@@ -55,6 +55,7 @@ def _turn(
argv: list[str] | None = None,
released: list[int] | None = None,
cancel_on_delta: bool = False,
+ provider_failure: Any = None,
) -> tuple[str | None, list[dict[str, Any]], list[tuple[str, str]], list[str | None]]:
resumes: list[str | None] = []
@@ -79,6 +80,7 @@ def _turn(
report_session=report_session,
),
after_turn=(lambda: released.append(1)) if released is not None else None,
+ provider_failure=provider_failure,
)
monkeypatch.setattr(runner_acp, "plan_runtime_turn", fake_plan)
@@ -563,3 +565,35 @@ def test_a_detached_child_of_the_runtime_is_reaped_with_the_turn(monkeypatch, tm
while running() and time.monotonic() < deadline:
time.sleep(0.1)
assert not running()
+
+
+def test_a_swallowed_gateway_failure_fails_the_silent_turn_with_its_reason(monkeypatch, tmp_path):
+ """A runtime that kept a recoverable failure and ended silent: the turn failed, and says why."""
+ from concurrent.futures import Future
+
+ from dodaios.agent_runtimes import gateway
+
+ signal: Future[str] = Future()
+ reason = "The ChatGPT subscription could not answer this turn."
+ gateway._LAST_FAILURES[signal] = reason
+ events = _turn(monkeypatch, tmp_path, "SILENT", provider_failure=signal)[1]
+ finished = _finished(events)
+ assert (finished["status"], finished["error"]) == ("error", reason)
+
+
+def test_a_silent_turn_without_a_gateway_failure_stays_done(monkeypatch, tmp_path):
+ from concurrent.futures import Future
+
+ events = _turn(monkeypatch, tmp_path, "SILENT", provider_failure=Future())[1]
+ assert _finished(events)["status"] == "done"
+
+
+def test_an_answer_after_a_retried_failure_stays_done(monkeypatch, tmp_path):
+ from concurrent.futures import Future
+
+ from dodaios.agent_runtimes import gateway
+
+ signal: Future[str] = Future()
+ gateway._LAST_FAILURES[signal] = "ChatGPT rejected this request (HTTP 400)."
+ events = _turn(monkeypatch, tmp_path, "hello", provider_failure=signal)[1]
+ assert _finished(events)["status"] == "done"
diff --git a/tests/unit/agent_runtimes/test_runtime_gateway.py b/tests/unit/agent_runtimes/test_runtime_gateway.py
index f4bfe00dd5..35f2826c83 100644
--- a/tests/unit/agent_runtimes/test_runtime_gateway.py
+++ b/tests/unit/agent_runtimes/test_runtime_gateway.py
@@ -969,3 +969,33 @@ def test_a_warm_up_covers_only_its_own_agent(fake, brain, guarded) -> None:
assert len(brain["requests"]) == 1 # agent-2's own turn, on its own route
with pytest.raises(gateway.GatewayError), gateway.warming("jrg_unknown"):
pass
+
+
+def test_a_recoverable_failure_is_kept_for_the_turn_that_saw_it() -> None:
+ from concurrent.futures import Future
+
+ signal: Future[str] = Future()
+ grant = gateway.Grant("agent-1", "openai-codex")
+ soft = gateway.GatewayError("The ChatGPT subscription could not answer this turn.", status=502,
+ code="subscription_unavailable")
+ gateway._report_failure(grant, "m", soft, signal)
+ assert not signal.done()
+ assert gateway.last_failure(signal) == str(soft)
+ assert gateway.last_failure(None) == ""
+ assert gateway.last_failure(Future()) == ""
+
+
+def test_a_later_answer_clears_the_kept_failure() -> None:
+ # A retried request that answers means the runtime recovered: a turn that
+ # then ends quietly (a file written, nothing said) is not a failure.
+ from concurrent.futures import Future
+
+ signal: Future[str] = Future()
+ grant = gateway.Grant("agent-1", "openai-codex")
+ soft = gateway.GatewayError("The provider is overloaded.", status=503,
+ code="provider_overloaded")
+ gateway._report_failure(grant, "m", soft, signal)
+ assert gateway.last_failure(signal)
+ gateway._answered(signal)
+ assert gateway.last_failure(signal) == ""
+ gateway._answered(None)