File size: 10,345 Bytes
1ad1eea 8145bee 1ad1eea 8145bee 1ad1eea 8145bee 98c8696 8145bee 98c8696 1ad1eea 98c8696 1ad1eea 98c8696 1ad1eea 98c8696 1ad1eea 98c8696 043da5c 1ad1eea 98c8696 1ad1eea 98c8696 1ad1eea 98c8696 1ad1eea 98c8696 1ad1eea 98c8696 1ad1eea 98c8696 1ad1eea 8145bee 1ad1eea 8145bee 1ad1eea 8145bee 81a8217 8145bee 1ad1eea 8145bee | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | 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<string, unknown> =>
value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
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<string, unknown>): 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<InboxView>) => { current = { ...current, ...next }; onChange(current); };
return async (action: InboxAction): Promise<void> => {
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 <section className="as-notice" aria-label="Notice">
{notice.sender ? <p className="as-notice-sender">From {notice.sender}</p> : null}
{notice.title ? <h3 className="as-notice-subject">{notice.title}</h3> : null}
{notice.text ? <p className="as-notice-body">{notice.text}</p> : null}
{!view.outcome && notice.stateLabel ? <p className="as-notice-sender" role="status">{notice.stateLabel}</p> : null}
{view.outcome ? <p className="as-confirm-result" role="status">{OUTCOME_LINE[view.outcome]}</p>
: choosable ? <div className="as-confirm-actions">
<button type="button" className="as-confirm-button as-notice-approve" disabled={view.busy}
onClick={() => onAct("approve")}>Approve</button>
<button type="button" className="as-confirm-button" disabled={view.busy}
onClick={() => onAct("not_now")}>Not now</button>
</div> : null}
{view.problem ? <p className="as-problem" role="status">{view.problem}</p> : null}
</section>;
}
function InboxNoticeCard({ notice }: { notice: InboxNotice }) {
const [view, setView] = useState<InboxView>(() => ({ busy: false, problem: "",
outcome: notice.state === "approved" || notice.state === "declined" ? notice.state : "" }));
const decide = useRef<ReturnType<typeof inboxDecider> | null>(null);
if (!decide.current) decide.current = inboxDecider(notice.requestId, view, setView);
return <InboxNoticeView notice={notice} view={view} onAct={(action) => 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 ? <InboxNoticeCard notice={inbox} /> : <FeedNoticeCard turn={turn} />;
}
/** 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 <section className="as-notice" aria-label="Notice">
{sender ? <p className="as-notice-sender">From {sender}</p> : null}
{subject ? <h3 className="as-notice-subject">{subject}</h3> : null}
{body && body !== subject ? <p className="as-notice-body">{body}</p> : null}
{destination ? <a className="as-notice-open" href={href} onClick={(event) => {
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</a> : null}
</section>;
}
|