import { useOptionalAppContext } from "../../app-context"; import { archiveActionLabel } from "../../lib/archive-session"; // The session header bar — the slim canvas top strip's contents on a session // route. Split out of the session shell as a PURE, presentational component: it takes // plain session data + callbacks and renders the two-line identity block // (breadcrumb → title) on the left and the action cluster on the right // (provider+model·effort·speed, sandbox, pin, connection, status, panel). // The live children that need their own hooks — the sandbox switcher and the // subscription account control — arrive as slots so the whole bar can be rendered // (and screenshotted) in isolation. `CanvasTopStrip` in session-shell owns the // data wiring and passes the real slots. import { t } from "../../lib/console-text"; import { cn } from "../../lib/utils"; import { OPEN_WORKSTREAM_CONTROL_EVENT } from "../../../workstream-control-event"; import { SessionStatus as SessionStatusBadge, SESSION_STATUS_META, StatusDot, StatusPill, } from "../../../components/session-status"; import { sessionDisplayStatus, type SessionDisplayStatus } from "../../../session-status-model"; import { ModelMark } from "../../../components/model-mark"; import { modelDisplayName } from "@opengeni/sdk/model-display"; import type { SessionEventsConnectionState } from "../../../hooks/use-session-events"; import type { SessionSummary } from "@opengeni/sdk"; import { SiteOriginLink, SiteOriginMenuItem } from "../session/site-origin-link"; import { sessionSiteOrigin } from "../../lib/session-site-origin"; import { sessionSlackAgentInfo } from "../../lib/session-slack-agent"; import { MetaChip } from "../../../ui/meta-chip"; import type { CreateBotTemplateRequest, WorkspaceBotTemplate } from "@opengeni/contracts"; import { ArchiveIcon, BellIcon, BellOffIcon, BotIcon, CalendarClockIcon, CopyIcon, GaugeIcon, LinkIcon, LockIcon, MoreHorizontalIcon, PanelRightCloseIcon, PanelRightOpenIcon, PauseIcon, PencilIcon, PinIcon, SearchIcon, Share2Icon, ShieldCheckIcon, ShieldOffIcon, SmartphoneIcon, UserRoundPenIcon, ZapIcon, ZapOffIcon, } from "lucide-react"; import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"; import { BillingClassMark, type BillingClass } from "../billing-class-mark"; import { ConnectionPill } from "../common"; import { GrantSessionAdminAccessDialog, SessionAdminAccessIndicator, SessionAdminAccessMenuItems, type SessionAdminAccessControl, } from "../session/session-admin-access"; import { SessionAncestryBreadcrumb } from "../session/subagents"; import { ShareChatDialog } from "../session/share-chat-dialog"; import { useSessionUiFeature } from "../../lib/session-ui-features"; import { SESSION_HEADER_PARTS, useSessionHeaderOverflow, type SessionHeaderPart, } from "./session-header-overflow"; import { Button } from "../../../ui/button"; import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuTrigger, } from "../../../ui/context-menu"; import { copyTitle } from "../../lib/copy-link"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuShortcut, DropdownMenuTrigger, } from "../../../ui/dropdown-menu"; import { useActionShortcut } from "../../lib/actions/actions-provider"; import { useChatOperations } from "../../lib/actions/chat-operations"; import { RENAME_CURRENT_CHAT_EVENT } from "../../lib/actions/events"; import { Skeleton } from "../../../ui/skeleton"; import { requestConversationFind } from "../../lib/conversation-find-event"; import { currentPhoneAppPlatform, openInAppUrl } from "../../lib/open-in-app"; import { sessionControlPaused, sessionInputWait } from "../../lib/session-rail"; import { sessionAutomationWaitLines, sessionAutomationWaitWords, } from "../../../components/automations/automation-model"; import { HoverCard, HoverCardContent, HoverCardTrigger } from "../../../ui/hover-card"; import { useSessionStartup } from "../../../lib/session-startup"; import { isCodexProductModel } from "../../lib/session-model"; import { SESSION_TITLE_MAX_LENGTH, sessionDisplayTitle, useInlineRename, type InlineRename, } from "../../lib/session-rename"; import { pinLiveAnnouncement } from "../../lib/pin-live-announcement"; import { repliesMuteLabel, type SessionRepliesMute } from "../../lib/inbox"; import { labelEffort, type IntelligenceEffort } from "../../lib/session-tools"; import type { LatencyMode, Session } from "../../types"; import { usePage } from "../../lib/navigation"; import { toast } from "../../lib/toast"; import { SessionAvatar } from "../session/session-avatar"; import { SessionProfileEditorDialog, type UpdateSessionProfileFn, } from "../session/session-profile-editor"; import { BotTemplateDialog } from "../bots/bot-template-dialog"; import { useUiEventTarget } from "../../lib/ui-events"; const SUBSCRIPTION_RAILS: ReadonlySet = new Set([ "codex_subscription", "claude_subscription", "supergrok_subscription", ]); export function SessionHeader({ session, ancestors, onOpenAutomations, lineageLoading, lineageError, connectionState, status, keyAuthRequired, onForgetAccessKey, inspectorOpen, onToggleInspector, onRename, onPin, onUpdateProfile, onSaveBotTemplate, onArchive, repliesMute, adminAccess, onOpenUsageLimit, sandboxSlot, accountSlot, accessSlot, leading, lastStartedModel, lastStartedReasoningEffort, lastStartedLatencyMode, billingClass, modelLabel, modelLogoUrl, policyLoading, }: { session: Session; /** Root-to-direct-parent order. */ ancestors: SessionSummary[]; /** * Present only when an automation posts into this session. Opens the * Automations page filtered to this chat, so the reader can see or edit what * puts runs here. */ onOpenAutomations?: ((() => void) | null) | undefined; lineageLoading?: boolean | undefined; lineageError?: Error | null | undefined; connectionState: SessionEventsConnectionState; status: Session["status"]; keyAuthRequired: boolean; onForgetAccessKey: () => void; inspectorOpen: boolean; /** Absent: the surface shows no session panel, so no toggle. */ onToggleInspector?: (() => void) | undefined; onRename: (workspaceId: string, sessionId: string, title: string) => Promise; onPin: (session: Session, pinned: boolean) => Promise; /** Saves the chat's name, description and avatar. Absent hides Edit profile. */ onUpdateProfile?: UpdateSessionProfileFn | null | undefined; /** Saves a bot template in the workspace. Absent hides Save as bot template. */ onSaveBotTemplate?: | ((request: CreateBotTemplateRequest) => Promise) | null | undefined; /** Archives or restores this root session. Absent hides the action. */ onArchive?: ((session: Session, archived: boolean) => Promise) | undefined; /** * The signed-in person's mute on this session's replies. Absent hides the * action (sub-agents, people without an inbox, servers without it). */ repliesMute?: SessionRepliesMute | null | undefined; /** * This session's full access, when the viewer can see it on or give it. * Absent hides the shield and the menu action. */ adminAccess?: SessionAdminAccessControl | null | undefined; /** * Opens this chat's usage limit (Agent tab > Usage). Absent hides the menu * item, for servers without usage limits. */ onOpenUsageLimit?: ((() => void) | null) | undefined; /** The "Run on " control — a live component in production. */ sandboxSlot?: ReactNode | undefined; /** * Replaces the static provider mark when the session runs on a subscription * (Codex, Claude, SuperGrok): the same mark, clickable for the account and * its usage. Absent for other payment rails. */ accountSlot?: ReactNode | undefined; /** Compact session access state/menu, lazy-mounted by the route shell. */ accessSlot?: ReactNode | undefined; /** Leading control (the mobile hamburger); absent on desktop. */ leading?: ReactNode | undefined; /** * Model·effort·latency from the newest turn that durably emitted `turn.started`. * Historical — does not follow the composer next-turn picker. Falls back to * session creation defaults before any turn has admitted. */ lastStartedModel?: string | undefined; lastStartedReasoningEffort?: IntelligenceEffort | undefined; lastStartedLatencyMode?: LatencyMode | undefined; /** Billing rail: subscription account chip, or the mark for makers without a logo. */ billingClass?: BillingClass | undefined; /** Product model label (e.g. GPT-5.6 Luna). */ modelLabel?: string | undefined; modelLogoUrl?: string | undefined; /** * True while last-started policy and/or model catalog are still resolving. * Avoids flashing session defaults (wrong provider) before admitted truth. */ policyLoading?: boolean | undefined; }) { const uiEvents = useUiEventTarget("document"); const page = usePage(); const waiting = sessionInputWait({ ...session, status }); // A session the runtime could not start reads as stuck, not "Waiting on you". const displayStatus = sessionDisplayStatus({ status, admissionBlock: session.admissionBlock, }); const startup = useSessionStartup({ ...session, status }); const startupLabel = startup === "starting" ? "Starting" : startup === "delayed" || startup === "retrying" ? "Waiting to start" : undefined; const modelId = lastStartedModel?.trim() || session.model; const resolvedBilling: BillingClass = billingClass ?? (isCodexProductModel(modelId) ? "codex_subscription" : "opengeni_credits"); const resolvedModel = modelLabel?.trim() || modelDisplayName(modelId); const displayEffort: IntelligenceEffort = lastStartedReasoningEffort ?? session.reasoningEffort; const displayLatency: LatencyMode = lastStartedLatencyMode ?? session.latencyMode; // Subscription rails → clickable account chip, the same for every provider. // Other rails → static provider icon only (never invent a text // "Opengeni"/"BYOK" word). Don't key off `accountSlot != null`. const isSubscriptionRail = SUBSCRIPTION_RAILS.has(resolvedBilling); const policyBits = [ resolvedModel, labelEffort(displayEffort), displayLatency === "fast" ? "Fast" : displayLatency === "ultrafast" ? "Ultrafast" : displayLatency === "priority" ? "Priority" : null, ].filter((bit): bit is string => Boolean(bit)); const rename = useInlineRename(session, onRename); const pin = useSessionPinToggle(session, onPin); const context = useOptionalAppContext(); // Archiving is one-way, so an archived chat offers no archive action, and // only people who can control the chat archive it. const canArchive = Boolean(onArchive) && session.parentSessionId === null && !session.archived && (context ? archiveActionLabel(context, session) !== null : true); // An archived chat cannot be pinned. const canPin = !session.archived; const [grantAdminOpen, setGrantAdminOpen] = useState(false); const shareLinksFeature = useSessionUiFeature("shareLinks"); // Only the person who started a top-level chat can share it; the server // decides whether links are on at all and says so in the dialog. const canShare = shareLinksFeature && context !== null && session.parentSessionId === null && session.createdBy?.kind === "subject" && session.createdBy.subjectId === context.accessContext.subjectId; const [shareOpen, setShareOpen] = useState(false); const canEditProfile = Boolean(onUpdateProfile); const [profileOpen, setProfileOpen] = useState(false); const [saveTemplateOpen, setSaveTemplateOpen] = useState(false); // Menu actions that move focus (rename input, find field) run after the menu // has closed, so its focus restoration cannot steal focus back to the trigger. const afterMenuClose = useRef<(() => void) | null>(null); const chatOps = useChatOperations(); const findKeys = useActionShortcut("chat.find"); const copyLinkKeys = useActionShortcut("chat.copyLink"); const pinKeys = useActionShortcut("chat.pin"); const archiveKeys = useActionShortcut("chat.archive"); const panelKeys = useActionShortcut("view.workspacePanel"); const hasCrumb = Boolean(session.parentSessionId) || ancestors.length > 0 || Boolean(lineageError); // A chat started for a Slack agent says which one; its avatar is the agent's icon. const slackAgent = sessionSlackAgentInfo(session.metadata); const overflow = useSessionHeaderOverflow({ present: SESSION_HEADER_PARTS.filter((part) => { switch (part) { case "panel": return Boolean(onToggleInspector); case "access": return Boolean(accessSlot); case "fullAccess": return Boolean(adminAccess?.state.active); case "automations": return Boolean(onOpenAutomations); case "machine": return Boolean(sandboxSlot); case "site": return sessionSiteOrigin(session) !== null; case "slackAgent": return slackAgent !== null; case "accessKey": return keyAuthRequired; default: return true; } }), contentKey: sessionDisplayTitle(session), resetKey: session.id, frozen: rename.editing, }); // In the "…" menu instead of the row (see SESSION_HEADER_PARTS). const inMenu = (part: SessionHeaderPart) => overflow.collapsed.has(part); const part = overflow.partRef; // "Rename" from the ⌘K menu or the desktop menu bar edits this title. const startRenaming = rename.startEditing; useEffect(() => { const start = () => startRenaming(); uiEvents.addEventListener(RENAME_CURRENT_CHAT_EVENT, start); return () => uiEvents.removeEventListener(RENAME_CURRENT_CHAT_EVENT, start); }, [uiEvents, startRenaming]); const providerControl = isSubscriptionRail ? ( (accountSlot ?? ( )) ) : ( // The model maker's logo; the payment rail only when the maker has none. } /> ); return ( // An elevated band, not just canvas-with-a-hairline: reading as a real top // bar was the light-theme fix — a near-white header on a near-white canvas // needs its own surface + a crisp divider to look intentional (and it lifts // the dark bar a touch above the canvas too).
{leading} {/* Every chat's header is one row of the same height. A child chat's way back is a small line above its title, never beside it. The title keeps a readable width: when the row is too narrow, the least important parts move into the "…" menu (SESSION_HEADER_PARTS). */}
{/* A bot's avatar travels with its title. */} {session.avatar ? ( ) : null} void chatOps.copyLink(session)} />
{/* Below lg (or when the full badge has no room) the lifecycle is a dot beside the title. */} {accessSlot && !inMenu("access") ? ( {accessSlot} ) : null} {adminAccess?.state.active && !inMenu("fullAccess") ? ( setGrantAdminOpen(true)} /> ) : null} {sessionSiteOrigin(session) && !inMenu("site") ? ( ) : null} {slackAgent && !inMenu("slackAgent") ? ( Slack agent: {slackAgent.name} ) : null} {onOpenAutomations && !inMenu("automations") ? ( // The first to give way: its words shorten to its icon before // anything moves into the menu. The weight is high enough that // the title keeps every pixel until then (a sliver would already // truncate it). ) : null}
{/* Provider + model · effort · speed stay one cluster on the action side. */} {inMenu("model") ? null : (
{policyLoading ? ( ) : ( {providerControl} {policyBits.map((bit, index) => ( {index > 0 ? " · " : null} {bit} ))} )}
)} {/* Below lg, machine, find and pin live in the "…" menu. */} {sandboxSlot && !inMenu("machine") ? ( {sandboxSlot} ) : null} {inMenu("find") ? null : ( )} {inMenu("pin") || !canPin ? null : ( )} {pin.announcement} {inMenu("status") ? null : (
{/* Admission vs lifecycle are different axes, but showing both when control is Active (Running + Active) is redundant noise. When paused, admission is the headline — hide lifecycle so we don't imply the session is still "Running"/"Idle" under a pause gate. */} {!sessionControlPaused(session) ? ( waiting ? ( Waiting ) : ( ) ) : ( )}
)} Connection {connectionState}. {keyAuthRequired && !inMenu("accessKey") ? ( ) : null} {onToggleInspector && !inMenu("panel") ? ( ) : null} { const action = afterMenuClose.current; if (!action) return; afterMenuClose.current = null; event.preventDefault(); action(); }} > {onToggleInspector && inMenu("panel") ? ( { afterMenuClose.current = onToggleInspector; }} > {inspectorOpen ? : } {inspectorOpen ? "Hide workspace" : "Open workspace"} {panelKeys ? {panelKeys.label} : null} ) : null} { afterMenuClose.current = () => requestConversationFind(uiEvents); }} > Find {findKeys ? {findKeys.label} : null} { afterMenuClose.current = rename.startEditing; }} > Rename {canEditProfile ? ( { afterMenuClose.current = () => setProfileOpen(true); }} > Edit profile… ) : null} {onSaveBotTemplate ? ( { afterMenuClose.current = () => setSaveTemplateOpen(true); }} > Save as bot template… ) : null} void chatOps.copyLink(session)} > Copy link {copyLinkKeys ? ( {copyLinkKeys.label} ) : null} void copyTitle(sessionDisplayTitle(session))}> Copy title {canShare ? ( { afterMenuClose.current = () => setShareOpen(true); }} > Share… ) : null} {canPin ? ( pin.toggle()} > {session.pinned ? "Unpin" : "Pin"} {pinKeys ? {pinKeys.label} : null} ) : null} {currentPhoneAppPlatform() ? ( { page.assign(openInAppUrl(page.href())); }} > Open in app ) : null} {sandboxSlot ? (
{sandboxSlot}
) : null} {/* Parts with no room in the header row (SESSION_HEADER_PARTS). */} {accessSlot && inMenu("access") ? (
Access {accessSlot}
) : null} {onOpenAutomations && inMenu("automations") ? ( { afterMenuClose.current = onOpenAutomations; }} /> ) : null} {inMenu("site") ? : null} {slackAgent && inMenu("slackAgent") ? (
Slack agent: {slackAgent.name}
) : null} {keyAuthRequired && inMenu("accessKey") ? ( Clear access key ) : null} {repliesMute ? ( repliesMute.toggle()}> {repliesMute.muted ? : } {repliesMuteLabel(repliesMute)} ) : null} {onOpenUsageLimit ? ( { afterMenuClose.current = onOpenUsageLimit; }} > Usage limit ) : null} {adminAccess?.state.active && inMenu("fullAccess") ? ( <> setGrantAdminOpen(true)} runAfterClose={(action) => { afterMenuClose.current = action; }} /> ) : adminAccess?.state.active && adminAccess.state.canRevoke ? ( adminAccess.revoke()}> Turn off full access ) : adminAccess && !adminAccess.state.active && adminAccess.state.canGrant ? ( { afterMenuClose.current = () => setGrantAdminOpen(true); }} > Give full access… ) : null} {canArchive ? ( <> void onArchive?.(session, true)} > Archive {archiveKeys ? ( {archiveKeys.label} ) : null} ) : null}
{canShare && context ? ( ) : null} {onUpdateProfile && profileOpen ? ( ) : null} {onSaveBotTemplate && saveTemplateOpen ? ( { const created = await onSaveBotTemplate({ ...values, sourceSessionId: session.id }); toast.success("Bot template saved", { description: created.name, }); }} /> ) : null} {adminAccess ? ( ) : null}
); } /** * The automations that post into this chat: what they wait for in a few * words, every wait on hover, and their settings on click. A paused or * finished automation still links to its settings, marked inactive. Narrow * headers keep only the icon; its name always carries the whole wait. */ function AutomationWaitChip({ session, onOpen }: { session: Session; onOpen: () => void }) { const now = new Date(); const wait = sessionAutomationWaitWords(t, session, { now }); const lines = sessionAutomationWaitLines(t, session, { now }); const kind = wait?.kind ?? "none"; return (

{t("automations.wait.details.heading")}

    {lines.map((line) => (
  • {line.text}
  • ))}

{t("automations.wait.details.open")}

); } function AutomationWaitIcon({ kind }: { kind: "event" | "schedule" | "none" }) { return kind === "event" ? ( ) : kind === "schedule" ? ( ) : ( ); } /** The automation chip as a "…" menu item, for a header with no room for it. */ function AutomationWaitMenuItem({ session, onOpen }: { session: Session; onOpen: () => void }) { const wait = sessionAutomationWaitWords(t, session, { now: new Date() }); return ( {wait?.short ?? t("sessionChrome.automation")} ); } /** * Small-screen status: a dot beside the title, named for assistive tech. * `always` keeps it on wide screens too, when the full badge has no room. */ function CompactSessionStatus({ paused, waiting, status, label, always = false, }: { paused: boolean; waiting: boolean; status: SessionDisplayStatus; label?: string | undefined; always?: boolean | undefined; }) { const className = cn("inline-flex shrink-0 items-center", !always && "lg:hidden"); if (paused) { return ( Paused ); } if (waiting) { return ( Waiting ); } const name = label ?? SESSION_STATUS_META(t)[status].label; return ( {name} ); } /** Pause-only header chip (Active is not shown — lifecycle status covers “go”). */ function WorkstreamControlIndicator({ session }: { session: Session }) { const control = session.effectiveControl; if (control.state !== "paused" || session.status === "cancelled") { return null; } const blocker = control.primaryBlocker; const label = blocker?.kind === "workspace" ? "Workspace paused" : control.directState === "paused" || blocker?.sessionId === session.id ? "Paused here" : `Paused by ${blocker?.displayName ?? "parent"}`; return ( ); } /** Pin toggle shared by the desktop pin button and the phone "…" menu item. */ function useSessionPinToggle( session: Session, onPin: (session: Session, pinned: boolean) => Promise, ) { const [busy, setBusy] = useState(false); const [announcement, setAnnouncement] = useState(""); const announcementSequence = useRef(0); const announce = useCallback((message: string) => { announcementSequence.current += 1; setAnnouncement(pinLiveAnnouncement(message, announcementSequence.current)); }, []); const toggle = useCallback(() => { if (busy) return; const nextPinned = !session.pinned; setBusy(true); void onPin(session, nextPinned) .then((updated) => { announce( updated ? `Session ${nextPinned ? "pinned" : "unpinned"}.` : `Session was not ${nextPinned ? "pinned" : "unpinned"}.`, ); }) .catch(() => { announce(`Session was not ${nextPinned ? "pinned" : "unpinned"}.`); }) .finally(() => setBusy(false)); }, [announce, busy, onPin, session]); return { busy, toggle, announcement }; } /** * The session header title — display by default, click the title (or the * hover pencil / "…" > Rename) to rename inline. Prefers the durable session.title * (agent- or user-set), falling back to the initial message / "Untitled * session" exactly like the rail list. Enter saves, Esc cancels, blur saves; an * empty/unchanged value is a no-op cancel. The live title (context.session) * flows in through the session.title_set SSE event the react useSession hook * applies, so cross-client renames and agent titling reflect here without a * reload. The shared `useInlineRename` hook keeps this behaviour identical to * the rail row's rename. */ function SessionTitleEditor(props: { session: Session; rename: InlineRename; onCopyLink: () => void; }) { const display = sessionDisplayTitle(props.session); const rename = props.rename; const afterMenuClose = useRef<(() => void) | null>(null); if (rename.editing) { return ( // A calm in-place edit: same size and position as the display title, a // soft surface tint + hairline instead of a loud focus ring. The global // focus-ring rule is what painted the old blue box; opting out here keeps // the rename feeling like editing the text, not filling in a form field. rename.setDraft(event.target.value)} onBlur={() => void rename.commit()} onKeyDown={(event) => { if (event.key === "Enter") { event.preventDefault(); void rename.commit(); } else if (event.key === "Escape") { event.preventDefault(); rename.cancel(); } }} maxLength={SESSION_TITLE_MAX_LENGTH} aria-label="Session title" dir="auto" className="-mx-1.5 w-full min-w-0 truncate rounded-md bg-surface-2/70 px-1.5 text-[15px] font-semibold leading-6 tracking-[-0.01em] outline-hidden ring-1 ring-border-strong focus:outline-hidden focus-visible:outline-hidden" style={{ outline: "none" }} /> ); } return (
{/* Right-click (or long-press) the title to copy it or the chat's link. */} { // Rename starts once the menu has handed focus back, so the // field keeps it. const action = afterMenuClose.current; if (!action) return; afterMenuClose.current = null; event.preventDefault(); action(); }} > void copyTitle(display)}> Copy title Copy link { afterMenuClose.current = rename.startEditing; }} > Rename {/* The pencil earns its pixels only when relevant: hidden at rest and revealed on hover/focus. Touch screens rename by tapping the title (or "…" > Rename), so the title keeps the row's width. */}
); }