Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(agents,chat): graph hover fix + callback-edge removal (A8) + trigger provenance (A9) (#965)
Call Whiteacb423a13ab5
diff --git a/docs/plans/agents-run-graph-contract.md b/docs/plans/agents-run-graph-contract.mdindex bdc7277ee..65c632190 100644--- a/docs/plans/agents-run-graph-contract.md+++ b/docs/plans/agents-run-graph-contract.md@@ -39,6 +39,16 @@ Amendments (orchestrator-approved):(and refetches/re-adds on `'foreground'`); absent `visibility` field ⇒no-op (defensive pre-M1). M1 does not touch `ui/**` for this; the gap isrecorded in #957's inventory as assigned to #956.+- **A8 (2026-07-23, owner regression feedback)**: callback edges are **no+ longer rendered on the canvas** (visual clutter). The payload keeps emitting+ them unchanged; the node detail panel ("REPORTS TO · callback status")+ becomes the only callback surface. Client-side rendering change only.+- **A9 (2026-07-23, owner regression feedback)**: chat trigger-message+ provenance: agent-callback ("自动触发") messages render the SOURCE session's+ title prefix and click through to `/chat/<source_session_id>`; task/watch+ trigger messages click through to the corresponding Harness filter view+ (reuse the backgroundActivity deep-link helpers). Read-side message+ enrichment only if the payload lacks source ids.- **A7 (2026-07-23, PR #956 review)**: graph endpoint path renamed`/api/agents/graph` → **`/api/agents-graph`**. Rationale: `/api/agents/…`is the agent-resource namespace and agent names are user-creatable slugs —diff --git a/storage/messages_service.py b/storage/messages_service.pyindex c7110b572..262f41490 100644--- a/storage/messages_service.py+++ b/storage/messages_service.py@@ -21,7 +21,7 @@ from sqlalchemy import and_, delete, func, or_, select, updatefrom sqlalchemy.engine import Connectionfrom storage.db import escape_sql_like-from storage.models import agent_sessions, messages, scope_settings, scopes+from storage.models import agent_runs, agent_sessions, messages, scope_settings, scopesfrom vibe.message_identity import HARNESS_TYPE, INPUT_TURN_AUTHOR_TYPES@@ -75,6 +75,95 @@ def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:}+_AGENT_RUN_NATIVE_PREFIX = "agent_run:"+++def _attach_agent_run_provenance(+ conn: Connection, payloads: list[dict[str, Any]]+) -> list[dict[str, Any]]:+ """Read-side provenance for agent-callback ("自动触发") chat messages (A9a).++ A harness ``agent_run`` prompt is stored as ``native_message_id =+ "agent_run:<execution_id>"`` with no source-session pointer (the write path+ records none). Resolve it read-side: message → its ``agent_runs`` row+ (``id == <execution_id>``) → the run's ``source_actor`` (the session that+ triggered the callback) → that session's title, so the Chat chip can name the+ source and deep-link to ``/chat/<source_session_id>``. No schema/write-path+ change. Batched: at most two extra queries per page, only when such a message+ is present.+ """+ exec_by_msg: dict[str, str] = {}+ for payload in payloads:+ native_id = payload.get("native_message_id")+ if (+ payload.get("source") == "harness"+ and isinstance(native_id, str)+ and native_id.startswith(_AGENT_RUN_NATIVE_PREFIX)+ ):+ exec_by_msg[payload["id"]] = native_id[len(_AGENT_RUN_NATIVE_PREFIX):]+ if not exec_by_msg:+ return payloads++ # execution_id == agent_runs.id. The source SESSION differs by run kind:+ # - source_kind='agent' → source_actor IS the caller session id.+ # - source_kind='callback'→ source_actor is the parent RUN id (or a decorated+ # "<run>:terminal:<status>"), NOT a session; the real source is the parent+ # (delegated) run's session_id.+ runs = {+ row["id"]: row+ for row in conn.execute(+ select(+ agent_runs.c.id, agent_runs.c.source_kind,+ agent_runs.c.source_actor, agent_runs.c.parent_run_id,+ ).where(agent_runs.c.id.in_(set(exec_by_msg.values())))+ ).mappings()+ }+ callback_parents = {+ run["parent_run_id"] for run in runs.values()+ if run["source_kind"] == "callback" and run["parent_run_id"]+ }+ parent_session: dict[str, str] = {}+ if callback_parents:+ for row in conn.execute(+ select(agent_runs.c.id, agent_runs.c.session_id).where(+ agent_runs.c.id.in_(callback_parents)+ )+ ).mappings():+ sess = (row["session_id"] or "").strip()+ if sess:+ parent_session[row["id"]] = sess++ source_by_exec: dict[str, str] = {}+ for exec_id, run in runs.items():+ if run["source_kind"] == "callback":+ source_id = parent_session.get(run["parent_run_id"])+ else:+ source_id = (run["source_actor"] or "").strip() or None+ # A session id never contains ':' (decorated run/terminal forms do); guard+ # so an unexpected source_actor shape can't become a bogus /chat target.+ if source_id and ":" not in source_id:+ source_by_exec[exec_id] = source_id+ if not source_by_exec:+ return payloads++ meta_by_session: dict[str, dict[str, Optional[str]]] = {}+ for row in conn.execute(+ select(agent_sessions.c.id, agent_sessions.c.title, agent_sessions.c.agent_name).where(+ agent_sessions.c.id.in_(set(source_by_exec.values()))+ )+ ).mappings():+ meta_by_session[row["id"]] = {"title": row["title"], "agent_name": row["agent_name"]}++ for payload in payloads:+ source_id = source_by_exec.get(exec_by_msg.get(payload["id"], ""))+ if source_id:+ meta = meta_by_session.get(source_id) or {}+ payload["source_session_id"] = source_id+ payload["source_session_title"] = meta.get("title")+ payload["source_session_agent_name"] = meta.get("agent_name")+ return payloads++_WS_RE = re.compile(r"\s+")# Snippet window radii (chars) either side of the matched term. Tuned for a@@ -472,7 +561,7 @@ def list_session_messages(has_newer = len(newer) > effective_limitnewer = newer[:effective_limit]- merged = older + anchor_rows + newer+ merged = _attach_agent_run_provenance(conn, older + anchor_rows + newer)return {"messages": merged,"next_after_id": newer[-1]["id"] if has_newer and newer else None,@@ -481,7 +570,9 @@ def list_session_messages(if tail:# Newest ``limit`` rows, then flip back to chronological for the caller.query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit + 1)- rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]+ rows = _attach_agent_run_provenance(+ conn, [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]+ )has_older = len(rows) > effective_limitrows = rows[:effective_limit]rows.reverse()@@ -502,7 +593,9 @@ def list_session_messages())query = query.order_by(messages.c.created_at.desc(), messages.c.id.desc()).limit(effective_limit + 1)- rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]+ rows = _attach_agent_run_provenance(+ conn, [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]+ )has_older = len(rows) > effective_limitrows = rows[:effective_limit]rows.reverse()@@ -523,7 +616,9 @@ def list_session_messages())query = query.order_by(messages.c.created_at.asc(), messages.c.id.asc()).limit(effective_limit + 1)- rows = [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]+ rows = _attach_agent_run_provenance(+ conn, [_row_to_payload(dict(row)) for row in conn.execute(query).mappings().all()]+ )# Probe one extra row against the clamped page size: a full page alone does# not prove there is another page, but the extra row does.has_newer = len(rows) > effective_limitdiff --git a/tests/test_messages_service.py b/tests/test_messages_service.pyindex a80178758..7261cc6ae 100644--- a/tests/test_messages_service.py+++ b/tests/test_messages_service.py@@ -16,8 +16,9 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from storage import messages_servicefrom storage.db import create_sqlite_enginefrom storage.importer import ensure_sqlite_state-from storage.models import agent_sessions, messages, scopes+from storage.models import agent_runs, agent_sessions, messages, scopesfrom storage.settings_service import upsert_scope+from vibe.message_identity import HARNESS_TYPE@pytest.fixture()@@ -51,6 +52,87 @@ def _seed_session(conn, scope_id: str, session_id: str) -> None:)+def _insert_harness_msg(conn, scope_id, session_id, *, author_name, native_message_id,+ author_id=None, msg_id, created_at):+ conn.execute(+ messages.insert().values(+ id=msg_id, scope_id=scope_id, session_id=session_id, platform="avibe",+ author="harness", type=HARNESS_TYPE, source="harness",+ author_name=author_name, author_id=author_id,+ native_message_id=native_message_id,+ content_text="prompt", content_json="{}", metadata_json="{}",+ created_at=created_at, updated_at=created_at,+ )+ )+++def _seed_titled_agent_session(conn, scope_id, session_id, *, title, agent_name):+ now = messages_service._utc_now_iso()+ conn.execute(+ agent_sessions.insert().values(+ id=session_id, scope_id=scope_id, agent_name=agent_name,+ agent_backend="claude", agent_variant="default",+ session_anchor="anchor_" + session_id, native_session_id="",+ status="active", title=title, metadata_json="{}",+ created_at=now, updated_at=now, last_active_at=now,+ )+ )+++def _insert_agent_run(conn, run_id, *, session_id, source_kind, source_actor=None, parent_run_id=None):+ now = messages_service._utc_now_iso()+ conn.execute(+ agent_runs.insert().values(+ id=run_id, run_type="agent_run", status="succeeded", cancel_requested=0,+ source_kind=source_kind, source_actor=source_actor, parent_run_id=parent_run_id,+ session_id=session_id, created_at=now, updated_at=now, metadata_json="{}",+ )+ )+++def test_agent_run_message_provenance_enrichment(isolated_state):+ # A9a read-side enrichment resolves the SOURCE session per run kind:+ # - source_kind='agent' → source_actor is the caller session.+ # - source_kind='callback' → source_actor is a run id; the source is the+ # PARENT (delegated) run's session.+ # A non-agent_run harness message (task trigger) is left untouched.+ engine = create_sqlite_engine()+ with engine.begin() as conn:+ scope_id = _seed_scope(conn)+ _seed_session(conn, scope_id, "ses_target")+ _seed_titled_agent_session(conn, scope_id, "ses_caller", title="Caller 总控", agent_name="pm")+ _seed_titled_agent_session(conn, scope_id, "ses_delegated", title="Delegated 审计", agent_name="evm")+ # Agent spawn: source_actor is the caller session.+ _insert_agent_run(conn, "execAgent", session_id="ses_target",+ source_kind="agent", source_actor="ses_caller")+ # Callback: source_actor is a decorated run id; parent run ran in ses_delegated.+ _insert_agent_run(conn, "parentRun", session_id="ses_delegated", source_kind="agent",+ source_actor="ses_caller")+ _insert_agent_run(conn, "execCb", session_id="ses_target", source_kind="callback",+ source_actor="parentRun:terminal:succeeded", parent_run_id="parentRun")+ _insert_harness_msg(conn, scope_id, "ses_target", author_name="agent_run",+ native_message_id="agent_run:execAgent", msg_id="msg_agent",+ created_at="2026-05-30T10:00:00Z")+ _insert_harness_msg(conn, scope_id, "ses_target", author_name="agent_run",+ native_message_id="agent_run:execCb", msg_id="msg_cb",+ created_at="2026-05-30T10:00:01Z")+ _insert_harness_msg(conn, scope_id, "ses_target", author_name="scheduled",+ author_id="def_1", native_message_id="scheduled:def_1:execB",+ msg_id="msg_task", created_at="2026-05-30T10:00:02Z")++ with engine.connect() as conn:+ result = messages_service.list_session_messages(conn, session_id="ses_target")+ by_id = {m["id"]: m for m in result["messages"]}+ assert by_id["msg_agent"]["source_session_id"] == "ses_caller"+ assert by_id["msg_agent"]["source_session_title"] == "Caller 总控"+ assert by_id["msg_agent"]["source_session_agent_name"] == "pm"+ # Callback resolves through the parent run's session, not the run-id source_actor.+ assert by_id["msg_cb"]["source_session_id"] == "ses_delegated"+ assert by_id["msg_cb"]["source_session_title"] == "Delegated 审计"+ # A non-agent_run harness message gets no source fields.+ assert "source_session_id" not in by_id["msg_task"]++def test_mark_session_read_ties_break_on_id(isolated_state):"""When ``until_message_id`` points at a message whose ``created_at``is shared by newer messages (second precision), only rows at-or-beforediff --git a/ui/src/components/workbench/AgentGraphCanvas.tsx b/ui/src/components/workbench/AgentGraphCanvas.tsxindex e0b179e19..1b93892d9 100644--- a/ui/src/components/workbench/AgentGraphCanvas.tsx+++ b/ui/src/components/workbench/AgentGraphCanvas.tsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useRef, useState } from 'react';+import { createContext, useContext, useEffect, useMemo, useRef, useState } from 'react';import {Background,BackgroundVariant,@@ -40,29 +40,35 @@ import { AgentGraphTriggerChip } from './AgentGraphTriggerChip';type SessionNodeData = {node: AgentGraphNode;- selected: boolean;- faded: boolean;onSelect: (id: string) => void;onOpenChat: (id: string) => void;};type TriggerNodeData = {trigger: AgentGraphTriggerNode;- faded: boolean;onSelect: (definitionId: string) => void;};+// Hover-highlight + selection live in context, NOT in each node's `data`, so a+// mouse-enter never rebuilds the RF node array. Rebuilding it re-measures every+// node, shifts it under the cursor, and fires a spurious mouseleave→mouseenter+// oscillation (the reported flicker). Custom nodes read this and toggle their+// own classes; the node array changes only on real data changes.+type CanvasInteraction = { highlighted: Set<string> | null; selectedId: string | null };+const InteractionContext = createContext<CanvasInteraction>({ highlighted: null, selectedId: null });+// Hidden handles anchor the edges; the card/chip fills the sized RF node box.const HANDLE_CLASS = '!h-1 !w-1 !min-w-0 !border-0 !bg-transparent';-const SessionRFNode: React.FC<NodeProps> = ({ data }) => {+const SessionRFNode: React.FC<NodeProps> = ({ id, data }) => {const d = data as unknown as SessionNodeData;+ const { highlighted, selectedId } = useContext(InteractionContext);return (<><Handle type="target" position={Position.Left} className={HANDLE_CLASS} isConnectable={false} /><AgentGraphNodeCardnode={d.node}- selected={d.selected}- faded={d.faded}+ selected={id === selectedId}+ faded={!!highlighted && !highlighted.has(id)}onClick={() => d.onSelect(d.node.session_id)}// Double-click opens the chat only for openable sessions (internal// private-agent-run nodes have none).@@ -73,11 +79,16 @@ const SessionRFNode: React.FC<NodeProps> = ({ data }) => {);};-const TriggerRFNode: React.FC<NodeProps> = ({ data }) => {+const TriggerRFNode: React.FC<NodeProps> = ({ id, data }) => {const d = data as unknown as TriggerNodeData;+ const { highlighted } = useContext(InteractionContext);return (<>- <AgentGraphTriggerChip trigger={d.trigger} faded={d.faded} onClick={() => d.onSelect(d.trigger.definition_id)} />+ <AgentGraphTriggerChip+ trigger={d.trigger}+ faded={!!highlighted && !highlighted.has(id)}+ onClick={() => d.onSelect(d.trigger.definition_id)}+ /><Handle type="source" position={Position.Right} className={HANDLE_CLASS} isConnectable={false} /></>);@@ -88,9 +99,11 @@ const NODE_TYPES = { session: SessionRFNode, trigger: TriggerRFNode };// ── edge styling ─────────────────────────────────────────────────────────────+// Callback edges are no longer drawn on the canvas (contract A8 — the detail+// panel's "REPORTS TO · callback status" is the only callback surface), so the+// canvas renders spawn + trigger only.function edgeVars(kind: AgentGraphEdge['kind']): { color: string; dashed: boolean } {if (kind === 'spawn') return { color: 'var(--mint)', dashed: false };- if (kind === 'callback') return { color: 'var(--cyan)', dashed: true };return { color: 'var(--violet)', dashed: true }; // trigger}@@ -164,14 +177,26 @@ const Flow: React.FC<AgentGraphCanvasProps> = ({const reactFlow = useReactFlow();const fittedRef = useRef(false);- const adjacency = useMemo(() => buildAdjacency(edges), [edges]);+ // Only spawn + trigger edges are drawn (contract A8 drops callback edges from+ // the canvas). Derive the rendered set once and drive both the hover+ // adjacency and the edge list from it, so hover chains follow what's visible.+ const renderedEdges = useMemo(() => edges.filter((e) => e.kind !== 'callback'), [edges]);++ const adjacency = useMemo(() => buildAdjacency(renderedEdges), [renderedEdges]);const highlighted = useMemo(() => (hoveredId ? reachable(hoveredId, adjacency) : null),[hoveredId, adjacency],);+ // Interaction state (hover highlight + selection) handed to custom nodes via+ // context so it never rebuilds the node array (see InteractionContext).+ const interaction = useMemo<CanvasInteraction>(+ () => ({ highlighted, selectedId }),+ [highlighted, selectedId],+ );- // Layout only ranks along the call tree (spawn + trigger). Callback edges are- // drawn but excluded from ranking so they don't fight the left→right layers.+ // Layout ranks along the call tree (spawn + trigger). Memoized on the rendered+ // edges + node identity only — NOT on hover/selection — so pointer moves never+ // trigger a dagre pass.const layout = useMemo(() => {const layoutNodes = [...nodes.map((n) => ({ id: n.session_id, width: SESSION_NODE_WIDTH, height: SESSION_NODE_HEIGHT })),@@ -181,13 +206,14 @@ const Flow: React.FC<AgentGraphCanvasProps> = ({height: TRIGGER_NODE_HEIGHT,})),];- const layoutEdges = edges- .filter((e) => e.kind === 'spawn' || e.kind === 'trigger')- .map((e) => ({ source: e.from, target: e.to }));+ const layoutEdges = renderedEdges.map((e) => ({ source: e.from, target: e.to }));return layoutLR(layoutNodes, layoutEdges);- }, [nodes, triggerNodes, edges]);+ }, [nodes, triggerNodes, renderedEdges]);- // Compose the React Flow node list (sessions + trigger chips).+ // Compose the React Flow node list (sessions + trigger chips). Deliberately+ // independent of hover/selection — those are read from context by the custom+ // nodes — so this array (and thus node measurement) is stable across pointer+ // moves and only rebuilds when the underlying data/layout changes.const computedNodes = useMemo<Node[]>(() => {const out: Node[] = [];for (const node of nodes) {@@ -200,8 +226,6 @@ const Flow: React.FC<AgentGraphCanvasProps> = ({style: { width: SESSION_NODE_WIDTH, height: SESSION_NODE_HEIGHT },data: {node,- selected: node.session_id === selectedId,- faded: !!highlighted && !highlighted.has(node.session_id),onSelect: onSelectNode,onOpenChat,} as unknown as Record<string, unknown>,@@ -218,16 +242,15 @@ const Flow: React.FC<AgentGraphCanvasProps> = ({style: { width: TRIGGER_NODE_WIDTH, height: TRIGGER_NODE_HEIGHT },data: {trigger,- faded: !!highlighted && !highlighted.has(id),onSelect: onSelectTrigger,} as unknown as Record<string, unknown>,});}return out;- }, [nodes, triggerNodes, layout, selectedId, highlighted, onSelectNode, onSelectTrigger, onOpenChat]);+ }, [nodes, triggerNodes, layout, onSelectNode, onSelectTrigger, onOpenChat]);const computedEdges = useMemo<Edge[]>(() => {- return edges.map((edge) => {+ return renderedEdges.map((edge) => {const { color, dashed } = edgeVars(edge.kind);const dim = !!highlighted && !(highlighted.has(edge.from) && highlighted.has(edge.to));return {@@ -244,7 +267,7 @@ const Flow: React.FC<AgentGraphCanvasProps> = ({markerEnd: { type: MarkerType.ArrowClosed, color, width: 13, height: 13 },} satisfies Edge;});- }, [edges, highlighted]);+ }, [renderedEdges, highlighted]);useEffect(() => setRfNodes(computedNodes), [computedNodes, setRfNodes]);useEffect(() => setRfEdges(computedEdges), [computedEdges, setRfEdges]);@@ -266,32 +289,34 @@ const Flow: React.FC<AgentGraphCanvasProps> = ({return (<div className="h-[600px] max-h-[72vh] w-full overflow-hidden rounded-2xl border border-border-strong bg-surface-3/60">- <ReactFlow- nodes={rfNodes}- edges={rfEdges}- onNodesChange={onNodesChange}- onEdgesChange={onEdgesChange}- nodeTypes={NODE_TYPES}- colorMode={resolvedTheme}- nodesDraggable={false}- nodesConnectable={false}- elementsSelectable- // Read-only graph: keep click selection but disable Delete/Backspace, or- // the change handlers would drop a selected node/edge until next refresh.- deleteKeyCode={null}- proOptions={{ hideAttribution: true }}- minZoom={0.2}- maxZoom={1.75}- onNodeMouseEnter={(_e, node) => setHoveredId(node.id)}- onNodeMouseLeave={() => setHoveredId(null)}- onPaneClick={() => setHoveredId(null)}- >- <Background variant={BackgroundVariant.Dots} gap={22} size={1} className="opacity-40" />- <Controls showInteractive={false} position="bottom-right" />- <Panel position="bottom-left">- <Legend t={t} />- </Panel>- </ReactFlow>+ <InteractionContext.Provider value={interaction}>+ <ReactFlow+ nodes={rfNodes}+ edges={rfEdges}+ onNodesChange={onNodesChange}+ onEdgesChange={onEdgesChange}+ nodeTypes={NODE_TYPES}+ colorMode={resolvedTheme}+ nodesDraggable={false}+ nodesConnectable={false}+ elementsSelectable+ // Read-only graph: keep click selection but disable Delete/Backspace, or+ // the change handlers would drop a selected node/edge until next refresh.+ deleteKeyCode={null}+ proOptions={{ hideAttribution: true }}+ minZoom={0.2}+ maxZoom={1.75}+ onNodeMouseEnter={(_e, node) => setHoveredId(node.id)}+ onNodeMouseLeave={() => setHoveredId(null)}+ onPaneClick={() => setHoveredId(null)}+ >+ <Background variant={BackgroundVariant.Dots} gap={22} size={1} className="opacity-40" />+ <Controls showInteractive={false} position="bottom-right" />+ <Panel position="bottom-left">+ <Legend t={t} />+ </Panel>+ </ReactFlow>+ </InteractionContext.Provider></div>);};@@ -301,15 +326,14 @@ const Legend: React.FC<{ t: (k: string) => string }> = ({ t }) => (<LegendItem label={t('agents.graph.legend.spawn')}><span className="h-[2px] w-5" style={{ background: 'var(--mint)' }} /></LegendItem>- <LegendItem label={t('agents.graph.legend.callback')}>- <span className="h-0 w-5 border-t-2 border-dashed" style={{ borderColor: 'var(--cyan)' }} />- </LegendItem><LegendItem label={t('agents.graph.legend.trigger')}><span className="h-0 w-5 border-t-2 border-dashed" style={{ borderColor: 'var(--violet)' }} /></LegendItem><LegendItem label={t('agents.graph.legend.background')}><span className="text-muted">◎</span></LegendItem>+ {/* A8: callback edges are no longer drawn; the detail panel owns them. */}+ <span className="text-muted/70">{t('agents.graph.legend.callbackNote')}</span></div>);diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsxindex 6064a835d..9850b48e6 100644--- a/ui/src/components/workbench/ChatPage.tsx+++ b/ui/src/components/workbench/ChatPage.tsx@@ -1,7 +1,7 @@import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';-import { Activity, ArrowLeft, ArrowRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Info, Loader2, MessageSquare, Pencil, Presentation, Terminal, Undo2, UploadCloud, X } from 'lucide-react';+import { Activity, ArrowLeft, ArrowRight, ArrowUpRight, Bell, Bot, ChevronDown, ChevronRight, Clock, Eye, GitFork, Info, Loader2, MessageSquare, Pencil, Presentation, Terminal, Undo2, UploadCloud, X } from 'lucide-react';import type { LucideIcon } from 'lucide-react';import clsx from 'clsx';@@ -24,6 +24,7 @@ import {resolveActivityLabel,sortBackgroundActivities,} from '../../lib/backgroundActivity';+import { chatTriggerLink, isUnresolvedAgentCallback } from '../../lib/chatTrigger';import { useFileDrop } from '../../lib/useFileDrop';import { quoteText } from '../../lib/quoteText';import { mergeById, insertMessageOrdered } from '../../lib/transcriptOrder';@@ -1003,6 +1004,10 @@ export const ChatPage: React.FC = () => {return;}appendMessage(msg);+ // A9a: a live agent-callback prompt is published before its source+ // session is resolved, so pull the enriched REST row (mergeById fills+ // source_session_* in place) — the chip appears without a reload/refocus.+ if (isUnresolvedAgentCallback(msg)) void reconcile();// Agent Activity: a terminal reply settles the turn → mark the generation// settled and rebuild groups from storage (chip, rows, status, duration all// come from the endpoint, never the lossy live buffer).@@ -3074,6 +3079,7 @@ type MessageRowProps = {// useCallback), so the default shallow compare is correct here.const MessageRow = memo(function MessageRow({ message, session, messageFontSize, onQuickReply, highlighted }: MessageRowProps) {const { t } = useTranslation();+ const navigate = useNavigate();// Harness rows are collapsed by default; this tracks the per-row expand state.const [expanded, setExpanded] = useState(false);@@ -3092,6 +3098,9 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,// watch / webhook); collapsed by default so it doesn't dominate.const isHarness = !isNotify && !isAgent && !isSystem && message.source === 'harness';const isUser = !isNotify && !isAgent && !isSystem && !isHarness;+ // Trigger-message provenance click-through (contract A9a/A9b): agent-callback+ // rows link to the source session's chat; task/watch rows to the Harness view.+ const triggerLink = isHarness ? chatTriggerLink(message, t('chat.source.agentFallback')) : null;const messageFontStyle = { fontSize: `${normalizeChatMessageFontSize(messageFontSize)}px` };// User-uploaded attachments ride in ``content.attachments`` (agent-reply media@@ -3220,7 +3229,33 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,<div className="group/message flex max-w-[min(92%,860px)] flex-col items-start gap-1"><div className="flex items-center gap-2 px-0.5"><RoleAvatar tone="cyan"><Clock /></RoleAvatar>- <span className="text-[11px] font-medium text-cyan">{harnessLabel(message.author_name, t)}</span>+ {triggerLink?.kind === 'harness' ? (+ // A9b: task/watch label deep-links to the Harness filtered view.+ <button+ type="button"+ onClick={() => navigate(triggerLink.to)}+ className="inline-flex items-center gap-1 text-[11px] font-medium text-cyan hover:underline"+ >+ {harnessLabel(message.author_name, t)}+ <ArrowUpRight className="size-3 shrink-0" />+ </button>+ ) : (+ <span className="text-[11px] font-medium text-cyan">{harnessLabel(message.author_name, t)}</span>+ )}+ {triggerLink?.kind === 'source' && (+ // A9a: agent-callback shows the SOURCE session + links to its chat.+ <>+ <span className="text-[11px] text-muted">·</span>+ <button+ type="button"+ onClick={() => navigate(triggerLink.to)}+ className="inline-flex min-w-0 items-center gap-1 text-[11px] font-medium text-cyan hover:underline"+ >+ <span className="min-w-0 truncate">{triggerLink.label}</span>+ <ArrowUpRight className="size-3 shrink-0" />+ </button>+ </>+ )}</div><Buttontype="button"diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 2e8f30833..4e6184de7 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1000,6 +1000,13 @@ export type WorkbenchMessage = {source: 'user' | 'agent' | 'harness' | string | null;author_id: string | null;author_name: string | null;+ // Read-side provenance for an agent-callback ("自动触发") harness message (A9a):+ // the session that triggered the run, resolved from the run's source_actor.+ // Present only on agent_run harness messages; enables the source-session chip+ // + /chat/<source_session_id> deep-link.+ source_session_id?: string | null;+ source_session_title?: string | null;+ source_session_agent_name?: string | null;native_message_id: string | null;parent_native_message_id: string | null;text: string;diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 777da65a4..fefee934d 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -1959,9 +1959,9 @@},"legend": {"spawn": "Spawn",- "callback": "Callback","trigger": "Task / Watch",- "background": "Background"+ "background": "Background",+ "callbackNote": "Reports-to only in detail panel"},"status": {"active": "running",@@ -2388,7 +2388,8 @@"scheduled": "Scheduled task","watch": "Watch","webhook": "Webhook",- "harness": "Automated"+ "harness": "Automated",+ "agentFallback": "agent"},"picker": {"agent": "Agent",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex e84569f3a..49ab761aa 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -1959,9 +1959,9 @@},"legend": {"spawn": "启动",- "callback": "汇报 / callback","trigger": "Task / Watch 触发",- "background": "后台会话"+ "background": "后台会话",+ "callbackNote": "汇报关系只在详情面板"},"status": {"active": "运行中",@@ -2388,7 +2388,8 @@"scheduled": "定时任务","watch": "Watch 监听","webhook": "Webhook",- "harness": "自动触发"+ "harness": "自动触发",+ "agentFallback": "智能体"},"picker": {"agent": "Agent",diff --git a/ui/src/lib/chatTrigger.test.ts b/ui/src/lib/chatTrigger.test.tsnew file mode 100644index 000000000..283fc5bad--- /dev/null+++ b/ui/src/lib/chatTrigger.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from 'vitest';++import { chatTriggerLink, isUnresolvedAgentCallback } from './chatTrigger';++type Msg = Parameters<typeof chatTriggerLink>[0];+const msg = (over: Partial<Msg>): Msg => ({+ source: 'harness',+ author_name: null,+ author_id: null,+ session_id: 'ses_here',+ source_session_id: null,+ source_session_title: null,+ source_session_agent_name: null,+ ...over,+});+// Second arg is the localized "agent" fallback word; a fixed literal keeps the+// mapper translation-free and the test deterministic.+const link = (over: Partial<Msg>) => chatTriggerLink(msg(over), 'agent');++describe('chatTriggerLink', () => {+ it('returns null for non-harness messages', () => {+ expect(link({ source: 'user' })).toBeNull();+ expect(link({ source: 'agent' })).toBeNull();+ });++ it('A9a: agent-callback links to the source session chat, labelled by title prefix', () => {+ expect(link({ author_name: 'agent_run', source_session_id: 'ses_src_1234', source_session_title: 'Vaults 总控' })).toEqual({+ kind: 'source',+ to: '/chat/ses_src_1234',+ label: 'Vaults 总控',+ });+ });++ it('A9a: truncates a long source title to ~12 chars', () => {+ expect(link({ source_session_id: 'ses_x', source_session_title: '0123456789ABCDEF' })).toEqual({+ kind: 'source',+ to: '/chat/ses_x',+ label: '0123456789AB…',+ });+ });++ it('A9a: falls back to agent name + short id when the title is null', () => {+ expect(link({ source_session_id: 'ses_abcdef123456', source_session_title: null, source_session_agent_name: 'pm' })).toEqual({+ kind: 'source',+ to: '/chat/ses_abcdef123456',+ label: 'pm · 123456',+ });+ });++ it('A9a: uses the localized agent fallback when both title and agent name are null', () => {+ expect(link({ source_session_id: 'ses_abcdef123456' })?.label).toBe('agent · 123456');+ });++ it('A9b: watch trigger links to the Harness watches tab filtered to this session', () => {+ expect(link({ author_name: 'watch', author_id: 'def_w', session_id: 'ses_1' })).toEqual({+ kind: 'harness',+ to: '/harness?tab=watches&session=ses_1',+ });+ });++ it('A9b: scheduled + task_run + legacy task all link to the Harness tasks tab', () => {+ for (const author_name of ['scheduled', 'task_run', 'task']) {+ expect(link({ author_name, session_id: 'ses_1' })?.to).toBe('/harness?tab=tasks&session=ses_1');+ }+ });++ it('does not navigate for webhook or unknown harness kinds without a source', () => {+ expect(link({ author_name: 'webhook' })).toBeNull();+ expect(link({ author_name: 'agent_run', source_session_id: null })).toBeNull();+ });++ it('prefers the source link over the kind link when both could apply', () => {+ expect(link({ author_name: 'watch', source_session_id: 'ses_src' })?.kind).toBe('source');+ });+});++describe('isUnresolvedAgentCallback', () => {+ const m = (over: Partial<Parameters<typeof isUnresolvedAgentCallback>[0]>) =>+ isUnresolvedAgentCallback({ source: 'harness', native_message_id: 'agent_run:exec1', source_session_id: null, ...over });++ it('is true for a live agent_run harness message without a resolved source', () => {+ expect(m({})).toBe(true);+ });++ it('is false once the source session is resolved', () => {+ expect(m({ source_session_id: 'ses_src' })).toBe(false);+ });++ it('is false for non-agent_run harness messages and non-harness messages', () => {+ expect(m({ native_message_id: 'scheduled:def:exec' })).toBe(false);+ expect(m({ native_message_id: null })).toBe(false);+ expect(m({ source: 'agent' })).toBe(false);+ });+});diff --git a/ui/src/lib/chatTrigger.ts b/ui/src/lib/chatTrigger.tsnew file mode 100644index 000000000..93f272c70--- /dev/null+++ b/ui/src/lib/chatTrigger.ts@@ -0,0 +1,80 @@+// Provenance click-through for a harness trigger message in Chat (contract+// A9a/A9b). A pure mapper so the branching is unit-tested without the component.+//+// - A9a "自动触发" (agent callback): link to the SOURCE session's chat, labelled+// by its title prefix (fallback: source agent name + short session id).+// - A9b "定时任务" / "Watch 监听": link to the matching Harness tab filtered to+// this session, reusing the backgroundActivity deep-link helper.+// Other harness rows (webhook, or an agent callback whose source didn't resolve)+// stay non-navigating.+import type { WorkbenchMessage } from '../context/ApiContext';+import { harnessNavPath } from './backgroundActivity';++export type ChatTriggerLink =+ | { kind: 'source'; to: string; label: string }+ | { kind: 'harness'; to: string };++const AGENT_RUN_NATIVE_PREFIX = 'agent_run:';++// True for a live agent-callback ("自动触发") harness message that has NOT yet+// been enriched with its source session (A9a). The live ``message.new`` payload+// is published raw (before ``list_session_messages`` resolves the source), so+// ChatPage triggers a targeted reconcile on these to pull the enriched REST row+// (``mergeById`` then fills ``source_session_*`` in place) — otherwise the source+// chip would only appear after a manual reload/refocus.+export function isUnresolvedAgentCallback(+ message: Pick<WorkbenchMessage, 'source' | 'native_message_id' | 'source_session_id'>,+): boolean {+ return (+ message.source === 'harness' &&+ typeof message.native_message_id === 'string' &&+ message.native_message_id.startsWith(AGENT_RUN_NATIVE_PREFIX) &&+ message.source_session_id == null+ );+}++// author_name values that map to the Harness "tasks" tab (watch → "watches").+// Includes the legacy/queued-restore `task` trigger kind alongside scheduled/task_run.+const TASK_KINDS = new Set(['scheduled', 'task_run', 'task']);+const TITLE_PREFIX_MAX = 12;++function titlePrefix(title: string): string {+ const trimmed = title.trim();+ return trimmed.length > TITLE_PREFIX_MAX ? `${trimmed.slice(0, TITLE_PREFIX_MAX)}…` : trimmed;+}++type TriggerFields = Pick<+ WorkbenchMessage,+ | 'source'+ | 'author_name'+ | 'author_id'+ | 'session_id'+ | 'source_session_id'+ | 'source_session_title'+ | 'source_session_agent_name'+>;++// ``agentFallback`` is the localized word for "agent" (chat.source.agentFallback);+// passed in so this stays a pure, translation-free mapper.+export function chatTriggerLink(message: TriggerFields, agentFallback: string): ChatTriggerLink | null {+ if (message.source !== 'harness') return null;++ const sourceId = message.source_session_id;+ if (sourceId) {+ const title = message.source_session_title?.trim();+ const label = title+ ? titlePrefix(title)+ : `${message.source_session_agent_name?.trim() || agentFallback} · ${sourceId.slice(-6)}`;+ return { kind: 'source', to: `/chat/${encodeURIComponent(sourceId)}`, label };+ }++ const kind = message.author_name;+ if (kind === 'watch' || TASK_KINDS.has(kind ?? '')) {+ const itemKind = kind === 'watch' ? 'watch' : 'task';+ return {+ kind: 'harness',+ to: harnessNavPath({ id: `${itemKind}:${message.author_id ?? ''}`, item_kind: itemKind }, message.session_id),+ };+ }+ return null;+}diff --git a/ui/src/lib/transcriptOrder.test.ts b/ui/src/lib/transcriptOrder.test.tsindex 190c27b87..e813976f5 100644--- a/ui/src/lib/transcriptOrder.test.ts+++ b/ui/src/lib/transcriptOrder.test.ts@@ -49,6 +49,24 @@ describe('mergeById', () => {expect(mergeById([], [])).toEqual([]);expect(ids(mergeById([], [mk('a', t(1))]))).toEqual(['a']);});++ it('fills late-arriving source-session provenance onto an existing live row (A9a)', () => {+ const live = { id: 'm1', created_at: t(1), source_session_id: null } as unknown as WorkbenchMessage;+ const enriched = {+ id: 'm1', created_at: t(1),+ source_session_id: 'ses_src', source_session_title: 'Src', source_session_agent_name: 'pm',+ } as unknown as WorkbenchMessage;+ const [row] = mergeById([live], [enriched]);+ expect(row.source_session_id).toBe('ses_src');+ expect(row.source_session_title).toBe('Src');+ expect(row.source_session_agent_name).toBe('pm');+ });++ it('does not overwrite an already-resolved source-session id with a null reconcile', () => {+ const existing = { id: 'm1', created_at: t(1), source_session_id: 'ses_src' } as unknown as WorkbenchMessage;+ const incoming = { id: 'm1', created_at: t(1), source_session_id: null } as unknown as WorkbenchMessage;+ expect(mergeById([existing], [incoming])[0].source_session_id).toBe('ses_src');+ });});describe('insertMessageOrdered', () => {diff --git a/ui/src/lib/transcriptOrder.ts b/ui/src/lib/transcriptOrder.tsindex 8ba324f4f..903e08737 100644--- a/ui/src/lib/transcriptOrder.ts+++ b/ui/src/lib/transcriptOrder.ts@@ -27,8 +27,27 @@ export const mergeById = (existing: WorkbenchMessage[],incoming: WorkbenchMessage[],): WorkbenchMessage[] => {+ const incomingById = new Map(incoming.map((m) => [m.id, m]));+ // Fill late-arriving read-side provenance (A9a): the live ``message.new`` row is+ // published before ``list_session_messages`` resolves ``source_session_*``, so a+ // plain dedupe-by-id would drop the enriched REST reconcile and the+ // source-session chip would only appear after a full reload. Merge just those+ // fields onto an existing row that still lacks them; everything else is+ // untouched, and unseen incoming ids are appended as before.+ const patched = existing.map((m) => {+ const inc = incomingById.get(m.id);+ if (inc && m.source_session_id == null && inc.source_session_id != null) {+ return {+ ...m,+ source_session_id: inc.source_session_id,+ source_session_title: inc.source_session_title,+ source_session_agent_name: inc.source_session_agent_name,+ };+ }+ return m;+ });const seen = new Set(existing.map((m) => m.id));- const merged = [...existing, ...incoming.filter((m) => !seen.has(m.id))];+ const merged = [...patched, ...incoming.filter((m) => !seen.has(m.id))];merged.sort(byCreatedThenId);return merged;};