import type { MachineView, Session, SessionMachineAccess } from "@opengeni/sdk";
import { InfoIcon } from "lucide-react";
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { useSessionStart, type UseSessionStartOptions } from "../hooks/use-session-start";
import { useOpenGeniText } from "../messages/runtime";
import { machineDisplayName } from "../sandbox-label-model";
import {
personalMachineCopy,
runSavedMessageOnMachine,
savedMessageApprovedMachines,
sessionAdmissionApprovedElsewhere,
sessionAdmissionApprovedElsewhereCopy,
sessionAdmissionCopy,
sessionAdmissionMachineChangedCopy,
sessionAdmissionNeedsDifferentMachine,
sessionAdmissionReason,
sessionWaitingWorkExplainsBlock,
waitingMessagesCopy,
waitingWorkCopy,
} from "../session-admission-model";
import { Button } from "../ui/button";
import { Notice } from "../ui/notice";
/**
* Why a chat that runs on a personal machine can't take somebody's message,
* with the ways forward. `queued` explains a saved message the runtime
* refused; otherwise it warns about a draft before it is sent.
*/
export function PersonalMachineExplanation({
access,
queued = false,
action,
}: {
access: SessionMachineAccess;
queued?: boolean | undefined;
/** A machine picker or other way forward, shown before the copy-request button. */
action?: ReactNode | undefined;
}) {
const t = useOpenGeniText();
const copy = personalMachineCopy(t, access, { queued });
return (
<>
{copy.explanation}
{copy.next}
{copy.workNote ?
{copy.workNote}
: null}
>
);
}
/** A way forward plus "Copy request to …": a message the person sends the owner themselves. */
function OwnerRequestActions({
request,
label,
action,
}: {
request: string | null;
label: string | null;
action?: ReactNode | undefined;
}) {
const t = useOpenGeniText();
const [copyState, setCopyState] = useState<"idle" | "copied" | "failed">("idle");
if (!action && !(request && label)) return null;
return (
<>
) : null}
>
);
}
/**
* Updates from other people's work (their agents' messages and workers'
* results) wait because this chat runs on somebody's personal machine. One
* notice for all of them, updated in place: it says whose updates wait and
* why, and gives the machine's owner the way to let the agent continue with
* them under the owner's own access. Everyone else acts from the composer's
* notice (choose a machine, or ask the owner). Renders nothing when nothing waits.
*/
export function SessionWaitingWorkNotice({
access,
busy = false,
onContinue,
}: {
access: SessionMachineAccess;
/** Another control action is in flight. */
busy?: boolean | undefined;
/** The owner lets the agent continue with them; omitted where the host can't. */
onContinue?: (() => Promise) | undefined;
}) {
const t = useOpenGeniText();
const descriptionId = useId();
const pending = useRef(false);
const [continuing, setContinuing] = useState(false);
const [failure, setFailure] = useState(null);
const copy = waitingWorkCopy(t, access);
if (!copy) return null;
const canContinue = copy.continueAction !== null && onContinue !== undefined;
async function continueWork() {
if (pending.current || busy || !onContinue) return;
pending.current = true;
setContinuing(true);
setFailure(null);
try {
await onContinue();
} catch (error) {
// 409: the chat is not running the owner's own work yet (for example,
// someone else sent the last message before it moved to this machine).
setFailure(
(error as { status?: unknown } | null)?.status === 409
? t("sessionAdmission.continueWaitingWorkNeedsYourTurn")
: t("sessionAdmission.continueWaitingWorkFailed"),
);
} finally {
pending.current = false;
setContinuing(false);
}
}
return (
{copy.explanation}
{copy.continueAction === null || canContinue ?
{copy.next}
: null}
{canContinue ? (
) : null}
{failure ? (
{failure}
) : null}
);
}
/**
* Messages other people sent wait because this chat runs on somebody's
* personal machine, where only its owner can start work. One calm notice for
* all of them: whose messages wait, and what brings them to the agent. They
* never block the chat, so it offers no action. Renders nothing when none wait.
*/
export function SessionWaitingMessagesNotice({ access }: { access: SessionMachineAccess }) {
const t = useOpenGeniText();
const copy = waitingMessagesCopy(t, access);
if (!copy) return null;
return (
{copy.explanation}
{copy.next}
);
}
/**
* The personal machine a chat runs on, before sending. On somebody else's
* machine a new message from this person could not start there, so it says
* why and offers the ways forward. Its owner, in a chat shared with the
* workspace, gets a one-line heads-up that people here see what the agent
* does on it, with `action` as the way to move elsewhere. Renders nothing in
* the owner's private chats or when the chat is not on a personal machine.
*/
export function SessionMachineAccessNotice({
access,
action,
shared = false,
className,
}: {
access: SessionMachineAccess | null | undefined;
action?: ReactNode | undefined;
/** The chat is shared with the workspace rather than Only me. */
shared?: boolean | undefined;
/** Spacing for the owner's one-line heads-up where it sits. */
className?: string | undefined;
}) {
const t = useOpenGeniText();
if (!access) return null;
if (access.isOwner) {
if (!shared) return null;
return (
);
}
return (
);
}
export type SessionAdmissionNoticeProps = {
session: Session;
/** The person may pause, resume and recheck this session. */
canControl: boolean;
/** The session is paused; rechecking would not clear that. */
paused: boolean;
/** Another control action is in flight. */
busy: boolean;
/** Control changed underneath the notice: re-read before any recheck. */
refreshRequired?: boolean | undefined;
/** One fenced Resume followed by a fresh read (see `recheckSessionAdmission`). */
onRecheck: () => Promise;
/** The session's current personal-machine projection, when known. */
machineAccess?: SessionMachineAccess | null | undefined;
/** The machine picker offered when the saved message needs a different machine. */
machineAction?: ReactNode | undefined;
/**
* The person's machines, to find the one a saved message was approved for
* (`machineAccess.queuedTurnApprovedMachines`). Omit where they aren't read.
*/
machines?: readonly MachineView[] | undefined;
/**
* Move the chat to a machine (by sandbox id) without sending anything.
* Offered as "Run it on …" when the saved message was approved for that
* machine; the notice rechecks once the move is confirmed.
*/
onMoveToMachine?: ((sandboxId: string) => Promise) | undefined;
/**
* As the machine's owner, let the agent continue with other people's
* waiting updates (`machineAccess.waitingWork`): continue, then recheck a
* blocked chat and refresh. Omit where the host cannot.
*/
onContinueWaitingWork?: (() => Promise) | undefined;
};
/**
* The runtime refused to start the session's next message (an admission
* block). Says why in the person's language, keeps the saved message, and
* offers the one safe way forward: choose a machine they can use, or recheck
* after access changes. Renders nothing when the session is not blocked.
*/
export function SessionAdmissionNotice({
session,
canControl,
paused,
busy,
refreshRequired = false,
onRecheck,
machineAccess,
machineAction,
machines,
onMoveToMachine,
onContinueWaitingWork,
}: SessionAdmissionNoticeProps) {
const t = useOpenGeniText();
const descriptionId = useId();
const pending = useRef(false);
const [checking, setChecking] = useState(false);
const [failed, setFailed] = useState(false);
const [moveFailure, setMoveFailure] = useState(null);
const [blockedMachine, setBlockedMachine] = useState<{
sandboxId: string;
blockedAt: string | undefined;
} | null>(null);
const reason = sessionAdmissionReason(session);
const machineBlocked = sessionAdmissionNeedsDifferentMachine(reason, machineAccess);
const approvedElsewhere = sessionAdmissionApprovedElsewhere(reason, machineAccess);
const blockedAt = session.admissionBlock?.blockedAt;
const machineSandboxId = machineAccess?.sandboxId;
// Remember the machine the message couldn't run on, so after the chat moves
// the notice says the machine changed and offers the recheck.
const blockedHere = machineBlocked || approvedElsewhere;
useEffect(() => {
if (blockedHere && machineSandboxId) {
setBlockedMachine((previous) =>
previous?.sandboxId === machineSandboxId && previous.blockedAt === blockedAt
? previous
: { sandboxId: machineSandboxId, blockedAt },
);
}
}, [blockedHere, machineSandboxId, blockedAt]);
// Other people's messages waiting for the machine's owner never block the
// chat; they are explained beside whatever else the chat shows.
const waitingMessages = machineAccess?.waitingMessages?.length ? (
) : null;
// Other people's updates waiting on a personal machine: one calm notice
// that says whose and why, instead of a generic permission failure.
if (
machineAccess?.waitingWork?.length &&
!machineBlocked &&
sessionWaitingWorkExplainsBlock(reason)
) {
return (
<>
{waitingMessages}
>
);
}
if (!reason) return waitingMessages;
const machineChanged =
((reason.reason === "database_claim_rejected" && reason.permissionDenied) ||
reason.reason === "personal_resource_grant_required") &&
!blockedHere &&
blockedMachine !== null &&
blockedMachine.blockedAt === blockedAt &&
blockedMachine.sandboxId !== session.activeSandboxId;
const copy = machineChanged
? sessionAdmissionMachineChangedCopy(t)
: sessionAdmissionCopy(t, reason);
async function recheck() {
if (pending.current || busy || ((paused || machineBlocked) && !refreshRequired) || !canControl)
return;
pending.current = true;
setChecking(true);
setFailed(false);
setMoveFailure(null);
try {
await onRecheck();
} catch {
setFailed(true);
} finally {
pending.current = false;
setChecking(false);
}
}
// Move back to the machine the saved message was approved for, then recheck
// once. The same pending state as a recheck: while it runs, whatever the
// notice shows next (the reads land one by one) stays busy.
async function runOnMachine(sandboxId: string) {
if (pending.current || busy || paused || !canControl || !onMoveToMachine) return;
pending.current = true;
setChecking(true);
setFailed(false);
setMoveFailure(null);
try {
setMoveFailure(
await runSavedMessageOnMachine({
sandboxId,
attach: onMoveToMachine,
recheck: onRecheck,
failedMove: t("sessionAdmission.machineChangeFailed"),
}),
);
} catch {
setFailed(true);
} finally {
pending.current = false;
setChecking(false);
}
}
if (approvedElsewhere && machineAccess) {
return (
<>
void recheck()}
onRun={(sandboxId) => void runOnMachine(sandboxId)}
/>
{waitingMessages}
>
);
}
return (
<>
) : null}
{waitingMessages}
>
);
}
/**
* The person's own saved message was approved for another of their machines,
* so it can't start where the chat runs now and no recheck would help. Names
* both machines and offers the one action that starts it: move the chat back
* and recheck. Sending it again here goes through the queue, which already
* offers removing it.
*/
function ApprovedElsewhereNotice({
access,
machines,
canControl,
canMove,
paused,
busy,
running,
refreshRequired,
failure,
machineAction,
onRefresh,
onRun,
}: {
access: SessionMachineAccess;
machines: readonly MachineView[];
canControl: boolean;
canMove: boolean;
paused: boolean;
busy: boolean;
running: boolean;
refreshRequired: boolean;
failure: string | null;
machineAction?: ReactNode | undefined;
onRefresh: () => void;
onRun: (sandboxId: string) => void;
}) {
const t = useOpenGeniText();
const descriptionId = useId();
const target = savedMessageApprovedMachines(access, machines)[0] ?? null;
const copy = sessionAdmissionApprovedElsewhereCopy(t, access, target);
return (
) : null}
);
}
export type SessionMachineChoicesProps = {
/** Machines the saved message can move to; see `savedMessageMachineChoices`. */
machines: readonly MachineView[];
/** Move the chat; resolve to an error to show, or null once it moved. */
onChoose: (machine: MachineView) => Promise;
disabled?: boolean | undefined;
/** A more specific reason for the last failed move (for example, the machine went offline). */
failureDetail?: string | null | undefined;
};
/**
* A compact "Choose machine" disclosure listing the machines the person may
* move the chat to. Moving never resends anything: the saved message runs only
* after an explicit recheck.
*/
export function SessionMachineChoices({
machines,
onChoose,
disabled,
failureDetail,
}: SessionMachineChoicesProps) {
const t = useOpenGeniText();
const listId = useId();
const [open, setOpen] = useState(false);
const [moving, setMoving] = useState(null);
const [error, setError] = useState(null);
return (
// `contents`: the toggle sits in its parent's action row (beside "Copy
// request"); the open list wraps onto its own full-width line below it.
{open ? (
{machines.length === 0 ? (
{t("sessionAdmission.noMachineChoices")}
) : (
{machines.map((machine) => (
))}
)}
{t("sessionAdmission.savedMessageMachineNote")}
{error ? (
{failureDetail || error}
) : null}
) : null}
);
}
export type SessionStartNoticeProps = UseSessionStartOptions & {
/** The person may control this session. The server enforces it either way. */
canControl?: boolean | undefined;
/** Another control action (send, pause, resume) is in flight. */
busy?: boolean | undefined;
/** Warn before sending when the chat runs on somebody else's personal machine. */
showPreSendWarning?: boolean | undefined;
};
/**
* Everything a chat embedding needs to explain why a message can't start:
* the admission block for a saved message the runtime refused and, before
* sending, the personal-machine warning. Offers the machines the person may
* use, moves the chat, and rechecks with one fenced Resume, so the saved
* message is kept and never sent twice. Access control is the server's; this
* only explains it and offers the allowed ways forward. Every word comes from
* the message catalog (`sessionAdmission.*`).
*/
export function SessionStartNotice({
canControl = true,
busy = false,
showPreSendWarning = true,
...options
}: SessionStartNoticeProps) {
const start = useSessionStart(options);
const { session } = options;
const picker = start.canChooseMachine ? (
) : undefined;
const waiting =
(start.machineAccess?.waitingWork?.length ?? 0) > 0 ||
(start.machineAccess?.waitingMessages?.length ?? 0) > 0;
return (
<>
{start.reason || waiting ? (
) : null}
{showPreSendWarning && start.warnBeforeSending ? (
) : null}
>
);
}