import { useRef, useState } from "react"; import { AUTOMATION_OPEN_EVENT, VIEW_OPEN_EVENT, signal } from "../apiContract"; import { call as queryRequest } from "../query/queryApi"; import { agentAddressHash, dataAddressHash } from "../shell/nav"; import { retryEmit, routeForTarget } from "../shell/targetRoute"; import type { AssistantLogTurn } from "./AssistantPage"; import { interceptOpen, useOpenInPlace } from "./OpenInPlace"; const text = (value: unknown): string => typeof value === "string" ? value.trim() : ""; const record = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; export const REQUEST_STATE_LABELS = { submitted: "New", working: "With", "input-required": "Waiting for", completed: "Done", rejected: "Not now", canceled: "Withdrawn", failed: "Could not finish", "auth-required": "Sign in needed", } as const; type RequestState = keyof typeof REQUEST_STATE_LABELS; function requestState(payload: Record): RequestState { const state = text(payload.state); if (Object.prototype.hasOwnProperty.call(REQUEST_STATE_LABELS, state)) return state as RequestState; if (["approved", "Resolved", "Closed by condition"].includes(state || text(payload.status))) return "completed"; if (state === "declined") return "rejected"; if (state === "pending" && payload.type === "access_request") return "input-required"; const metadata = record(payload.metadata); return text(metadata.assigned_to) || text(payload.assigned_to) || text(payload.owner) ? "working" : "submitted"; } /** Read the display state from C4 or legacy columns without changing either wire. */ export function requestStateLabel(value: unknown): string { const payload = record(value); const state = requestState(payload); const label = REQUEST_STATE_LABELS[state]; if (state !== "working" && state !== "input-required") return label; const metadata = record(payload.metadata); const assigned = metadata.assigned_to || payload.assigned_to || payload.owner; const people = assigned || payload.to || payload.recipients; const names = (Array.isArray(people) ? people : text(people).split(",")) .map((person) => text(record(person).name) || text(record(person).username) || text(person)).filter(Boolean); return `${label} ${[...new Set(names)].join(", ") || "someone"}`; } /** C4 extends the existing inbox kinds. Other payloads remain feed notices. */ export const INBOX_TYPES = ["assignment", "access_request", "share", "question", "approval"] as const; export type InboxAction = "approve" | "not_now"; type InboxState = "pending" | "approved" | "declined" | RequestState; export type InboxNotice = { type: typeof INBOX_TYPES[number]; requestId: string; sender: string; text: string; actions: InboxAction[]; state: InboxState; title?: string; stateLabel?: string; }; /** What the card shows: `outcome` is empty until the item is settled. */ export type InboxView = { busy: boolean; outcome: "" | "approved" | "declined"; problem: string }; const PROBLEM = "This choice could not be saved. Try again."; const OUTCOME_LINE = { approved: "Done", declined: "Not now" } as const; /** Reads a C6 payload with narrow guards. Returns null for a feed notice. */ export function readInboxNotice(payload: AssistantLogTurn["payload"]): InboxNotice | null { const row = record(payload); // A C4 task names its kind beside a `from` object. A feed notice also carries `kind` ("share"), // and reading that as an inbox request drops the feed card's Open link. const task = typeof row.from === "object" && row.from !== null; const type = INBOX_TYPES.find((kind) => kind === (row.type || (task ? row.kind : undefined))); if (!payload || !type) return null; const from = payload.sender; const sender = (typeof from === "object" && from ? text(from.name) || text(from.username) : text(from)) || text(record(row.from).person); const actions = Array.isArray(payload.actions) ? payload.actions.filter((action): action is InboxAction => action === "approve" || action === "not_now") : []; const state = payload.state === "approved" || payload.state === "declined" || payload.state === "pending" ? payload.state : requestState(row); return { type, requestId: text(payload.request_id) || text(row.id), sender, title: text(payload.title), text: text(payload.text) || text(payload.body), actions, state, stateLabel: requestStateLabel(row) }; } /** One decision per card: a second press while a POST is in flight, or after an outcome, sends nothing. */ export function inboxDecider(requestId: string, initial: InboxView, onChange: (view: InboxView) => void) { let current = initial; let inFlight = false; const set = (next: Partial) => { current = { ...current, ...next }; onChange(current); }; return async (action: InboxAction): Promise => { if (inFlight || current.outcome || !requestId) return; inFlight = true; set({ busy: true, problem: "" }); try { const result = await queryRequest(`/assistant/inbox/${encodeURIComponent(requestId)}/${action}`, { method: "POST" }, (body: unknown) => (body && typeof body === "object" ? body : {}) as { state?: unknown }); const state = result.ok ? result.value.state : undefined; // "Not now" may leave the item pending on the server. The card still shows the choice. const outcome = state === "approved" || state === "declined" ? state : state === "pending" && action === "not_now" ? "declined" : ""; set(outcome ? { busy: false, outcome } : { busy: false, problem: PROBLEM }); } catch { set({ busy: false, problem: PROBLEM }); } finally { inFlight = false; } }; } /** C6 card: sender, one line, and Approve / Not now while the item waits for a choice. */ export function InboxNoticeView({ notice, view, onAct }: { notice: InboxNotice; view: InboxView; onAct: (action: InboxAction) => void; }) { const choosable = !view.outcome && Boolean(notice.requestId) && (notice.state === "pending" || notice.state === "input-required") && notice.actions.includes("approve") && notice.actions.includes("not_now"); return
{notice.sender ?

From {notice.sender}

: null} {notice.title ?

{notice.title}

: null} {notice.text ?

{notice.text}

: null} {!view.outcome && notice.stateLabel ?

{notice.stateLabel}

: null} {view.outcome ?

{OUTCOME_LINE[view.outcome]}

: choosable ?
: null} {view.problem ?

{view.problem}

: null}
; } function InboxNoticeCard({ notice }: { notice: InboxNotice }) { const [view, setView] = useState(() => ({ busy: false, problem: "", outcome: notice.state === "approved" || notice.state === "declined" ? notice.state : "" })); const decide = useRef | null>(null); if (!decide.current) decide.current = inboxDecider(notice.requestId, view, setView); return void decide.current?.(action)} />; } /** The inbox has no screen of its own (R81): a C6 notice is this card, inside the chat. */ export function NoticeCard({ turn }: { turn: AssistantLogTurn }) { const inbox = readInboxNotice(turn.payload); return inbox ? : ; } /** The feed supplies the sender, subject and permission-filtered target. */ export function FeedNoticeCard({ turn }: { turn: AssistantLogTurn }) { const payload = turn.payload || {}; const sender = text(payload.sender) || text(payload.source); const subject = text(payload.subject) || text(payload.title); const body = text(payload.body) || turn.text; const destination = routeForTarget(payload.target ?? null); const cancel = useRef<(() => void) | null>(null); const inPlace = useOpenInPlace(); const href = destination?.surface === "automation" ? agentAddressHash("agent", destination.autoId) : destination?.surface === "map" ? "#/customer" : destination?.surface === "database" && destination.viewId ? dataAddressHash({ database: destination.key, view: destination.viewId }) : destination ? `#/${destination.key}` : ""; return
{sender ?

From {sender}

: null} {subject ?

{subject}

: null} {body && body !== subject ?

{body}

: null} {destination ? { if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; // S72-T14: a database target opens in the Assistant's pop-up when a host is mounted. if (destination.surface === "database" && interceptOpen(inPlace, destination.key.includes("?") ? `#/${destination.key}` : dataAddressHash({ database: destination.key, view: destination.viewId }), event)) return; event.preventDefault(); cancel.current?.(); window.location.hash = href; if (destination.surface === "automation") { signal(AUTOMATION_OPEN_EVENT, { autoId: destination.autoId, tab: destination.tab }); } else if (destination.surface === "map") { window.setTimeout(() => signal("aios:route-open", { routeId: destination.routeId }), 0); } else if (destination.viewId) { // Timers must survive this card unmounting while the destination grid loads. cancel.current = retryEmit(() => signal(VIEW_OPEN_EVENT, { topic: destination.key, viewId: destination.viewId })); } }}>Open : null}
; }