Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(workbench): run-graph node search with locate + filter reveal (#986)

Call White0a1fb514f6d5
diff --git a/docs/plans/agents-run-graph-contract.md b/docs/plans/agents-run-graph-contract.md
index 65c632190..1161c859b 100644
--- a/docs/plans/agents-run-graph-contract.md
+++ b/docs/plans/agents-run-graph-contract.md
@@ -49,6 +49,14 @@ Amendments (orchestrator-approved):
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.
+- **A10 (2026-07-23, owner feedback — graph blew up with every Harness
+ definition)**: `trigger_nodes` are **edge-derived**: emit a chip ONLY for
+ definitions that have ≥1 `trigger` edge in the returned payload (i.e. they
+ actually triggered a session within the window/filters). Enabled-but-idle
+ and disabled definitions with no in-window runs never appear. A disabled
+ definition that DID fire in-window keeps its chip (it explains lineage) —
+ client renders it dimmed with a disabled marker using the existing
+ `enabled` field.
- **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/ui/src/components/workbench/AgentGraphCanvas.tsx b/ui/src/components/workbench/AgentGraphCanvas.tsx
index 1b93892d9..a1c4f90d6 100644
--- a/ui/src/components/workbench/AgentGraphCanvas.tsx
+++ b/ui/src/components/workbench/AgentGraphCanvas.tsx
@@ -147,11 +147,19 @@ interface AgentGraphCanvasProps {
// Changes when the user changes a filter; a new value re-fits the viewport to
// the new layout. Unchanged across SSE/poll refreshes so they keep the view.
fitKey: string;
+ // A search "locate" request: pan+zoom to a node/chip and pulse it. `nonce`
+ // bumps per request so re-selecting the same target re-fires the animation.
+ locate?: { rfId: string; kind: 'node' | 'trigger'; nonce: number } | null;
onSelectNode: (sessionId: string) => void;
onSelectTrigger: (definitionId: string) => void;
onOpenChat: (sessionId: string) => void;
}
+// Zoom the locate animation settles on (readable, below maxZoom) and how long
+// the reused hover-highlight lingers as the "found it" pulse.
+const LOCATE_ZOOM = 1.15;
+const LOCATE_PULSE_MS = 1200;
+
export const AgentGraphCanvas: React.FC<AgentGraphCanvasProps> = (props) => (
// Provider lets the inner flow call fitView once nodes are measured.
<ReactFlowProvider>
@@ -165,6 +173,7 @@ const Flow: React.FC<AgentGraphCanvasProps> = ({
edges,
selectedId,
fitKey,
+ locate,
onSelectNode,
onSelectTrigger,
onOpenChat,
@@ -176,6 +185,20 @@ const Flow: React.FC<AgentGraphCanvasProps> = ({
const [rfEdges, setRfEdges, onEdgesChange] = useEdgesState<Edge>([]);
const reactFlow = useReactFlow();
const fittedRef = useRef(false);
+ // Guards the locate effect so it acts once per request (nonce), even though it
+ // re-runs whenever `layout` changes (SSE refreshes) waiting for a not-yet-laid
+ // -out target to appear.
+ const lastLocateRef = useRef(0);
+ // The locate pulse's release timer lives here — NOT in the effect cleanup — so
+ // an SSE/poll layout refresh mid-pulse (which re-runs the effect) can't clear
+ // it and leave the target stuck-hovered.
+ const pulseTimerRef = useRef<number | undefined>(undefined);
+ useEffect(
+ () => () => {
+ if (pulseTimerRef.current) window.clearTimeout(pulseTimerRef.current);
+ },
+ [],
+ );
// Only spawn + trigger edges are drawn (contract A8 drops callback edges from
// the canvas). Derive the rendered set once and drive both the hover
@@ -287,6 +310,42 @@ const Flow: React.FC<AgentGraphCanvasProps> = ({
}
}, [rfNodes, reactFlow]);
+ // Locate (search "跳转"): pan+zoom to the requested node/chip and pulse it.
+ // Runs once per nonce; if the target isn't laid out yet (it just entered via a
+ // filter-widening refetch) this no-ops until a later `layout` pass includes
+ // it. Marks `fittedRef` so a concurrent fitKey change can't steal the viewport
+ // back — a locate is the user's explicit "take me here".
+ useEffect(() => {
+ if (!locate || locate.nonce === lastLocateRef.current) return;
+ const pos = layout.get(locate.rfId);
+ if (!pos) return; // not laid out yet; a later layout pass re-runs this
+ const targetId = locate.rfId;
+ const nonce = locate.nonce;
+ fittedRef.current = true;
+ const w = locate.kind === 'trigger' ? TRIGGER_NODE_WIDTH : SESSION_NODE_WIDTH;
+ const h = locate.kind === 'trigger' ? TRIGGER_NODE_HEIGHT : SESSION_NODE_HEIGHT;
+ // Defer the pan + pulse to the next frame (like the fit) so we never call
+ // setState synchronously inside the effect body.
+ const raf = requestAnimationFrame(() => {
+ // Consume the nonce only once the pan actually runs, so a layout-driven
+ // rerun that cancels this raf before it fires re-schedules rather than
+ // dropping the locate.
+ lastLocateRef.current = nonce;
+ reactFlow.setCenter(pos.x + w / 2, pos.y + h / 2, { zoom: LOCATE_ZOOM, duration: 480 });
+ // Reuse the hover-highlight as the pulse (no new style): mark the target
+ // hovered so its chain lights + the rest fades, then release after a beat.
+ // The release timer lives in a ref so a mid-pulse layout refresh can't
+ // clear it (see pulseTimerRef).
+ setHoveredId(targetId);
+ if (pulseTimerRef.current) window.clearTimeout(pulseTimerRef.current);
+ pulseTimerRef.current = window.setTimeout(() => {
+ setHoveredId((cur) => (cur === targetId ? null : cur));
+ pulseTimerRef.current = undefined;
+ }, LOCATE_PULSE_MS);
+ });
+ return () => cancelAnimationFrame(raf);
+ }, [locate, layout, reactFlow]);
+
return (
<div className="h-[600px] max-h-[72vh] w-full overflow-hidden rounded-2xl border border-border-strong bg-surface-3/60">
<InteractionContext.Provider value={interaction}>
diff --git a/ui/src/components/workbench/AgentGraphSearch.tsx b/ui/src/components/workbench/AgentGraphSearch.tsx
new file mode 100644
index 000000000..be930885a
--- /dev/null
+++ b/ui/src/components/workbench/AgentGraphSearch.tsx
@@ -0,0 +1,221 @@
+// Run-graph node search (M8): a toolbar combobox that finds a session node or
+// trigger chip by id/title/name and, on select, asks the canvas to pan+zoom to
+// it. The matcher is the pure `searchGraph` (unit-tested); this component owns
+// only the input + dropdown + keyboard nav. The search corpus is the broad
+// window payload (incl. filter-hidden rows), so a hit can sit "outside current
+// filters" — those rows are badged and selecting one widens the filters first
+// (handled by the parent).
+import { useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { Loader2, Search } from 'lucide-react';
+import clsx from 'clsx';
+
+import { nodeDisplayTitle, statusMeta } from '../../lib/agentGraph';
+import type { GraphSearchResult } from '../../lib/graphSearch';
+
+// Keep the dropdown bounded; a prefix/substring query narrows fast, and an
+// unbounded list would overflow the toolbar. Truncation is surfaced, not silent.
+const MAX_RESULTS = 40;
+
+const shortId = (id: string) => (id.length > 6 ? `…${id.slice(-6)}` : id);
+
+interface AgentGraphSearchProps {
+ query: string;
+ onQueryChange: (q: string) => void;
+ results: GraphSearchResult[];
+ // Lazy-load hook: the parent fetches the broad search index on first focus.
+ onFocus: () => void;
+ onSelect: (result: GraphSearchResult) => void;
+ // True while the search index is being fetched (first focus / after refresh).
+ loading: boolean;
+ // Whether a result currently sits outside the visible graph filters.
+ isOutsideFilters: (result: GraphSearchResult) => boolean;
+}
+
+export const AgentGraphSearch: React.FC<AgentGraphSearchProps> = ({
+ query,
+ onQueryChange,
+ results,
+ onFocus,
+ onSelect,
+ loading,
+ isOutsideFilters,
+}) => {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const [activeIndex, setActiveIndex] = useState(0);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const listRef = useRef<HTMLDivElement>(null);
+
+ const trimmed = query.trim();
+ const shown = useMemo(() => results.slice(0, MAX_RESULTS), [results]);
+ const overflow = results.length - shown.length;
+ // The panel opens on focus; content shows once there's a query to answer.
+ const panelOpen = open && trimmed.length > 0;
+ // Clamp the active row to the current results at read time rather than syncing
+ // it back through an effect (avoids a cascading re-render when results shrink).
+ const activeRow = shown.length ? Math.min(activeIndex, shown.length - 1) : 0;
+
+ // Scroll the active row into view for keyboard nav past the visible slice.
+ useEffect(() => {
+ if (!panelOpen) return;
+ const el = listRef.current?.querySelector<HTMLElement>('[data-active="true"]');
+ el?.scrollIntoView({ block: 'nearest' });
+ }, [activeRow, panelOpen]);
+
+ // Close on an outside click (mousedown so it beats a row's onMouseDown-select).
+ useEffect(() => {
+ if (!open) return;
+ const onDocMouseDown = (e: MouseEvent) => {
+ if (!containerRef.current?.contains(e.target as Node)) setOpen(false);
+ };
+ document.addEventListener('mousedown', onDocMouseDown);
+ return () => document.removeEventListener('mousedown', onDocMouseDown);
+ }, [open]);
+
+ const choose = (r: GraphSearchResult | undefined) => {
+ if (!r) return;
+ onSelect(r);
+ setOpen(false);
+ };
+
+ const onKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
+ if (e.key === 'Escape') {
+ setOpen(false);
+ return;
+ }
+ if (!panelOpen || shown.length === 0) return;
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ setActiveIndex(Math.min(activeRow + 1, shown.length - 1));
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ setActiveIndex(Math.max(activeRow - 1, 0));
+ } else if (e.key === 'Enter') {
+ e.preventDefault();
+ choose(shown[activeRow]);
+ }
+ };
+
+ return (
+ <div ref={containerRef} className="relative w-full sm:w-[300px]">
+ <div className="flex h-9 w-full items-center gap-2 rounded-md border border-input bg-background px-3 transition-colors focus-within:border-ring focus-within:ring-2 focus-within:ring-ring">
+ <Search className="size-3.5 shrink-0 text-muted" />
+ <input
+ value={query}
+ onChange={(e) => {
+ onQueryChange(e.target.value);
+ setOpen(true);
+ setActiveIndex(0);
+ }}
+ onFocus={() => {
+ setOpen(true);
+ onFocus();
+ }}
+ onKeyDown={onKeyDown}
+ placeholder={t('agents.graph.search.placeholder')}
+ aria-label={t('agents.graph.search.placeholder')}
+ role="combobox"
+ aria-expanded={panelOpen}
+ aria-controls="agent-graph-search-list"
+ className="flex-1 bg-transparent text-[12px] text-foreground outline-none placeholder:text-muted"
+ />
+ {loading && <Loader2 className="size-3.5 shrink-0 animate-spin text-muted" />}
+ </div>
+
+ {panelOpen && (
+ <div
+ id="agent-graph-search-list"
+ ref={listRef}
+ role="listbox"
+ className="absolute z-30 mt-1.5 max-h-[320px] w-full min-w-[280px] overflow-y-auto rounded-lg border border-border-strong bg-surface p-1 shadow-lg"
+ >
+ {shown.length === 0 ? (
+ <div className="px-3 py-6 text-center text-[12px] text-muted">
+ {loading ? t('agents.graph.search.loading') : t('agents.graph.search.empty')}
+ </div>
+ ) : (
+ <>
+ {shown.map((r, i) => (
+ <ResultRow
+ key={r.kind === 'node' ? `n:${r.id}` : `t:${r.id}`}
+ result={r}
+ active={i === activeRow}
+ outside={isOutsideFilters(r)}
+ onHover={() => setActiveIndex(i)}
+ onChoose={() => choose(r)}
+ />
+ ))}
+ {overflow > 0 && (
+ <div className="px-3 pb-1.5 pt-1 text-center text-[11px] text-muted/80">
+ {t('agents.graph.search.more', { count: overflow })}
+ </div>
+ )}
+ </>
+ )}
+ </div>
+ )}
+ </div>
+ );
+};
+
+const ResultRow: React.FC<{
+ result: GraphSearchResult;
+ active: boolean;
+ outside: boolean;
+ onHover: () => void;
+ onChoose: () => void;
+}> = ({ result, active, outside, onHover, onChoose }) => {
+ const { t } = useTranslation();
+ // onMouseDown (not onClick) so selecting fires before the input's blur closes
+ // the panel; preventDefault keeps focus on the input.
+ const select = (e: React.MouseEvent) => {
+ e.preventDefault();
+ onChoose();
+ };
+ return (
+ <button
+ type="button"
+ role="option"
+ aria-selected={active}
+ data-active={active}
+ onMouseEnter={onHover}
+ onMouseDown={select}
+ className={clsx(
+ 'flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] transition',
+ active ? 'bg-foreground/[0.06]' : 'hover:bg-foreground/[0.04]',
+ // Trigger rows get a violet left accent so they read distinctly from
+ // session rows (spec: "行样式区分").
+ result.kind === 'trigger' && 'border-l-2 border-violet/70 pl-1.5',
+ )}
+ >
+ {result.kind === 'node' ? (
+ <>
+ <span className={clsx('size-1.5 shrink-0 rounded-full', statusMeta(result.node.status).dotClass)} />
+ <span className="min-w-0 flex-1 truncate font-medium text-foreground">
+ {nodeDisplayTitle(result.node)}
+ </span>
+ <span className="shrink-0 font-mono text-[10.5px] text-muted">{shortId(result.id)}</span>
+ <span className="shrink-0 text-[10.5px] text-muted">
+ {t(statusMeta(result.node.status).labelKey)}
+ </span>
+ </>
+ ) : (
+ <>
+ <span className="shrink-0 rounded bg-violet/15 px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide text-violet">
+ {t('agents.graph.search.triggerTag')}
+ </span>
+ <span className="min-w-0 flex-1 truncate font-medium text-foreground">
+ {result.trigger.name?.trim() || shortId(result.id)}
+ </span>
+ <span className="shrink-0 font-mono text-[10.5px] text-muted">{shortId(result.id)}</span>
+ </>
+ )}
+ {outside && (
+ <span className="shrink-0 rounded bg-gold/15 px-1.5 py-0.5 text-[10px] font-medium text-gold">
+ {t('agents.graph.search.outsideFilters')}
+ </span>
+ )}
+ </button>
+ );
+};
diff --git a/ui/src/components/workbench/AgentGraphTab.tsx b/ui/src/components/workbench/AgentGraphTab.tsx
index e4ccecbca..290a032f4 100644
--- a/ui/src/components/workbench/AgentGraphTab.tsx
+++ b/ui/src/components/workbench/AgentGraphTab.tsx
@@ -12,14 +12,20 @@ import { Switch } from '../ui/switch';
import { SegmentedRadio } from '../ui/segmented';
import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';
import {
+ type AgentGraphNode,
type AgentGraphResult,
+ type AgentGraphTriggerNode,
type GraphWindow,
GRAPH_WINDOWS,
+ isBackground,
+ triggerRefId,
} from '../../lib/agentGraph';
+import { searchGraph, type GraphSearchResult } from '../../lib/graphSearch';
import { AgentGraphCanvas } from './AgentGraphCanvas';
import { AgentGraphMobileList } from './AgentGraphMobileList';
import { AgentGraphDetail } from './AgentGraphDetail';
import { AgentGraphOrphanStrip } from './AgentGraphOrphanStrip';
+import { AgentGraphSearch } from './AgentGraphSearch';
// Degraded-mode refresh cadence while SSE is disconnected (mirrors the old
// RunningAgentsTab). SSE covers lifecycle writes when connected.
@@ -68,6 +74,36 @@ export const AgentGraphTab: React.FC = () => {
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
+ // ── Node search (M8) ──────────────────────────────────────────────────────
+ // The display graph is server-filtered, so search runs over a separate broad
+ // "index" payload (this window/project, but always incl. ended + background)
+ // fetched lazily on first focus and cached by window/project. Hits outside the
+ // visible filters get badged; selecting one widens the filters, then locates.
+ const [searchQuery, setSearchQuery] = useState('');
+ const [searchIndex, setSearchIndex] = useState<{
+ key: string;
+ nodes: AgentGraphNode[];
+ triggers: AgentGraphTriggerNode[];
+ } | null>(null);
+ const [searchIndexLoading, setSearchIndexLoading] = useState(false);
+ const searchSeqRef = useRef(0);
+ // Set on any display refresh (filter change / SSE / poll) so the next focus
+ // refetches a fresh index; the stale copy stays usable until then.
+ const searchStaleRef = useRef(false);
+ // Locate request handed to the canvas (nonce bumps per request).
+ const [locate, setLocate] = useState<{ rfId: string; kind: 'node' | 'trigger'; nonce: number } | null>(null);
+ const locateNonceRef = useRef(0);
+ // A locate that must wait for a filter-widening refetch to surface its target.
+ // `graphAtRequest` pins the payload present when the user selected, so the
+ // resolver only decides once a genuinely newer payload lands (superseded
+ // in-flight fetches never call setGraph, so graph identity is the signal).
+ const [pendingLocate, setPendingLocate] = useState<{
+ kind: 'node' | 'trigger';
+ id: string;
+ rfId: string;
+ graphAtRequest: GraphPayload | null;
+ } | null>(null);
+
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
@@ -125,6 +161,10 @@ export const AgentGraphTab: React.FC = () => {
// newer one issued after a filter change.
if (!mountedRef.current || seq !== seqRef.current) return;
setGraph(result);
+ // The graph just changed (filter/SSE/poll); the search index may now be
+ // out of date. Mark it stale so the next search-box focus refetches —
+ // the current copy stays usable so an open dropdown doesn't blank out.
+ searchStaleRef.current = true;
// Every session-less live row (any state) goes to the strip — the graph
// is session-centric so these have no node, and the old flat list let
// users end them. The strip labels each by its actual state and offers a
@@ -259,6 +299,121 @@ export const AgentGraphTab: React.FC = () => {
[navigate, triggersById],
);
+ // Lazy-load the broad search index for the current window/project. Skipped
+ // when a fresh copy for this key is already cached; a stale flag (set by any
+ // display refresh) forces a refetch on the next focus.
+ const ensureSearchIndex = useCallback(async () => {
+ const key = `${windowSel}|${projectSel}`;
+ if (searchIndex?.key === key && !searchStaleRef.current) return;
+ const seq = ++searchSeqRef.current;
+ setSearchIndexLoading(true);
+ try {
+ const res = await api.getAgentsGraph({
+ window: windowSel,
+ project: projectSel,
+ includeEnded: true,
+ includeBackground: true,
+ });
+ if (!mountedRef.current || seq !== searchSeqRef.current) return;
+ searchStaleRef.current = false;
+ setSearchIndex({ key, nodes: res.nodes, triggers: res.trigger_nodes });
+ } catch {
+ // Leave any prior index in place; the box just shows no fresh results.
+ } finally {
+ if (mountedRef.current && seq === searchSeqRef.current) setSearchIndexLoading(false);
+ }
+ }, [api, windowSel, projectSel, searchIndex]);
+
+ const searchResults = useMemo<GraphSearchResult[]>(() => {
+ // Gate on the current window/project key: after a filter change the cached
+ // index is for the old key until the focus-triggered refetch lands, and its
+ // hits can't be revealed (the select path only widens active/background, not
+ // project/window). Show nothing until the fresh index arrives.
+ const key = `${windowSel}|${projectSel}`;
+ if (!searchIndex || searchIndex.key !== key) return [];
+ const all = searchGraph(searchQuery, searchIndex.nodes, searchIndex.triggers);
+ // Mobile renders the grouped list, not the canvas, and triggers have no
+ // detail panel — a trigger hit there would be a dead tap, so show nodes
+ // only (they still open the detail panel).
+ return isDesktop ? all : all.filter((r) => r.kind === 'node');
+ }, [searchQuery, searchIndex, windowSel, projectSel, isDesktop]);
+
+ // A hit is "outside current filters" when it isn't in the visible payload.
+ const isOutsideFilters = useCallback(
+ (r: GraphSearchResult) => (r.kind === 'node' ? !nodesById.has(r.id) : !triggersById.has(r.id)),
+ [nodesById, triggersById],
+ );
+
+ const requestLocate = useCallback((kind: 'node' | 'trigger', rfId: string) => {
+ setLocate({ rfId, kind, nonce: ++locateNonceRef.current });
+ }, []);
+
+ // Select a search result: if it's already visible, select + locate now; if it
+ // sits outside the filters, widen the needed toggle(s) and defer the locate to
+ // the pendingLocate effect once the refetch surfaces it.
+ const onSelectResult = useCallback(
+ (r: GraphSearchResult) => {
+ const rfId = r.kind === 'node' ? r.id : triggerRefId(r.id);
+ const inDisplay = r.kind === 'node' ? nodesById.has(r.id) : triggersById.has(r.id);
+ if (inDisplay) {
+ if (r.kind === 'node') setSelectedNodeId(r.id);
+ requestLocate(r.kind, rfId);
+ return;
+ }
+ // Index & display share window/project, so a hit is hidden only by the
+ // active/background toggles — widen exactly what's needed.
+ let flipped = false;
+ if (r.kind === 'node') {
+ if (isBackground(r.node) && !showBackground) {
+ setShowBackground(true);
+ flipped = true;
+ }
+ // Active view keeps only live + queued; an ended/idle node needs 含历史.
+ if (mode === 'active' && !(r.node.live || r.node.status === 'queued')) {
+ setMode('history');
+ flipped = true;
+ }
+ } else {
+ // A trigger chip only draws when its triggered session is in-window;
+ // widen both so the session (and thus the chip) can reappear.
+ if (!showBackground) {
+ setShowBackground(true);
+ flipped = true;
+ }
+ if (mode === 'active') {
+ setMode('history');
+ flipped = true;
+ }
+ }
+ setPendingLocate({ kind: r.kind, id: r.id, rfId, graphAtRequest: graph });
+ // Already at the widest filters but still absent ⇒ the index is stale and
+ // the row aged out; force a refetch so the pendingLocate effect confirms
+ // (graph identity changes) and toasts rather than hanging.
+ if (!flipped) void fetchGraph(false);
+ },
+ [nodesById, triggersById, showBackground, mode, requestLocate, fetchGraph, graph],
+ );
+
+ // Resolve a deferred locate: fire once the widened payload includes the
+ // target; once a genuinely newer payload has landed (graph identity changed)
+ // and it's still missing, it left the window between index load and select —
+ // tell the user, don't hang.
+ useEffect(() => {
+ if (!pendingLocate) return;
+ const present =
+ pendingLocate.kind === 'node'
+ ? nodesById.has(pendingLocate.id)
+ : triggersById.has(pendingLocate.id);
+ if (present) {
+ if (pendingLocate.kind === 'node') setSelectedNodeId(pendingLocate.id);
+ requestLocate(pendingLocate.kind, pendingLocate.rfId);
+ setPendingLocate(null);
+ } else if (graph !== pendingLocate.graphAtRequest) {
+ showToast(t('agents.graph.search.noLongerInWindow'), 'warning');
+ setPendingLocate(null);
+ }
+ }, [pendingLocate, nodesById, triggersById, graph, requestLocate, showToast, t]);
+
const projectLabel = useMemo(() => {
if (projectSel === 'all') return t('agents.graph.filters.projectAll');
if (projectSel === 'standalone') return t('agents.graph.detail.standalone');
@@ -282,6 +437,15 @@ export const AgentGraphTab: React.FC = () => {
{/* Filters */}
<div className="flex flex-wrap items-center gap-2.5">
+ <AgentGraphSearch
+ query={searchQuery}
+ onQueryChange={setSearchQuery}
+ results={searchResults}
+ onFocus={() => void ensureSearchIndex()}
+ onSelect={onSelectResult}
+ loading={searchIndexLoading}
+ isOutsideFilters={isOutsideFilters}
+ />
<SegmentedRadio
value={mode}
onChange={setMode}
@@ -398,6 +562,7 @@ export const AgentGraphTab: React.FC = () => {
// large graph, different project/window); SSE-only refreshes keep
// the same key and preserve the current pan/zoom.
fitKey={`${windowSel}|${projectSel}|${mode}|${showBackground}`}
+ locate={locate}
onSelectNode={setSelectedNodeId}
onSelectTrigger={onSelectTrigger}
onOpenChat={(id) => navigate(`/chat/${encodeURIComponent(id)}`)}
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index ba3c23d3c..47755e120 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2245,6 +2245,15 @@
"watch": "Watch",
"disabled": "Disabled"
},
+ "search": {
+ "placeholder": "Find a session or trigger…",
+ "loading": "Loading…",
+ "empty": "No matches",
+ "more": "+{{count}} more — refine your search",
+ "triggerTag": "Trigger",
+ "outsideFilters": "Outside current filters",
+ "noLongerInWindow": "That session is no longer in the current window."
+ },
"legend": {
"spawn": "Spawn",
"trigger": "Task / Watch",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index dad4a36da..10f850b78 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2245,6 +2245,15 @@
"watch": "WATCH",
"disabled": "已禁用"
},
+ "search": {
+ "placeholder": "查找会话或触发器…",
+ "loading": "加载中…",
+ "empty": "无匹配结果",
+ "more": "还有 {{count}} 条 — 请细化搜索",
+ "triggerTag": "触发",
+ "outsideFilters": "在当前筛选外",
+ "noLongerInWindow": "该会话已不在当前窗口。"
+ },
"legend": {
"spawn": "启动",
"trigger": "Task / Watch 触发",
diff --git a/ui/src/lib/graphSearch.test.ts b/ui/src/lib/graphSearch.test.ts
new file mode 100644
index 000000000..0ae896008
--- /dev/null
+++ b/ui/src/lib/graphSearch.test.ts
@@ -0,0 +1,71 @@
+import { describe, expect, it } from 'vitest';
+
+import { searchGraph } from './graphSearch';
+import type { AgentGraphNode, AgentGraphTriggerNode } from './agentGraph';
+
+// The matcher only reads session_id/title (nodes) and name/definition_id
+// (triggers); minimal casts keep the fixtures readable.
+const node = (over: Partial<AgentGraphNode>): AgentGraphNode =>
+ ({ session_id: 'ses_x', title: null, agent_name: null, ...over }) as AgentGraphNode;
+const trigger = (over: Partial<AgentGraphTriggerNode>): AgentGraphTriggerNode =>
+ ({ definition_id: 'def_x', definition_type: 'scheduled', name: null, schedule_label: null, enabled: true, ...over }) as AgentGraphTriggerNode;
+
+const ids = (rs: ReturnType<typeof searchGraph>) => rs.map((r) => r.id);
+
+describe('searchGraph', () => {
+ it('returns nothing for an empty/whitespace query', () => {
+ expect(searchGraph('', [node({ session_id: 'ses_abc' })], [])).toEqual([]);
+ expect(searchGraph(' ', [node({ session_id: 'ses_abc' })], [])).toEqual([]);
+ });
+
+ it('matches a session_id by prefix (case-insensitive)', () => {
+ const rs = searchGraph('SES_AB', [node({ session_id: 'ses_abc123' })], []);
+ expect(ids(rs)).toEqual(['ses_abc123']);
+ expect(rs[0].rank).toBe(0);
+ });
+
+ it('matches a title by substring, case-insensitive', () => {
+ const rs = searchGraph('draft', [node({ session_id: 'ses_1', title: 'Daily Draft PM' })], []);
+ expect(ids(rs)).toEqual(['ses_1']);
+ expect(rs[0].rank).toBe(1);
+ });
+
+ it('matches a session_id by mid-string substring (lower rank than prefix)', () => {
+ const rs = searchGraph('abc', [node({ session_id: 'ses_xxabc' })], []);
+ expect(ids(rs)).toEqual(['ses_xxabc']);
+ expect(rs[0].rank).toBe(2);
+ });
+
+ it('excludes non-matches', () => {
+ expect(searchGraph('zzz', [node({ session_id: 'ses_1', title: 'hello' })], [])).toEqual([]);
+ });
+
+ it('matches trigger chips by definition name', () => {
+ const rs = searchGraph('daily', [], [trigger({ definition_id: 'def_1', name: 'Daily draft' })]);
+ expect(rs).toHaveLength(1);
+ expect(rs[0].kind).toBe('trigger');
+ expect(rs[0].id).toBe('def_1');
+ });
+
+ it('ranks an id prefix ahead of a substring hit', () => {
+ const rs = searchGraph(
+ 'ses_a',
+ [
+ node({ session_id: 'ses_zzz', title: 'ses_a appears in title' }), // title substring (1)
+ node({ session_id: 'ses_abc' }), // id prefix (0)
+ ],
+ [],
+ );
+ expect(ids(rs)).toEqual(['ses_abc', 'ses_zzz']);
+ });
+
+ it('ranks title/name-substring above id-substring, nodes before triggers on a tie', () => {
+ const nodes = [
+ node({ session_id: 'ses_1', title: 'Backend lane' }), // title substring (1)
+ node({ session_id: 'ses_2lane' }), // id substring (2)
+ ];
+ const triggers = [trigger({ definition_id: 'def_z', name: 'lane watch' })]; // name substring (1)
+ const rs = searchGraph('lane', nodes, triggers);
+ expect(ids(rs)).toEqual(['ses_1', 'def_z', 'ses_2lane']);
+ });
+});
diff --git a/ui/src/lib/graphSearch.ts b/ui/src/lib/graphSearch.ts
new file mode 100644
index 000000000..b50ce89bb
--- /dev/null
+++ b/ui/src/lib/graphSearch.ts
@@ -0,0 +1,55 @@
+// Pure matcher for the run-graph node search (M8). Kept out of the toolbar
+// component so the match + ranking is unit-tested without React Flow.
+//
+// Nodes match on session_id (prefix or substring) or title substring; trigger
+// chips match on their definition name (or definition_id substring). All
+// case-insensitive. Ranking: an id prefix is the strongest signal, then a
+// title/name substring, then an id substring — so "ses_ab…" lands the exact
+// session first and a word in a title still surfaces its node.
+import type { AgentGraphNode, AgentGraphTriggerNode } from './agentGraph';
+
+export type GraphSearchResult =
+ | { kind: 'node'; id: string; node: AgentGraphNode; rank: number }
+ | { kind: 'trigger'; id: string; trigger: AgentGraphTriggerNode; rank: number };
+
+// Ranks (lower = better).
+const RANK_ID_PREFIX = 0;
+const RANK_NAME_SUBSTR = 1;
+const RANK_ID_SUBSTR = 2;
+
+export function searchGraph(
+ query: string,
+ nodes: readonly AgentGraphNode[],
+ triggers: readonly AgentGraphTriggerNode[],
+): GraphSearchResult[] {
+ const q = query.trim().toLowerCase();
+ if (!q) return [];
+
+ const out: GraphSearchResult[] = [];
+
+ nodes.forEach((node) => {
+ const sid = node.session_id.toLowerCase();
+ const title = (node.title ?? '').toLowerCase();
+ let rank = -1;
+ if (sid.startsWith(q)) rank = RANK_ID_PREFIX;
+ else if (title.includes(q)) rank = RANK_NAME_SUBSTR;
+ else if (sid.includes(q)) rank = RANK_ID_SUBSTR;
+ if (rank >= 0) out.push({ kind: 'node', id: node.session_id, node, rank });
+ });
+
+ triggers.forEach((trigger) => {
+ const name = (trigger.name ?? '').toLowerCase();
+ const did = trigger.definition_id.toLowerCase();
+ let rank = -1;
+ if (name.includes(q)) rank = RANK_NAME_SUBSTR; // by definition name (spec)
+ else if (did.includes(q)) rank = RANK_ID_SUBSTR; // id parity with nodes
+ if (rank >= 0) out.push({ kind: 'trigger', id: trigger.definition_id, trigger, rank });
+ });
+
+ // Stable sort by rank; ties keep discovery order (nodes before triggers, then
+ // payload order) via the index tiebreak, so results are deterministic.
+ return out
+ .map((r, i) => ({ r, i }))
+ .sort((a, b) => a.r.rank - b.r.rank || a.i - b.i)
+ .map((x) => x.r);
+}