A desktop coding agent with free access to frontier models.
TypeScript
feat: work knowledge page, connector health and new connectors
ogsamratbb4befb0ef4a
diff --git a/apps/app/src/app/lib/omnirush-server.ts b/apps/app/src/app/lib/omnirush-server.tsindex 85b3209c..920f1f48 100644--- a/apps/app/src/app/lib/omnirush-server.ts+++ b/apps/app/src/app/lib/omnirush-server.ts@@ -625,6 +625,57 @@ export type OmniRushWorkConnector = {records: number;sync_enabled: boolean;};+/** One source of GET /omnirush/work/health (contract Addendum A1). */+export type OmniRushWorkHealth = {+ id: string;+ status?: string;+ token_ok?: boolean;+ scopes_ok?: boolean;+ missing_scopes?: string[];+ last_sync_at?: string | null;+ last_error?: string | null;+ backlog_estimate?: number | null;+ checks?: { name: string; ok: boolean; detail?: string | null }[];+};+export type OmniRushWorkEntityKind = "person" | "company" | "deal" | "project" | "product" | "other";+export type OmniRushWorkEntitySummary = {+ id: string;+ kind: OmniRushWorkEntityKind | string;+ name: string;+ keys: string[];+ record_count: number;+ sources: string[];+ last_activity_at: string | null;+};+export type OmniRushWorkFactKind = "decision" | "preference" | "policy" | "fact" | "contact_note";+export type OmniRushWorkFact = {+ id: string;+ entity_id?: string | null;+ kind: OmniRushWorkFactKind | string;+ text: string;+ source_record_ids?: string[];+ created_by?: "agent" | "user" | string;+ status: "active" | "retired" | string;+ created_at?: string;+ updated_at?: string;+};+export type OmniRushWorkEntityRecord = {+ source_id: string;+ source: string;+ kind: string;+ subject?: string | null;+ text_preview?: string | null;+ occurred_at?: string | null;+ actors?: unknown;+ /** A link to the record at its source, when the server has one. */+ url?: string | null;+};+export type OmniRushWorkEntityDetail = {+ entity: OmniRushWorkEntitySummary & { attrs?: Record<string, unknown> };+ records: OmniRushWorkEntityRecord[];+ facts: OmniRushWorkFact[];+ related: { id: string; kind: string; name: string; reason?: string | null }[];+};export type OmniRushSubagentModelState = {setting: OmniRushSubagentModelSetting;@@ -2293,6 +2344,18 @@ export function createOmniRushServerClient(options: { baseUrl: string; token?: srequestJson<unknown>(baseUrl, `/work/connectors/${encodeURIComponent(id)}/disconnect`, { token, hostToken, method: "POST", timeoutMs: timeouts.config }),setWorkConnectorSync: (id: string, syncEnabled: boolean) =>requestJson<{ ok: boolean; sync_enabled: boolean }>(baseUrl, `/work/connectors/${encodeURIComponent(id)}`, { token, hostToken, method: "PATCH", body: { sync_enabled: syncEnabled }, timeoutMs: timeouts.config }),+ getWorkHealth: (source?: string) =>+ requestJson<unknown>(baseUrl, `/work/health${source ? `?source=${encodeURIComponent(source)}` : ""}`, { token, hostToken, timeoutMs: timeouts.config }),+ listWorkEntities: (query: { q?: string; kind?: string; limit?: number; cursor?: string } = {}) => {+ const params = new URLSearchParams(Object.entries(query).filter(([, value]) => value !== undefined && value !== "").map(([key, value]) => [key, String(value)]));+ return requestJson<{ items: OmniRushWorkEntitySummary[]; next_cursor: string | null }>(baseUrl, `/work/entities${params.size ? `?${params}` : ""}`, { token, hostToken, timeoutMs: timeouts.config });+ },+ getWorkEntity: (id: string) =>+ requestJson<OmniRushWorkEntityDetail>(baseUrl, `/work/entities/${encodeURIComponent(id)}`, { token, hostToken, timeoutMs: timeouts.config }),+ addWorkFact: (fact: { text: string; kind: string; entity_id?: string }) =>+ requestJson<OmniRushWorkFact>(baseUrl, "/work/facts", { token, hostToken, method: "POST", body: fact, timeoutMs: timeouts.config }),+ updateWorkFact: (id: string, patch: { text?: string; status?: "active" | "retired" }) =>+ requestJson<OmniRushWorkFact>(baseUrl, `/work/facts/${encodeURIComponent(id)}`, { token, hostToken, method: "PATCH", body: patch, timeoutMs: timeouts.config }),getWebSearch: () =>requestJson<OmniRushWebSearchState>(baseUrl, "/omnirush/web-search", { token, hostToken, timeoutMs: timeouts.config }),setWebSearch: (enabled: boolean) =>diff --git a/apps/app/src/react-app/domains/session/chat/session-page.tsx b/apps/app/src/react-app/domains/session/chat/session-page.tsxindex 4fdd7c98..c33f8d8d 100644--- a/apps/app/src/react-app/domains/session/chat/session-page.tsx+++ b/apps/app/src/react-app/domains/session/chat/session-page.tsx@@ -158,8 +158,8 @@ export type SessionPageHistoryControls = {export type SessionPageSidebarProps = {/** Work mode (domains/work): the Code | Work switch at the top, shown only while Work is on for the account. */modeToggle?: React.ReactNode;- /** In Work: Home and Connectors take the place of the Code tools row. */- workNavigation?: { onOpenHome: () => void; onOpenConnectors: () => void; connectorsActive: boolean };+ /** In Work: Home, Knowledge and Connectors take the place of the Code tools row. */+ workNavigation?: { onOpenHome: () => void; onOpenConnectors: () => void; connectorsActive: boolean; onOpenKnowledge: () => void; knowledgeActive: boolean };workspaceSessionGroups: WorkspaceSessionGroup[];selectedWorkspaceId: string;selectedSessionId: string | null;diff --git a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsxindex fc7eadb7..5ca5a97f 100644--- a/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx+++ b/apps/app/src/react-app/domains/session/sidebar/app-sidebar.tsx@@ -35,7 +35,7 @@ import {Sparkles,CircleHelp,} from "lucide-react";-import { CalendarClock, Flag, Home, LayoutDashboard, Megaphone, MessageSquareText, Plug, Puzzle } from "lucide-react";+import { CalendarClock, Flag, Home, LayoutDashboard, Library, Megaphone, MessageSquareText, Plug, Puzzle } from "lucide-react";import type { LucideIcon } from "lucide-react";import { LazyMotion, Reorder, domMax, m, useDragControls } from "motion/react";@@ -930,8 +930,8 @@ function SessionSideChatControl({ workspaceId, sessionId, title }: {export type AppSidebarProps = {/** Work mode (domains/work): the Code | Work switch at the top, shown only while Work is on for the account. */modeToggle?: React.ReactNode;- /** In Work: Home and Connectors take the place of the Code tools row. */- workNavigation?: { onOpenHome: () => void; onOpenConnectors: () => void; connectorsActive: boolean };+ /** In Work: Home, Knowledge and Connectors take the place of the Code tools row. */+ workNavigation?: { onOpenHome: () => void; onOpenConnectors: () => void; connectorsActive: boolean; onOpenKnowledge: () => void; knowledgeActive: boolean };sessionNumberShortcuts: SessionNumberShortcutsState;workspaceSessionGroups: WorkspaceSessionGroup[];selectedWorkspaceId: string;@@ -1520,6 +1520,7 @@ export function AppSidebar(props: AppSidebarProps) {{props.workNavigation ? (<div role="group" aria-label="Work" data-testid="sidebar-work-tools" className="flex items-center gap-0.5"><SidebarIconButton icon={Home} label="Work home" onClick={props.workNavigation.onOpenHome} />+ <SidebarIconButton icon={Library} label="Knowledge" active={props.workNavigation.knowledgeActive} onClick={props.workNavigation.onOpenKnowledge} data-testid="sidebar-work-knowledge" /><SidebarIconButton icon={Plug} label="Connectors" active={props.workNavigation.connectorsActive} onClick={props.workNavigation.onOpenConnectors} data-testid="sidebar-work-connectors" /><NotificationBell variant="sidebar-icon" /></div>diff --git a/apps/app/src/react-app/domains/work/knowledge-views.tsx b/apps/app/src/react-app/domains/work/knowledge-views.tsxnew file mode 100644index 00000000..9e8f7fd8--- /dev/null+++ b/apps/app/src/react-app/domains/work/knowledge-views.tsx@@ -0,0 +1,314 @@+/** @jsxImportSource react */+import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";+import { ExternalLink, MessageSquarePlus, Search } from "lucide-react";+import { useState } from "react";++import { Badge } from "@/components/ui/badge";+import { Button } from "@/components/ui/button";+import { Input } from "@/components/ui/input";+import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { toast } from "@/components/ui/sonner";+import { Textarea } from "@/components/ui/textarea";+import type { OmniRushWorkEntityDetail, OmniRushWorkEntityRecord, OmniRushWorkEntitySummary, OmniRushWorkFact } from "@/app/lib/omnirush-server";+import { cn } from "@/lib/utils";++import { askAboutPrompt, connectorLabel, ENTITY_KINDS, FACT_KINDS, workEntityKey, type WorkClient } from "./work-mode";+import { ConnectorIcon } from "./work-views";++const PAGE = 50;++function when(value: string | null | undefined): string {+ if (!value) return "";+ const at = new Date(value);+ return Number.isNaN(at.getTime()) ? "" : at.toLocaleDateString(undefined, { year: "numeric", month: "short", day: "numeric" });+}++/** A record's people, whatever shape the server sends (strings, or {name, email}). */+export function actorNames(actors: unknown): string {+ const list = Array.isArray(actors) ? actors : [];+ return list+ .map((actor) => (typeof actor === "string" ? actor : actor && typeof actor === "object" ? String((actor as { name?: unknown; email?: unknown }).name || (actor as { email?: unknown }).email || "") : ""))+ .filter(Boolean)+ .slice(0, 4)+ .join(", ");+}++const KIND_NAMES: Record<string, string> = { person: "Person", company: "Company", deal: "Deal", project: "Project", product: "Product", other: "Other" };+const kindLabel = (kind: string) => KIND_NAMES[kind] ?? kind;+const factKindLabel = (kind: string) => FACT_KINDS.find((item) => item.id === kind)?.label ?? kind;++/** One entity in the list. */+export function EntityListItem(props: { entity: OmniRushWorkEntitySummary; active: boolean; onSelect: () => void }) {+ const entity = props.entity;+ return (+ <button+ type="button"+ onClick={props.onSelect}+ data-work-entity={entity.id}+ aria-current={props.active ? "true" : undefined}+ className={cn("flex w-full flex-col gap-0.5 border-b border-border px-3 py-2.5 text-start last:border-b-0 hover:bg-muted", props.active && "bg-muted")}+ >+ <span className="flex items-center gap-2">+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{entity.name}</span>+ <span className="flex items-center gap-1">{entity.sources.slice(0, 4).map((source) => <ConnectorIcon key={source} id={source} className="size-3.5" />)}</span>+ </span>+ <span className="truncate text-[12px] text-muted-foreground">+ {[kindLabel(entity.kind), `${entity.record_count.toLocaleString()} records`, when(entity.last_activity_at)].filter(Boolean).join(" · ")}+ </span>+ </button>+ );+}++function Section(props: { title: string; children: React.ReactNode; action?: React.ReactNode }) {+ return (+ <section className="flex flex-col gap-2">+ <div className="flex items-center justify-between">+ <h3 className="text-[12px] font-medium uppercase tracking-wide text-muted-foreground">{props.title}</h3>+ {props.action}+ </div>+ {props.children}+ </section>+ );+}++function RecordRow(props: { record: OmniRushWorkEntityRecord; openLink: (url: string) => void }) {+ const record = props.record;+ const people = actorNames(record.actors);+ return (+ <li className="flex gap-3 border-b border-border py-2 last:border-b-0" data-work-record={record.source_id}>+ <ConnectorIcon id={record.source} className="mt-0.5" />+ <div className="min-w-0 flex-1">+ <div className="flex items-center gap-2">+ <span className="min-w-0 flex-1 truncate text-sm font-medium">{record.subject || record.kind}</span>+ <span className="shrink-0 text-[12px] text-muted-foreground">{when(record.occurred_at)}</span>+ {record.url ? (+ <button type="button" aria-label="Open at the source" className="shrink-0 text-muted-foreground hover:text-foreground" onClick={() => props.openLink(record.url!)}>+ <ExternalLink className="size-3.5" />+ </button>+ ) : null}+ </div>+ <div className="truncate text-[12px] text-muted-foreground">{[connectorLabel(record.source), record.kind, people].filter(Boolean).join(" · ")}</div>+ {record.text_preview ? <p className="mt-0.5 line-clamp-2 text-[13px] text-foreground/80">{record.text_preview}</p> : null}+ </div>+ </li>+ );+}++function FactKindSelect(props: { value: string; onChange: (value: string) => void }) {+ const items = FACT_KINDS.map((kind) => ({ value: kind.id, label: kind.label }));+ return (+ <Select value={props.value} items={items} onValueChange={(value) => value && props.onChange(String(value))}>+ <SelectTrigger className="w-36" aria-label="Kind"><SelectValue /></SelectTrigger>+ <SelectContent><SelectGroup>{items.map((item) => <SelectItem key={item.value} value={item.value}>{item.label}</SelectItem>)}</SelectGroup></SelectContent>+ </Select>+ );+}++/** One saved fact: its text, kind and who saved it; Edit and Retire. */+export function FactRow(props: { fact: OmniRushWorkFact; busy: boolean; onSave: (text: string) => void; onRetire: () => void }) {+ const [editing, setEditing] = useState(false);+ const [text, setText] = useState(props.fact.text);+ if (editing) {+ return (+ <li className="flex flex-col gap-2 rounded-lg border border-border p-2" data-work-fact={props.fact.id}>+ <Textarea aria-label="Fact" value={text} onChange={(event) => setText(event.target.value)} className="min-h-16" />+ <div className="flex justify-end gap-2">+ <Button variant="ghost" size="sm" onClick={() => { setText(props.fact.text); setEditing(false); }}>Cancel</Button>+ <Button size="sm" disabled={props.busy || !text.trim()} onClick={() => { props.onSave(text.trim()); setEditing(false); }}>Save</Button>+ </div>+ </li>+ );+ }+ return (+ <li className="flex items-start gap-2 rounded-lg border border-border px-3 py-2" data-work-fact={props.fact.id}>+ <div className="min-w-0 flex-1">+ <p className="text-sm">{props.fact.text}</p>+ <p className="mt-0.5 text-[12px] text-muted-foreground">+ {[factKindLabel(props.fact.kind), props.fact.created_by === "agent" ? "saved by the agent" : props.fact.created_by === "user" ? "saved by you" : null, when(props.fact.updated_at ?? props.fact.created_at)].filter(Boolean).join(" · ")}+ </p>+ </div>+ <Button variant="ghost" size="sm" disabled={props.busy} onClick={() => setEditing(true)}>Edit</Button>+ <Button variant="ghost" size="sm" disabled={props.busy} onClick={props.onRetire}>Retire</Button>+ </li>+ );+}++/** One entity: keys, sources, saved facts (add, edit, retire), the timeline of its records and related entities. */+export function EntityDetail(props: {+ detail: OmniRushWorkEntityDetail;+ busy: boolean;+ openLink: (url: string) => void;+ onAsk: () => void;+ onSelect: (id: string) => void;+ onAddFact: (fact: { text: string; kind: string }) => void;+ onSaveFact: (id: string, text: string) => void;+ onRetireFact: (id: string) => void;+}) {+ const { entity, records, facts, related } = props.detail;+ const [adding, setAdding] = useState(false);+ const [text, setText] = useState("");+ const [kind, setKind] = useState<string>("fact");+ const active = facts.filter((fact) => fact.status !== "retired");+ const timeline = [...records].sort((a, b) => String(b.occurred_at ?? "").localeCompare(String(a.occurred_at ?? "")));+ const add = () => {+ if (!text.trim()) return;+ props.onAddFact({ text: text.trim(), kind });+ setText("");+ setAdding(false);+ };+ return (+ <div className="flex flex-col gap-6" data-testid="work-entity-detail" data-entity={entity.id}>+ <div className="flex items-start gap-3">+ <div className="min-w-0 flex-1">+ <h2 className="truncate text-xl font-semibold tracking-tight">{entity.name}</h2>+ <p className="text-sm text-muted-foreground">{[kindLabel(entity.kind), `${entity.record_count.toLocaleString()} records`, when(entity.last_activity_at) && `last activity ${when(entity.last_activity_at)}`].filter(Boolean).join(" · ")}</p>+ </div>+ <Button size="sm" onClick={props.onAsk} data-testid="work-entity-ask"><MessageSquarePlus className="size-4" />Ask about this</Button>+ </div>++ {entity.keys.length || entity.sources.length ? (+ <div className="flex flex-wrap gap-1.5">+ {entity.sources.map((source) => (+ <Badge key={`s:${source}`} variant="secondary" className="gap-1"><ConnectorIcon id={source} className="size-3" />{connectorLabel(source)}</Badge>+ ))}+ {entity.keys.map((key) => <Badge key={`k:${key}`} variant="outline" className="font-mono text-[11px]">{key}</Badge>)}+ </div>+ ) : null}++ <Section title="Remembered" action={adding ? null : <Button variant="ghost" size="sm" onClick={() => setAdding(true)} data-testid="work-fact-add">Add</Button>}>+ {adding ? (+ <div className="flex flex-col gap-2 rounded-lg border border-border p-2">+ <Textarea aria-label="New fact" placeholder="e.g. Dana approves every order over $5,000." value={text} onChange={(event) => setText(event.target.value)} className="min-h-16" />+ <div className="flex items-center justify-end gap-2">+ <FactKindSelect value={kind} onChange={setKind} />+ <Button variant="ghost" size="sm" onClick={() => setAdding(false)}>Cancel</Button>+ <Button size="sm" disabled={props.busy || !text.trim()} onClick={add}>Save</Button>+ </div>+ </div>+ ) : null}+ {active.length ? (+ <ul className="flex flex-col gap-1.5">+ {active.map((fact) => (+ <FactRow key={fact.id} fact={fact} busy={props.busy} onSave={(value) => props.onSaveFact(fact.id, value)} onRetire={() => props.onRetireFact(fact.id)} />+ ))}+ </ul>+ ) : adding ? null : <p className="text-sm text-muted-foreground">Nothing saved yet. Add rules, decisions or notes the agent should keep in mind.</p>}+ </Section>++ <Section title="Timeline">+ {timeline.length ? (+ <ul className="flex flex-col">{timeline.map((record) => <RecordRow key={record.source_id} record={record} openLink={props.openLink} />)}</ul>+ ) : <p className="text-sm text-muted-foreground">No linked records yet.</p>}+ </Section>++ {related.length ? (+ <Section title="Related">+ <div className="flex flex-wrap gap-1.5">+ {related.map((item) => (+ <button key={item.id} type="button" onClick={() => props.onSelect(item.id)} title={item.reason ?? undefined}+ className="rounded-full border border-border px-2.5 py-1 text-[12px] hover:bg-muted" data-work-related={item.id}>+ {item.name} <span className="text-muted-foreground">· {kindLabel(item.kind)}</span>+ </button>+ ))}+ </div>+ </Section>+ ) : null}+ </div>+ );+}++/** Work > Knowledge: the people, companies and deals found across the connected sources, and what to remember about them. */+export function WorkKnowledgePage(props: {+ client: WorkClient | null;+ openLink: (url: string) => void;+ onAsk: (prompt: string) => Promise<void>;+ onBack?: () => void;+ initialEntityId?: string | null;+}) {+ const queryClient = useQueryClient();+ const [search, setSearch] = useState("");+ const [kind, setKind] = useState<string | null>(null);+ const [selected, setSelected] = useState<string | null>(props.initialEntityId ?? null);+ const base = props.client?.baseUrl?.trim() || "default";+ const list = useInfiniteQuery({+ queryKey: ["omnirush-work-entities", base, search.trim(), kind],+ queryFn: ({ pageParam }) => props.client!.listWorkEntities({ q: search.trim() || undefined, kind: kind ?? undefined, limit: PAGE, cursor: pageParam ?? undefined }),+ initialPageParam: null as string | null,+ getNextPageParam: (page) => page.next_cursor ?? null,+ enabled: Boolean(props.client),+ });+ const items = list.data?.pages.flatMap((page) => page.items ?? []) ?? [];+ const current = selected ?? items[0]?.id ?? null;+ const detailKey = workEntityKey(props.client, current ?? "");+ const detail = useQuery({ queryKey: detailKey, queryFn: () => props.client!.getWorkEntity(current!), enabled: Boolean(props.client && current) });+ const onError = (reason: unknown) => toast.error(reason instanceof Error ? reason.message : "That did not work. Try again.");+ const refresh = () => queryClient.invalidateQueries({ queryKey: detailKey });+ const addFact = useMutation({ mutationFn: (fact: { text: string; kind: string }) => props.client!.addWorkFact({ ...fact, entity_id: current! }), onSuccess: refresh, onError });+ const updateFact = useMutation({+ mutationFn: ({ id, patch }: { id: string; patch: { text?: string; status?: "active" | "retired" } }) => props.client!.updateWorkFact(id, patch),+ onSuccess: refresh,+ onError,+ });+ const [asking, setAsking] = useState(false);+ const ask = async (entity: OmniRushWorkEntitySummary) => {+ setAsking(true);+ try { await props.onAsk(askAboutPrompt(entity)); }+ catch (reason) { onError(reason); }+ finally { setAsking(false); }+ };+ const busy = addFact.isPending || updateFact.isPending || asking;+ return (+ <div className="flex h-full min-h-0 flex-col" data-testid="work-knowledge">+ <div className="border-b border-border px-6 pb-4 pt-8">+ {props.onBack ? <Button variant="ghost" size="sm" className="-ms-2 mb-2" onClick={props.onBack}>Back to Work</Button> : null}+ <h1 className="text-xl font-semibold tracking-tight">Knowledge</h1>+ <p className="mt-1 text-sm text-muted-foreground">People, companies and deals found across your connected sources, and what the agent should remember about them.</p>+ </div>+ <div className="flex min-h-0 flex-1">+ <div className="flex w-80 shrink-0 flex-col border-e border-border">+ <div className="flex flex-col gap-2 p-3">+ <div className="relative">+ <Search className="pointer-events-none absolute start-2.5 top-1/2 z-10 size-4 -translate-y-1/2 text-muted-foreground" />+ <Input aria-label="Search knowledge" placeholder="Search people, companies, deals…" value={search} onChange={(event) => { setSearch(event.target.value); setSelected(null); }} className="ps-8" data-testid="work-knowledge-search" />+ </div>+ <div className="flex flex-wrap gap-1" role="group" aria-label="Kind">+ {[{ id: null, label: "All" }, ...ENTITY_KINDS].map((item) => (+ <button key={item.id ?? "all"} type="button" aria-pressed={kind === item.id} data-entity-kind={item.id ?? "all"}+ onClick={() => { setKind(item.id); setSelected(null); }}+ className={cn("rounded-full border border-border px-2 py-0.5 text-[12px]", kind === item.id ? "bg-foreground text-background" : "text-muted-foreground hover:text-foreground")}>+ {item.label}+ </button>+ ))}+ </div>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto border-t border-border">+ {list.isLoading ? <div className="p-4 text-sm text-muted-foreground">Loading…</div>+ : list.error ? <div className="p-4 text-sm text-muted-foreground">{list.error instanceof Error ? list.error.message : "Knowledge could not be loaded."}</div>+ : items.length === 0 ? <div className="p-4 text-sm text-muted-foreground">{search.trim() || kind ? "Nothing matches." : "Nothing here yet. Connect a source and it fills in as data syncs."}</div>+ : items.map((entity) => <EntityListItem key={entity.id} entity={entity} active={entity.id === current} onSelect={() => setSelected(entity.id)} />)}+ {list.hasNextPage ? (+ <div className="p-2"><Button variant="ghost" size="sm" className="w-full" disabled={list.isFetchingNextPage} onClick={() => void list.fetchNextPage()}>Load more</Button></div>+ ) : null}+ </div>+ </div>+ <div className="min-w-0 flex-1 overflow-y-auto px-6 py-6">+ {!current ? null+ : detail.isLoading ? <div className="text-sm text-muted-foreground">Loading…</div>+ : detail.error || !detail.data ? <div className="text-sm text-muted-foreground">{detail.error instanceof Error ? detail.error.message : "This entry could not be loaded."}</div>+ : (+ <EntityDetail+ detail={detail.data}+ busy={busy}+ openLink={props.openLink}+ onAsk={() => void ask(detail.data.entity)}+ onSelect={setSelected}+ onAddFact={(fact) => addFact.mutate(fact)}+ onSaveFact={(id, text) => updateFact.mutate({ id, patch: { text } })}+ onRetireFact={(id) => updateFact.mutate({ id, patch: { status: "retired" } })}+ />+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/apps/app/src/react-app/domains/work/work-mode.ts b/apps/app/src/react-app/domains/work/work-mode.tsindex f4ab9290..1fcafddb 100644--- a/apps/app/src/react-app/domains/work/work-mode.ts+++ b/apps/app/src/react-app/domains/work/work-mode.ts@@ -2,7 +2,7 @@ import { useQuery } from "@tanstack/react-query";import { create } from "zustand";import { createJSONStorage, persist } from "zustand/middleware";-import type { OmniRushServerClient, OmniRushWorkConnector, OmniRushWorkState } from "@/app/lib/omnirush-server";+import type { OmniRushServerClient, OmniRushWorkConnector, OmniRushWorkEntitySummary, OmniRushWorkHealth, OmniRushWorkState } from "@/app/lib/omnirush-server";/** The window's top-level mode: Code (today's app) or Work (business chats). Remembered across restarts. */export type AppMode = "code" | "work";@@ -10,6 +10,7 @@ export type AppMode = "code" | "work";export const WORK_PRESET = "work";export const WORK_HOME_ROUTE = "/work";export const WORK_CONNECTORS_ROUTE = "/work/connectors";+export const WORK_KNOWLEDGE_ROUTE = "/work/knowledge";type WorkModeStore = { mode: AppMode; setMode: (mode: AppMode) => void };@@ -20,10 +21,12 @@ export const useWorkModeStore = create<WorkModeStore>()(}),);-export type WorkClient = Pick<OmniRushServerClient, "getWorkState" | "ensureWorkWorkspace" | "listWorkConnectors" | "startWorkConnector" | "disconnectWorkConnector" | "setWorkConnectorSync"> & { baseUrl?: string };+export type WorkClient = Pick<OmniRushServerClient, "getWorkState" | "ensureWorkWorkspace" | "listWorkConnectors" | "startWorkConnector" | "disconnectWorkConnector" | "setWorkConnectorSync"+ | "getWorkHealth" | "listWorkEntities" | "getWorkEntity" | "addWorkFact" | "updateWorkFact"> & { baseUrl?: string };export const workStateKey = (client: WorkClient | null) => ["omnirush-work-state", client?.baseUrl?.trim() || "default"];export const workConnectorsKey = (client: WorkClient | null) => ["omnirush-work-connectors", client?.baseUrl?.trim() || "default"];+export const workEntityKey = (client: WorkClient | null, id: string) => ["omnirush-work-entity", client?.baseUrl?.trim() || "default", id];/** The server's Work switch (re-read every 60 s); Work is hidden entirely while it is off or unknown. */export function useWorkState(client: WorkClient | null) {@@ -125,3 +128,54 @@ export function workToolPermission(permission: string): { label: string; scope:const name = WORK_APPS[app] ?? app;return { label: `${action} (${name})`, scope: `Your ${name} account` };}++/** Connector names for ids the server lists without a label; an unknown id shows as it is (with a generic icon). */+export const CONNECTOR_LABELS: Record<string, string> = {+ google: "Google", microsoft: "Microsoft 365", slack: "Slack", hubspot: "HubSpot", quickbooks: "QuickBooks Online",+ notion: "Notion", jira: "Jira", confluence: "Confluence", linear: "Linear", github: "GitHub", mock: "Test source",+};+export const connectorLabel = (id: string, label?: string | null) => label?.trim() || CONNECTOR_LABELS[id] || id;++/** One source's row of a GET /work/health answer (a list, or `{sources}` / `{items}`); null when absent. */+export function healthFor(answer: unknown, id: string): OmniRushWorkHealth | null {+ const box = answer && typeof answer === "object" ? (answer as Record<string, unknown>) : null;+ const rows = Array.isArray(answer) ? answer : Array.isArray(box?.sources) ? box.sources : Array.isArray(box?.items) ? box.items : [];+ const row = rows.find((item): item is OmniRushWorkHealth => Boolean(item) && typeof item === "object" && (item as { id?: unknown }).id === id);+ return row ?? null;+}++/** What a health check says, in a line: missing scopes (reconnect), a failed check or the last error; null when all is well. */+export function healthProblem(health: OmniRushWorkHealth | null): { text: string; reconnect: boolean } | null {+ if (!health) return null;+ const missing = (health.missing_scopes ?? []).filter(Boolean);+ if (missing.length || health.scopes_ok === false) {+ return { text: `Missing permissions${missing.length ? `: ${missing.join(", ")}` : ""}. Reconnect to grant them.`, reconnect: true };+ }+ if (health.token_ok === false) return { text: "Sign-in expired or revoked. Reconnect.", reconnect: true };+ const failed = (health.checks ?? []).find((check) => !check.ok);+ if (failed) return { text: `${failed.name} failed${failed.detail ? `: ${failed.detail}` : ""}`, reconnect: false };+ if (health.last_error) return { text: health.last_error, reconnect: false };+ return null;+}++export const ENTITY_KINDS = [+ { id: "person", label: "People" },+ { id: "company", label: "Companies" },+ { id: "deal", label: "Deals" },+ { id: "project", label: "Projects" },+ { id: "product", label: "Products" },+ { id: "other", label: "Other" },+] as const;++export const FACT_KINDS = [+ { id: "fact", label: "Fact" },+ { id: "decision", label: "Decision" },+ { id: "preference", label: "Preference" },+ { id: "policy", label: "Policy" },+ { id: "contact_note", label: "Contact note" },+] as const;++/** "Ask about this": the brief a Work chat starts with, so the agent calls work_context on the entity first. */+export function askAboutPrompt(entity: Pick<OmniRushWorkEntitySummary, "id" | "kind" | "name">): string {+ return `Brief me on ${entity.name} (${entity.kind}). Call work_context for "${entity.name}" first (entity id ${entity.id}), then summarise who or what this is, our recent history across every source, open items and anything we decided or agreed to remember, with links to the sources.`;+}diff --git a/apps/app/src/react-app/domains/work/work-views.tsx b/apps/app/src/react-app/domains/work/work-views.tsxindex 29a3339e..ebec0626 100644--- a/apps/app/src/react-app/domains/work/work-views.tsx+++ b/apps/app/src/react-app/domains/work/work-views.tsx@@ -1,6 +1,9 @@/** @jsxImportSource react */import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { ArrowUp, Briefcase, CalendarDays, Code2, Inbox, LifeBuoy, Plug, Receipt, Search, TrendingUp } from "lucide-react";+import {+ ArrowUp, BookOpen, Briefcase, Calculator, CalendarDays, Cloud, Code2, FileText, Github, Handshake, Hash, Inbox, Kanban, LifeBuoy, Mail, Plug,+ Receipt, Search, Shapes, Ticket, TrendingUp, type LucideIcon,+} from "lucide-react";import { useEffect, useRef, useState, type ReactNode } from "react";import { Badge } from "@/components/ui/badge";@@ -8,7 +11,7 @@ import { Button } from "@/components/ui/button";import { toast } from "@/components/ui/sonner";import { Switch } from "@/components/ui/switch";import { Textarea } from "@/components/ui/textarea";-import type { OmniRushWorkConnector } from "@/app/lib/omnirush-server";+import type { OmniRushWorkConnector, OmniRushWorkHealth } from "@/app/lib/omnirush-server";import { cn } from "@/lib/utils";import { useNavigate } from "react-router";@@ -21,7 +24,21 @@ import {LayoutSectionItemTitle,} from "@/react-app/domains/settings/settings-layout";-import { connectSettled, countLabel, useWorkState, visibleConnectors, WORK_CONNECTORS_ROUTE, WORK_TEMPLATES, workConnectorsKey, type AppMode, type WorkClient } from "./work-mode";+import {+ connectorLabel, connectSettled, countLabel, healthFor, healthProblem, useWorkState, visibleConnectors, WORK_CONNECTORS_ROUTE, WORK_TEMPLATES, workConnectorsKey,+ type AppMode, type WorkClient,+} from "./work-mode";++const CONNECTOR_ICONS: Record<string, LucideIcon> = {+ google: Mail, microsoft: Cloud, slack: Hash, hubspot: Handshake, quickbooks: Calculator, notion: FileText,+ jira: Ticket, confluence: BookOpen, linear: Kanban, github: Github, mock: Shapes,+};++/** A connector's icon; an id the app does not know gets the generic plug. */+export function ConnectorIcon(props: { id: string; className?: string }) {+ const Icon = CONNECTOR_ICONS[props.id] ?? Plug;+ return <Icon aria-hidden className={cn("size-4 shrink-0 text-muted-foreground", props.className)} data-connector-icon={CONNECTOR_ICONS[props.id] ? props.id : "generic"} />;+}const TEMPLATE_ICONS: Record<(typeof WORK_TEMPLATES)[number]["id"], ReactNode> = {inbox: <Inbox />,@@ -171,14 +188,21 @@ export function ConnectorRow(props: {onConnect: () => void;onDisconnect: () => void;onSync: (enabled: boolean) => void;+ /** The source's last health check (GET /work/health); undefined: not checked yet. */+ health?: OmniRushWorkHealth | null;+ checking?: boolean;+ onCheck?: () => void;}) {const row = props.connector;const connected = row.status === "connected" || row.status === "syncing" || row.status === "error";+ const problem = healthProblem(props.health ?? null);+ const reconnect = row.status === "error" || Boolean(problem?.reconnect);return (<div className="flex items-center gap-4 border-b border-border px-4 py-3 last:border-b-0" data-work-connector={row.id} data-status={row.status}>+ <ConnectorIcon id={row.id} /><div className="min-w-0 flex-1"><div className="flex items-center gap-2">- <span className="text-sm font-medium">{row.label}</span>+ <span className="text-sm font-medium">{connectorLabel(row.id, row.label)}</span><Badge variant={row.status === "error" ? "destructive" : row.status === "disconnected" ? "outline" : "secondary"} data-testid="work-connector-status">{props.connecting ? "Waiting for sign-in…" : STATUS_LABEL[row.status]}</Badge>@@ -190,6 +214,11 @@ export function ConnectorRow(props: {? [row.account, countLabel(row.records, "record"), lastSync(row.last_sync_at)].filter(Boolean).join(" · "): "Connect to let the agent search and use it."}</div>+ {connected && props.health !== undefined ? (+ <div className={cn("mt-0.5 text-[12px]", problem ? "text-destructive" : "text-muted-foreground")} data-testid="work-connector-health">+ {props.health === null ? "No health report for this source yet." : problem ? problem.text : "All checks passed."}+ </div>+ ) : null}</div>{connected ? (<label className="flex items-center gap-2 text-[12px] text-muted-foreground">@@ -202,10 +231,16 @@ export function ConnectorRow(props: {/></label>) : null}- {connected && row.status !== "error" ? (+ {connected && props.onCheck ? (+ <Button variant="ghost" size="sm" disabled={props.checking} onClick={props.onCheck}>{props.checking ? "Checking…" : "Check"}</Button>+ ) : null}+ {connected && reconnect ? (+ <Button size="sm" disabled={props.busy || props.connecting} onClick={props.onConnect}>Reconnect</Button>+ ) : null}+ {connected ? (<Button variant="outline" size="sm" disabled={props.busy} onClick={props.onDisconnect}>Disconnect</Button>) : (- <Button size="sm" disabled={props.busy || props.connecting} onClick={props.onConnect}>{row.status === "error" ? "Reconnect" : "Connect"}</Button>+ <Button size="sm" disabled={props.busy || props.connecting} onClick={props.onConnect}>Connect</Button>)}</div>);@@ -216,6 +251,7 @@ export function WorkConnectorsPage(props: { client: WorkClient | null; openLink:const queryClient = useQueryClient();const key = workConnectorsKey(props.client);const [connecting, setConnecting] = useState<string | null>(null);+ const [health, setHealth] = useState<Record<string, OmniRushWorkHealth | null>>({});const connectStarted = useRef(0);const query = useQuery({queryKey: key,@@ -246,6 +282,14 @@ export function WorkConnectorsPage(props: { client: WorkClient | null; openLink:onError,});const disconnect = useMutation({ mutationFn: (id: string) => props.client!.disconnectWorkConnector(id), onSuccess: refresh, onError });+ const check = useMutation({+ mutationFn: async (id: string) => healthFor(await props.client!.getWorkHealth(id), id),+ onSuccess: (found, id) => {+ setHealth((current) => ({ ...current, [id]: found }));+ void refresh();+ },+ onError,+ });const sync = useMutation({mutationFn: ({ id, enabled }: { id: string; enabled: boolean }) => props.client!.setWorkConnectorSync(id, enabled),onSuccess: refresh,@@ -279,6 +323,9 @@ export function WorkConnectorsPage(props: { client: WorkClient | null; openLink:onConnect={() => connect.mutate(row.id)}onDisconnect={() => disconnect.mutate(row.id)}onSync={(enabled) => sync.mutate({ id: row.id, enabled })}+ health={health[row.id]}+ checking={check.isPending && check.variables === row.id}+ onCheck={() => check.mutate(row.id)}/>))}</div>@@ -296,7 +343,7 @@ export function WorkConnectorsSetting(props: { client: WorkClient | null }) {<LayoutSectionItem><LayoutSectionItemHeader><LayoutSectionItemTitle>Work connectors</LayoutSectionItemTitle>- <LayoutSectionItemDescription>Connect Google, Microsoft 365, Slack, HubSpot, QuickBooks or Notion for Work chats.</LayoutSectionItemDescription>+ <LayoutSectionItemDescription>Connect your mail, chat, documents, CRM, tickets and accounting for Work chats.</LayoutSectionItemDescription><LayoutSectionItemHeaderActions><Button variant="outline" size="sm" data-testid="settings-work-connectors" onClick={() => navigate(WORK_CONNECTORS_ROUTE)}>Open</Button></LayoutSectionItemHeaderActions>diff --git a/apps/app/src/react-app/shell/app-root.tsx b/apps/app/src/react-app/shell/app-root.tsxindex 51fcb7c4..573c9f9c 100644--- a/apps/app/src/react-app/shell/app-root.tsx+++ b/apps/app/src/react-app/shell/app-root.tsx@@ -484,6 +484,7 @@ export function AppRoot() {/><Route path="/work" element={<DevProfiler id="WorkRoute"><SessionRoute /></DevProfiler>} /><Route path="/work/connectors" element={<DevProfiler id="WorkRoute"><SessionRoute /></DevProfiler>} />+ <Route path="/work/knowledge" element={<DevProfiler id="WorkRoute"><SessionRoute /></DevProfiler>} /><Route path="/apps" element={<DevProfiler id="AppsRoute"><SessionRoute /></DevProfiler>} /><Route path="/dashboard/apps/:appId" element={<DevProfiler id="DashboardAppRoute"><SessionRoute /></DevProfiler>} /><Route path="/apps/:appId" element={<DevProfiler id="AppPreviewRoute"><SessionRoute /></DevProfiler>} />diff --git a/apps/app/src/react-app/shell/session-route.tsx b/apps/app/src/react-app/shell/session-route.tsxindex 76c860b1..1add4c7d 100644--- a/apps/app/src/react-app/shell/session-route.tsx+++ b/apps/app/src/react-app/shell/session-route.tsx@@ -114,7 +114,8 @@ import {type SessionPagePaneRuntime,} from "@/react-app/domains/session/chat/session-page";import { AutomationsPage } from "@/react-app/domains/automations/automations-page";-import { isWorkModeShortcut, shownInMode, useWorkModeStore, useWorkState, WORK_CONNECTORS_ROUTE, WORK_HOME_ROUTE, WORK_PRESET, type AppMode } from "@/react-app/domains/work/work-mode";+import { isWorkModeShortcut, shownInMode, useWorkModeStore, useWorkState, WORK_CONNECTORS_ROUTE, WORK_HOME_ROUTE, WORK_KNOWLEDGE_ROUTE, WORK_PRESET, type AppMode } from "@/react-app/domains/work/work-mode";+import { WorkKnowledgePage } from "@/react-app/domains/work/knowledge-views";import { WorkConnectorsPage, WorkHome, WorkModeToggle } from "@/react-app/domains/work/work-views";import { AppsPage } from "@/react-app/domains/apps/apps-page";import { DashboardPage } from "@/react-app/domains/dashboard/dashboard-page";@@ -3846,11 +3847,13 @@ export function SessionRoute() {}}/>}- primaryTitle={workRouteActive ? (location.pathname.startsWith(WORK_CONNECTORS_ROUTE) ? "Connectors" : "Work") : appsRouteActive ? "Dashboard" : automationsRouteActive ? "Automations" : dashboardRouteActive ? "Dashboard" : tasksRouteActive ? "Parallel tasks" : undefined}+ primaryTitle={workRouteActive ? (location.pathname.startsWith(WORK_CONNECTORS_ROUTE) ? "Connectors" : location.pathname.startsWith(WORK_KNOWLEDGE_ROUTE) ? "Knowledge" : "Work") : appsRouteActive ? "Dashboard" : automationsRouteActive ? "Automations" : dashboardRouteActive ? "Dashboard" : tasksRouteActive ? "Parallel tasks" : undefined}workChat={workChatActive}primarySlot={workRouteActive ? (location.pathname.startsWith(WORK_CONNECTORS_ROUTE) ? (<WorkConnectorsPage client={client ?? null} openLink={(url) => platform.openLink(url)} onBack={() => navigate(WORK_HOME_ROUTE)} />+ ) : location.pathname.startsWith(WORK_KNOWLEDGE_ROUTE) ? (+ <WorkKnowledgePage client={client ?? null} openLink={(url) => platform.openLink(url)} onAsk={startWorkChat} onBack={() => navigate(WORK_HOME_ROUTE)} />) : (<WorkHomebusy={!workWorkspace}@@ -3904,7 +3907,7 @@ export function SessionRoute() {sidebar={{workspaceSessionGroups: sidebarWorkspaceSessionGroups,modeToggle: workEnabled ? <WorkModeToggle mode={appMode} onChange={switchAppMode} shortcut={/Mac/i.test(typeof navigator === "undefined" ? "" : navigator.platform) ? "⌘⇧K" : "Ctrl+Shift+K"} /> : undefined,- workNavigation: appMode === "work" ? { onOpenHome: () => navigate(WORK_HOME_ROUTE), onOpenConnectors: () => navigate(WORK_CONNECTORS_ROUTE), connectorsActive: location.pathname.startsWith(WORK_CONNECTORS_ROUTE) } : undefined,+ workNavigation: appMode === "work" ? { onOpenHome: () => navigate(WORK_HOME_ROUTE), onOpenConnectors: () => navigate(WORK_CONNECTORS_ROUTE), connectorsActive: location.pathname.startsWith(WORK_CONNECTORS_ROUTE), onOpenKnowledge: () => navigate(WORK_KNOWLEDGE_ROUTE), knowledgeActive: location.pathname.startsWith(WORK_KNOWLEDGE_ROUTE) } : undefined,selectedWorkspaceId,selectedSessionId,developerMode: false,diff --git a/apps/app/tests/work-mode.test.tsx b/apps/app/tests/work-mode.test.tsxindex 84814f5f..b1a6268a 100644--- a/apps/app/tests/work-mode.test.tsx+++ b/apps/app/tests/work-mode.test.tsx@@ -2,8 +2,9 @@ import { describe, expect, test } from "bun:test";import { renderToStaticMarkup } from "react-dom/server";import type { OmniRushWorkConnector } from "../src/app/lib/omnirush-server";-import { connectSettled, countLabel, isWorkModeShortcut, shownInMode, visibleConnectors, WORK_TEMPLATES, workToolPermission } from "../src/react-app/domains/work/work-mode";-import { ConnectorRow, WorkHome, WorkModeToggle } from "../src/react-app/domains/work/work-views";+import { askAboutPrompt, connectSettled, countLabel, healthFor, healthProblem, isWorkModeShortcut, shownInMode, visibleConnectors, WORK_TEMPLATES, workToolPermission } from "../src/react-app/domains/work/work-mode";+import { ConnectorIcon, ConnectorRow, WorkHome, WorkModeToggle } from "../src/react-app/domains/work/work-views";+import { actorNames, EntityDetail } from "../src/react-app/domains/work/knowledge-views";const row = (over: Partial<OmniRushWorkConnector>): OmniRushWorkConnector => ({id: "google", label: "Google", status: "disconnected", last_sync_at: null, records: 0, sync_enabled: false, ...over,@@ -87,4 +88,74 @@ describe("Work mode", () => {expect(off).toContain(">Connect<");expect(off).not.toContain('role="switch"');});++ test("an errored source offers Reconnect and Disconnect; Check shows missing scopes with a Reconnect prompt", () => {+ const error = renderToStaticMarkup(<ConnectorRow connector={row({ status: "error", error: "reconnect_required" })} connecting={false} busy={false} onConnect={noop} onDisconnect={noop} onSync={noop} onCheck={noop} />);+ expect(error).toContain(">Reconnect<");+ expect(error).toContain(">Disconnect<");+ expect(error).toContain(">Check<");+ const scopes = renderToStaticMarkup(+ <ConnectorRow connector={row({ id: "jira", label: "Jira", status: "connected", records: 3, sync_enabled: true })} connecting={false} busy={false} onConnect={noop} onDisconnect={noop} onSync={noop} onCheck={noop}+ health={{ id: "jira", token_ok: true, scopes_ok: false, missing_scopes: ["write:jira-work"] }} />,+ );+ expect(scopes).toContain("Missing permissions: write:jira-work");+ expect(scopes).toContain(">Reconnect<");+ const fine = renderToStaticMarkup(+ <ConnectorRow connector={row({ status: "connected" })} connecting={false} busy={false} onConnect={noop} onDisconnect={noop} onSync={noop} onCheck={noop} health={{ id: "google", token_ok: true, scopes_ok: true, checks: [{ name: "profile", ok: true }] }} />,+ );+ expect(fine).toContain("All checks passed.");+ expect(fine).not.toContain(">Reconnect<");+ });++ test("health answers: a list or {sources}; a failed check or last error is the line shown", () => {+ expect(healthFor({ sources: [{ id: "slack", last_error: "rate_limited" }] }, "slack")?.last_error).toBe("rate_limited");+ expect(healthFor([{ id: "slack" }], "google")).toBeNull();+ expect(healthProblem({ id: "x", checks: [{ name: "profile", ok: false, detail: "401" }] })).toEqual({ text: "profile failed: 401", reconnect: false });+ expect(healthProblem({ id: "x", token_ok: false })?.reconnect).toBe(true);+ expect(healthProblem({ id: "x", last_error: "timeout" })?.text).toBe("timeout");+ expect(healthProblem({ id: "x", token_ok: true, scopes_ok: true })).toBeNull();+ });++ test("new connectors get their icon, an unknown id the generic one", () => {+ for (const id of ["jira", "confluence", "linear", "github"]) expect(renderToStaticMarkup(<ConnectorIcon id={id} />)).toContain(`data-connector-icon="${id}"`);+ expect(renderToStaticMarkup(<ConnectorIcon id="zendesk" />)).toContain('data-connector-icon="generic"');+ expect(renderToStaticMarkup(<ConnectorRow connector={row({ id: "zendesk", label: "" })} connecting={false} busy={false} onConnect={noop} onDisconnect={noop} onSync={noop} />)).toContain(">zendesk<");+ });++ test("an entity shows keys, sources, remembered facts (retired hidden), a timeline newest first and related entities", () => {+ const markup = renderToStaticMarkup(+ <EntityDetail+ busy={false} openLink={noop} onAsk={noop} onSelect={noop} onAddFact={noop} onSaveFact={noop} onRetireFact={noop}+ detail={{+ entity: { id: "ent_1", kind: "company", name: "Acme Bakery", keys: ["acme-bakery.test", "hubspot:company:77"], record_count: 12, sources: ["google", "hubspot"], last_activity_at: "2026-11-08T10:00:00Z" },+ records: [+ { source_id: "gmail:old", source: "google", kind: "email", subject: "Old quote", occurred_at: "2026-10-01T10:00:00Z", actors: [{ name: "Dana" }] },+ { source_id: "hubspot:deal:9", source: "hubspot", kind: "deal", subject: "Catering 2027", occurred_at: "2026-11-08T10:00:00Z", actors: ["[email protected]"], url: "https://app.hubspot.example/deal/9" },+ ],+ facts: [+ { id: "f1", kind: "policy", text: "Never discount more than 10%.", status: "active", created_by: "user" },+ { id: "f2", kind: "fact", text: "Old address", status: "retired" },+ ],+ related: [{ id: "ent_2", kind: "person", name: "Dana Lee", reason: "email" }],+ }}+ />,+ );+ expect(markup).toContain("Acme Bakery");+ expect(markup).toContain("acme-bakery.test");+ expect(markup).toContain("Never discount more than 10%.");+ expect(markup).not.toContain("Old address");+ expect(markup).toContain(">Retire<");+ expect(markup.indexOf("Catering 2027")).toBeLessThan(markup.indexOf("Old quote"));+ expect(markup).toContain('aria-label="Open at the source"');+ expect(markup).toContain('data-work-related="ent_2"');+ expect(markup).toContain("Ask about this");+ expect(actorNames([{ name: "Dana" }, { email: "[email protected]" }, "Sam", 5])).toBe("Dana, [email protected], Sam");+ });++ test("Ask about this briefs the chat through work_context on that entity", () => {+ const prompt = askAboutPrompt({ id: "ent_1", kind: "company", name: "Acme Bakery" });+ expect(prompt).toContain("work_context");+ expect(prompt).toContain("Acme Bakery");+ expect(prompt).toContain("ent_1");+ });});diff --git a/apps/server/src/omnirush-gateway-broker.ts b/apps/server/src/omnirush-gateway-broker.tsindex e3405fcd..25454e27 100644--- a/apps/server/src/omnirush-gateway-broker.ts+++ b/apps/server/src/omnirush-gateway-broker.ts@@ -19,6 +19,7 @@ import { BOX_HEADER, MODEL_NOT_IN_MODE, notInModeMessage, projectMode } from "./import { MODE_NOT_BOUND, MODEL_NOT_BOUND, REFUSED_HEADER, SESSION_BIND_UNCONFIRMED, STRICT_SESSION_HEADER, SESSION_BINDING_CONFLICT, SESSION_MODEL_USED, VERIFICATION_REQUIRED, sessionBinder, strictSessions, type StrictSessions } from "./model-modes/strict-sessions.mjs";import { ClaudeDeviceAccess, type ClaudeAuthorization, type ClaudeDeviceRequest } from "./claude-code/access.js";import { stockMode } from "./stock-mode/stock-mode.mjs";+import { WORK_PATH } from "./work/work.js";/** A main chat's request on another model than the one it started on (one model per chat). */const SESSION_MODEL_FIXED = "session_model_fixed";@@ -1976,14 +1977,15 @@ export class OmniRushGatewayBroker {* request: a 401 is returned as it is, with no refresh and no second try.*//**- * A Work mode call (`/omnirush/work/<path>`: connectors, the hosted MCP server), with the device bearer and+ * A Work mode call (`/omnirush/work/<path>[?query]`: connectors, knowledge, health, the hosted MCP server), with the device bearer and* the same bounded 401 refresh. Only the contract's paths; the answer is returned as it came.*/workRequest(path: string, init: { method: "GET" | "POST" | "PATCH"; body?: string; headers?: Record<string, string>; signal?: AbortSignal }): Promise<Response> {- if (!/^(connectors(\/(google|microsoft|slack|hubspot|quickbooks|notion|mock)(\/(start|disconnect))?)?|mcp)$/.test(path)) {+ const [bare = "", query] = path.split("?", 2);+ if (!WORK_PATH.test(bare)) {return Promise.resolve(Response.json({ detail: "unsupported_work_path" }, { status: 404 }));}- return this.withDeviceBearer((state) => this.fetcher(apiUrl(state.gatewayUrl, `work/${path}`), {+ return this.withDeviceBearer((state) => this.fetcher(`${apiUrl(state.gatewayUrl, `work/${bare}`)}${query ? `?${new URLSearchParams(query)}` : ""}`, {method: init.method,headers: {Accept: "application/json",diff --git a/apps/server/src/work/prompt.ts b/apps/server/src/work/prompt.tsindex a0b74c31..1518eb27 100644--- a/apps/server/src/work/prompt.ts+++ b/apps/server/src/work/prompt.ts@@ -9,7 +9,14 @@ The user works at a small business and is not a software developer. Help them ge## How you work- Be concise. Lead with the answer or the result, then the details that matter. Plain language, no jargon, no code unless asked.- Use the connector tools (the omnirush-work tools) to look things up before you answer. Search first (work_search covers everything the user has connected), then read the records you need. Never guess a name, an amount, a date or what someone said.+- When a task mentions a person, a company, a deal or something that happened before (a meeting, a quote, an order, an earlier conversation), call work_context with the task first. It returns who and what is involved, their recent records across every source and what the user asked you to remember about them. Then read or search further as needed.+- To look up one person, company or deal by name, use work_entity.- Use web search only for public information.++## Remembering+- When the user states a lasting rule, decision or preference ("we never discount more than 10%", "Dana handles all Acme orders", "always copy finance on invoices"), offer to save it and call work_remember once they agree, with the matching kind (decision, preference, policy, fact or contact_note) and the person or company it is about. The app asks the user to approve it too.+- Follow what work_context returns as remembered. If it conflicts with what the user says now, the user wins: point out the old note and offer to update it.+- Use work_forget only when the user asks to drop something remembered.- If a source the user needs is not connected, say which one and that they can connect it from Work > Connectors.- When something is ambiguous, ask one short question.diff --git a/apps/server/src/work/routes.ts b/apps/server/src/work/routes.tsindex f69390b4..9572dd65 100644--- a/apps/server/src/work/routes.ts+++ b/apps/server/src/work/routes.ts@@ -8,6 +8,9 @@* POST /work/connectors/:id/start { auth_url }* POST /work/connectors/:id/disconnect* PATCH /work/connectors/:id { sync_enabled }+ * GET /work/health[?source=] the sources' health checks+ * GET /work/entities?q=&kind=&limit=&cursor=, GET /work/entities/:id the context graph+ * GET /work/facts?entity_id=&status=, POST /work/facts, PATCH /work/facts/:id (retire: status)** The engine's hosted MCP calls (POST /omnirush/work/mcp with the engine's token) are forwarded by server.ts.*/@@ -15,7 +18,7 @@ import { mkdir } from "node:fs/promises";import { addRoute, type Route } from "../routes/registry.js";import type { ServerConfig, WorkspaceInfo } from "../types.js";-import { rememberedWorkSwitch, rememberWorkConnectors, rememberWorkSwitch, WORK_PRESET, workHome } from "./work.js";+import { rememberedWorkSwitch, rememberWorkConnectors, rememberWorkSwitch, WORK_PRESET, WORK_SOURCE_ID, workHome } from "./work.js";export type WorkBroker = {workRequest: (path: string, init: { method: "GET" | "POST" | "PATCH"; body?: string; headers?: Record<string, string>; signal?: AbortSignal }) => Promise<Response>;@@ -43,7 +46,20 @@ const WORK_ERRORS: Record<string, string> = {omnirush_account_required: "Sign in to omnirush.ai to use Work.",};-const CONNECTOR = /^(google|microsoft|slack|hubspot|quickbooks|notion|mock)$/;+const CONNECTOR = WORK_SOURCE_ID;+const RECORD_ID = /^[A-Za-z0-9_.:-]{1,128}$/;+const FACT_KINDS = ["decision", "preference", "policy", "fact", "contact_note"];++/** The query a list route forwards: only the named parameters, each short. */+function forwardQuery(url: URL, names: string[]): string {+ const out = new URLSearchParams();+ for (const name of names) {+ const value = url.searchParams.get(name)?.trim();+ if (value) out.set(name, value.slice(0, 200));+ }+ const text = out.toString();+ return text ? `?${text}` : "";+}/** The Work workspace among the server's: preset "work" in the Work folder. */export function findWorkWorkspace(workspaces: WorkspaceInfo[]): WorkspaceInfo | null {@@ -113,6 +129,57 @@ export function registerWorkRoutes(deps: WorkRouteDeps): void {if (!found) return signedOut();return (await passThrough(await found.workRequest(`connectors/${ctx.params.id}`, { method: "PATCH", body: JSON.stringify({ sync_enabled: body.sync_enabled }) }), jsonResponse)).response;});++ // Connector health, the context graph and saved knowledge (Work > Knowledge): forwarded as they are.+ const forward = async (path: string, method: "GET" | "POST" | "PATCH", body?: Record<string, unknown>) => {+ const found = deps.broker();+ if (!found) return signedOut();+ return (await passThrough(await found.workRequest(path, { method, ...(body ? { body: JSON.stringify(body) } : {}) }), jsonResponse)).response;+ };+ const invalid = (detail: string) => jsonResponse({ detail, code: "invalid_request", message: detail }, 400);+ const text = (value: unknown) => (typeof value === "string" && value.trim() ? value.trim() : null);++ addRoute(routes, "GET", "/work/health", "client", async (ctx) => {+ const source = ctx.url.searchParams.get("source");+ if (source && !CONNECTOR.test(source)) return jsonResponse({ detail: "unknown_connector" }, 404);+ return forward(`health${forwardQuery(ctx.url, ["source"])}`, "GET");+ });++ addRoute(routes, "GET", "/work/entities", "client", async (ctx) => forward(`entities${forwardQuery(ctx.url, ["q", "kind", "limit", "cursor"])}`, "GET"));++ addRoute(routes, "GET", "/work/entities/:id", "client", async (ctx) => {+ if (!RECORD_ID.test(ctx.params.id ?? "")) return jsonResponse({ detail: "not_found" }, 404);+ return forward(`entities/${ctx.params.id}`, "GET");+ });++ addRoute(routes, "GET", "/work/facts", "client", async (ctx) => forward(`facts${forwardQuery(ctx.url, ["entity_id", "status"])}`, "GET"));++ addRoute(routes, "POST", "/work/facts", "client", async (ctx) => {+ const body = await deps.readJsonBody(ctx.request);+ const fact = text(body.text);+ if (!fact || fact.length > 4000) return invalid("A fact needs text (at most 4000 characters).");+ if (typeof body.kind !== "string" || !FACT_KINDS.includes(body.kind)) return invalid(`kind must be one of ${FACT_KINDS.join(", ")}`);+ const entity = body.entity_id === undefined || body.entity_id === null ? null : String(body.entity_id);+ if (entity !== null && !RECORD_ID.test(entity)) return invalid("entity_id is not valid");+ return forward("facts", "POST", { text: fact, kind: body.kind, ...(entity ? { entity_id: entity } : {}) });+ });++ addRoute(routes, "PATCH", "/work/facts/:id", "client", async (ctx) => {+ if (!RECORD_ID.test(ctx.params.id ?? "")) return jsonResponse({ detail: "not_found" }, 404);+ const body = await deps.readJsonBody(ctx.request);+ const patch: Record<string, unknown> = {};+ if (body.text !== undefined) {+ const fact = text(body.text);+ if (!fact || fact.length > 4000) return invalid("A fact needs text (at most 4000 characters).");+ patch.text = fact;+ }+ if (body.status !== undefined) {+ if (body.status !== "active" && body.status !== "retired") return invalid("status must be active or retired");+ patch.status = body.status;+ }+ if (Object.keys(patch).length === 0) return invalid("Nothing to change.");+ return forward(`facts/${ctx.params.id}`, "PATCH", patch);+ });}/**diff --git a/apps/server/src/work/work.test.ts b/apps/server/src/work/work.test.tsindex a5fbcdcb..30dbe683 100644--- a/apps/server/src/work/work.test.ts+++ b/apps/server/src/work/work.test.ts@@ -7,7 +7,7 @@ import { firstPartyRemote } from "../mcp-allow/mcp-allow.mjs";import { applyWork } from "./engine.js";import { WORK_PROMPT } from "./prompt.js";import { forwardWorkMcp, registerWorkRoutes, type WorkBroker } from "./routes.js";-import { isWorkRoot, rememberedWorkSwitch, rememberWorkConnectors, rememberWorkSwitch, workEnvironment, workHome } from "./work.js";+import { isWorkRoot, rememberedWorkSwitch, rememberWorkConnectors, rememberWorkSwitch, WORK_PATH, WORK_READ_TOOLS, workEnvironment, workHome } from "./work.js";import type { Route } from "../routes/registry.js";import type { ServerConfig } from "../types.js";@@ -17,8 +17,8 @@ describe("work switch", () => {test("off unless the server says enabled; a missing block turns it off; no answer keeps it", () => {const dir = temp();expect(rememberedWorkSwitch(dir).enabled).toBe(false);- expect(rememberWorkSwitch(dir, { work: { enabled: true, allow_users: "all", sources: ["google", "mock", "zendesk"] } })).toBe(true);- expect(rememberedWorkSwitch(dir)).toEqual({ enabled: true, sources: ["google", "mock"], message: null });+ expect(rememberWorkSwitch(dir, { work: { enabled: true, allow_users: "all", sources: ["google", "mock", "jira", "zendesk", "../x", 7] } })).toBe(true);+ expect(rememberedWorkSwitch(dir)).toEqual({ enabled: true, sources: ["google", "mock", "jira", "zendesk"], message: null });expect(rememberWorkSwitch(dir, null)).toBe(false);expect(rememberedWorkSwitch(dir).enabled).toBe(true);expect(rememberWorkSwitch(dir, { schema_versions: [1, 2, 3] })).toBe(true);@@ -93,6 +93,15 @@ describe("work engine config", () => {});});+describe("work prompt and tools", () => {+ test("context tools read without asking; remember and forget ask; the prompt briefs and remembers", () => {+ for (const tool of ["work_context", "work_entity", "jira_search", "github_read"]) expect(WORK_READ_TOOLS).toContain(tool);+ for (const tool of ["work_remember", "work_forget", "jira_comment", "github_create_issue"]) expect(WORK_READ_TOOLS).not.toContain(tool);+ expect(WORK_PROMPT).toContain("call work_context");+ expect(WORK_PROMPT).toContain("work_remember once they agree");+ });+});+describe("work routes", () => {const json = (data: unknown, status = 200) => Response.json(data, { status });function setup(answer: (path: string, init: { method: string; body?: string; headers?: Record<string, string> }) => Response) {@@ -107,10 +116,11 @@ describe("work routes", () => {const config = { workspaces: [] } as unknown as ServerConfig;registerWorkRoutes({ routes, config, workDir: () => dir, broker: () => broker, jsonResponse: json, readJsonBody: (r) => r.json(), addWorkspace: async (folderPath) => ({ id: "ws_work", name: "Work", path: folderPath, preset: "work", workspaceType: "local" }), applyEngine: async () => undefined });const call = async (method: string, path: string, body?: unknown) => {- const route = routes.find((r) => r.method === method && r.regex.test(path));+ const pathname = path.split("?")[0] ?? "";+ const route = routes.find((r) => r.method === method && r.regex.test(pathname));if (!route) throw new Error(`no route ${method} ${path}`);const params: Record<string, string> = {};- const match = path.match(route.regex);+ const match = pathname.match(route.regex);route.keys.forEach((key, i) => { params[key] = match?.[i + 1] ?? ""; });const request = new Request(`http://x${path}`, { method, ...(body === undefined ? {} : { body: JSON.stringify(body) }) });return route.handler({ request, url: new URL(request.url), params } as never);@@ -129,10 +139,39 @@ describe("work routes", () => {expect(await (await call("POST", "/work/connectors/mock/start")).json()).toEqual({ auth_url: "https://auth.example/x" });expect((await call("PATCH", "/work/connectors/mock", { sync_enabled: false })).status).toBe(200);expect((await call("PATCH", "/work/connectors/mock", { sync_enabled: "no" })).status).toBe(400);- expect((await call("POST", "/work/connectors/zendesk/start")).status).toBe(404);+ expect((await call("POST", "/work/connectors/Bad.Id/start")).status).toBe(404);expect(calls).toEqual(["GET connectors ", "POST connectors/mock/start {}", "PATCH connectors/mock {\"sync_enabled\":false}"]);});+ test("health, entities and facts are forwarded with only their own parameters, and checked first", async () => {+ const { calls, call } = setup((path) => json(path.startsWith("health") ? { sources: [{ id: "jira", token_ok: true, scopes_ok: false, missing_scopes: ["write:jira-work"] }] } : { items: [], next_cursor: null }));+ expect((await (await call("GET", "/work/health?source=jira")).json()).sources[0].missing_scopes).toEqual(["write:jira-work"]);+ expect((await call("GET", "/work/health?source=../x")).status).toBe(404);+ await call("GET", "/work/entities?q=acme%20bakery&kind=company&limit=50&cursor=c1&evil=1");+ await call("GET", "/work/entities/ent_42");+ expect((await call("GET", "/work/entities/a%2Fb")).status).toBe(404);+ await call("GET", "/work/facts?entity_id=ent_42&status=active");+ expect((await call("POST", "/work/facts", { text: " Dana approves orders over $5k ", kind: "policy", entity_id: "ent_42" })).status).toBe(200);+ expect((await call("POST", "/work/facts", { text: "x", kind: "gossip" })).status).toBe(400);+ expect((await call("POST", "/work/facts", { text: " ", kind: "fact" })).status).toBe(400);+ expect((await call("PATCH", "/work/facts/f_1", { status: "retired", extra: 1 })).status).toBe(200);+ expect((await call("PATCH", "/work/facts/f_1", { status: "deleted" })).status).toBe(400);+ expect((await call("PATCH", "/work/facts/f_1", {})).status).toBe(400);+ expect(calls).toEqual([+ "GET health?source=jira ",+ "GET entities?q=acme+bakery&kind=company&limit=50&cursor=c1 ",+ "GET entities/ent_42 ",+ "GET facts?entity_id=ent_42&status=active ",+ "POST facts {\"text\":\"Dana approves orders over $5k\",\"kind\":\"policy\",\"entity_id\":\"ent_42\"}",+ "PATCH facts/f_1 {\"status\":\"retired\"}",+ ]);+ });++ test("the broker reaches only the contract's paths", () => {+ for (const path of ["connectors", "connectors/jira/start", "connectors/github", "entities", "entities/ent_42", "facts", "facts/f_1", "health", "mcp"]) expect(WORK_PATH.test(path)).toBe(true);+ for (const path of ["connectors/../admin", "entities/a/b", "tokens", "admin/work", "facts/f_1/x", ""]) expect(WORK_PATH.test(path)).toBe(false);+ });+test("the server's errors reach the app as they came (work_disabled)", async () => {const { call } = setup(() => json({ detail: "work_disabled" }, 404));const response = await call("GET", "/work/connectors");diff --git a/apps/server/src/work/work.ts b/apps/server/src/work/work.tsindex 18f3738e..76ec046d 100644--- a/apps/server/src/work/work.ts+++ b/apps/server/src/work/work.ts@@ -14,7 +14,11 @@ import { dirname, join, resolve } from "node:path";export const WORK_DIR_ENV = "OMNIRUSH_WORK_DIR";export const WORK_PRESET = "work";-export const WORK_SOURCES = ["google", "microsoft", "slack", "hubspot", "quickbooks", "notion", "mock"] as const;+/** A connector id as the server names it (google, jira, …): new ids the app does not know yet still work. */+export const WORK_SOURCE_ID = /^[a-z][a-z0-9_-]{0,31}$/;++/** The `/omnirush/work/` paths the app calls (the contract's): connectors, entities, facts, health and the MCP server. */+export const WORK_PATH = /^(?:connectors(?:\/[a-z][a-z0-9_-]{0,31}(?:\/(?:start|disconnect))?)?|entities(?:\/[A-Za-z0-9_.:-]{1,128})?|facts(?:\/[A-Za-z0-9_.:-]{1,128})?|health|mcp)$/;/** The hosted server's tools that only read (the contract's table): every other tool asks first, in every mode. */export const WORK_READ_TOOLS = [@@ -22,6 +26,9 @@ export const WORK_READ_TOOLS = ["outlook_search", "outlook_read", "onedrive_search", "onedrive_read", "teams_search", "teams_read","slack_search", "slack_read_channel", "slack_read_thread", "hubspot_search", "hubspot_read","qbo_query", "qbo_read", "notion_search", "notion_read", "work_search", "mock_search", "mock_read",+ "jira_search", "jira_read", "confluence_search", "confluence_read", "linear_search", "linear_read", "github_search", "github_read",+ // The context graph: briefing and lookup only; work_remember and work_forget ask like every write.+ "work_context", "work_entity",];/** The engine's own tools a Work chat does not get (no shell, no code editing). */@@ -71,7 +78,7 @@ export function workServerSwitch(capabilities: unknown): WorkSwitch {const block = isRecord(capabilities) ? capabilities.work : null;if (!isRecord(block)) return { enabled: false, sources: [], message: null };const sources = Array.isArray(block.sources)- ? block.sources.filter((id): id is string => typeof id === "string" && (WORK_SOURCES as readonly string[]).includes(id))+ ? block.sources.filter((id): id is string => typeof id === "string" && WORK_SOURCE_ID.test(id)): [];const message = typeof block.message === "string" && block.message.trim() ? block.message.trim().slice(0, 400) : null;return { enabled: block.enabled === true, sources, message };@@ -100,7 +107,7 @@ export function rememberWorkSwitch(dir: string, capabilities: unknown): booleanexport function rememberWorkConnectors(dir: string, listed: unknown): WorkConnectorUse[] {const rows = Array.isArray(listed) ? listed : isRecord(listed) && Array.isArray(listed.connectors) ? listed.connectors : [];const used = rows- .filter((row): row is Record<string, unknown> => isRecord(row) && typeof row.id === "string" && (WORK_SOURCES as readonly string[]).includes(row.id))+ .filter((row): row is Record<string, unknown> => isRecord(row) && typeof row.id === "string" && WORK_SOURCE_ID.test(row.id)).filter((row) => row.status === "connected" || row.status === "syncing" || row.status === "error").map((row) => ({ id: String(row.id), enabled: row.sync_enabled === true }));try {