"use client"; import Link from "next/link"; import { useMemo, useState, type ReactNode } from "react"; import ReactMarkdown from "react-markdown"; import type { AlertEvent, ClassifierHitEvent, FlowPacket, IslandflowAiCompiledScreen, IslandflowAiPlanType, IslandflowAiRateLimitSnapshot, IslandflowAiReasoningEffort, IslandflowAiTaskKind, IslandflowAiTaskSnapshot, IslandflowAiTaskStatus, OptionFlowFilters, OptionPrint, SmartMoneyEvent, } from "@islandflow/types"; import { useDesktopAi } from "./desktop-ai"; const numberFormatter = new Intl.NumberFormat("en-US"); const usdFormatter = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 2, maximumFractionDigits: 4, }); const humanizeValue = (value: string | null | undefined): string => { if (!value) { return "Unknown"; } return value .replace(/_/g, " ") .replace(/\b\w/g, (char) => char.toUpperCase()); }; const formatTokens = (value: number): string => numberFormatter.format(value); const formatUsd = (value: number | null): string => value === null ? "Unavailable" : usdFormatter.format(value); const formatTimestamp = (value: number | null): string => { if (!value) { return "Not reported"; } return new Intl.DateTimeFormat("en-US", { dateStyle: "medium", timeStyle: "short", }).format(value); }; const formatPercent = (value: number): string => `${Math.round(value)}%`; const getTaskStatusLabel = (value: string): string => humanizeValue(value); type CopilotTaskCache = Record; const RUNNING_TASK_STATUSES: IslandflowAiTaskStatus[] = ["queued", "running"]; export const createCopilotTaskCacheKey = ( kind: IslandflowAiTaskKind, contextKey: string, ): string => `${kind}:${contextKey}`; export const getCachedCopilotTaskId = ( cache: CopilotTaskCache, kind: IslandflowAiTaskKind, contextKey: string, ): string | null => cache[createCopilotTaskCacheKey(kind, contextKey)] ?? null; export const shouldShowCopilotRegenerate = ( task: Pick | null, ): boolean => Boolean( task && task.status === "completed" && (task.text.trim().length > 0 || task.compiledScreen), ); export const isCopilotTaskRunning = ( task: Pick | null, ): boolean => Boolean(task && RUNNING_TASK_STATUSES.includes(task.status)); export const getCopilotTaskSurfaceState = ( task: Pick | null, ): "empty" | "running" | "completed" | "failed" | "cancelled" => { if (!task) { return "empty"; } if (RUNNING_TASK_STATUSES.includes(task.status)) { return "running"; } if (task.status === "completed") { return "completed"; } if (task.status === "failed") { return "failed"; } return "cancelled"; }; const getSmartMoneyContextKey = (event: SmartMoneyEvent): string => [event.underlying_id, event.source_ts, event.event_id].join(":"); type DesktopAiSettingsNotice = { title: string; body: string; }; export const getDesktopAiSettingsBridgeNotice = ( shellAvailable: boolean, bridgeAvailable: boolean, ): DesktopAiSettingsNotice | null => { if (!shellAvailable) { return { title: "Desktop app required", body: "Open Islandflow Desktop to connect ChatGPT, load managed models, and use native Copilot controls.", }; } if (!bridgeAvailable) { return { title: "Bridge unavailable in this window", body: "This Islandflow Desktop window is missing its native AI bridge, so login actions and model controls stay disabled until the bridge reconnects. Reload the window or restart Islandflow if this keeps happening.", }; } return null; }; export const getDesktopAiModelSelectLabel = ( shellAvailable: boolean, bridgeAvailable: boolean, loggedIn: boolean, modelCount: number, ): string => { if (!shellAvailable) { return "Desktop app required"; } if (!bridgeAvailable) { return "Bridge unavailable"; } if (!loggedIn) { return "Connect ChatGPT to load models"; } if (modelCount === 0) { return "Waiting for managed models"; } return "Use server default"; }; export const getDesktopAiModelListEmptyCopy = ( shellAvailable: boolean, bridgeAvailable: boolean, loggedIn: boolean, ): string => { if (!shellAvailable) { return "Open Islandflow Desktop to load managed model options."; } if (!bridgeAvailable) { return "Managed model options will appear here after the native AI bridge reconnects."; } if (!loggedIn) { return "Connect a ChatGPT or Codex account to load the managed model catalog."; } return "No model catalog has been reported yet."; }; export const getDesktopAiProfileBadgeLabel = ( selected: boolean, statusLabel: string, bridgeAvailable: boolean, ): string => { if (!bridgeAvailable) { return statusLabel; } return selected ? "Selected" : statusLabel; }; const findTask = ( tasks: T[], taskId: string | null, ): T | null => { if (!taskId) { return null; } return tasks.find((task) => task.taskId === taskId) ?? null; }; const getCompiledScreenSummary = ( compiled: IslandflowAiCompiledScreen, ): string[] => { const filters = compiled.compiledFilters; if (!filters) { return []; } const parts: string[] = []; if (filters.view) { parts.push(`View: ${filters.view}`); } if (filters.securityTypes?.length) { parts.push(`Security: ${filters.securityTypes.join(", ")}`); } if (filters.optionTypes?.length) { parts.push(`Options: ${filters.optionTypes.join(", ")}`); } if (filters.nbboSides?.length) { parts.push(`NBBO: ${filters.nbboSides.join(", ")}`); } if (typeof filters.minNotional === "number") { parts.push(`Min notional: $${numberFormatter.format(filters.minNotional)}`); } return parts; }; const CopilotPane = ({ title, eyebrow, actions, wide = false, children, }: { title: string; eyebrow?: string; actions?: ReactNode; wide?: boolean; children: ReactNode; }) => { return (
{eyebrow ?
{eyebrow}
: null}

{title}

{actions ? (
{actions}
) : null}
{children}
); }; const UsageBreakdown = ({ title, breakdown, normalizedCostUsd, turnCount, activeDays, }: { title: string; breakdown: { totalTokens: number; inputTokens: number; cachedInputTokens: number; outputTokens: number; reasoningOutputTokens: number; }; normalizedCostUsd: number | null; turnCount: number; activeDays: number; }) => { return (

{title}

{formatUsd(normalizedCostUsd)}
Total tokens {formatTokens(breakdown.totalTokens)}
Input {formatTokens(breakdown.inputTokens)}
Cached input {formatTokens(breakdown.cachedInputTokens)}
Output {formatTokens(breakdown.outputTokens)}
Reasoning {formatTokens(breakdown.reasoningOutputTokens)}
Turns {formatTokens(turnCount)}
Active days {formatTokens(activeDays)}
); }; const RateLimitBoard = ({ limit, }: { limit: IslandflowAiRateLimitSnapshot; }) => { return (
{limit.limitName ?? "Default rate window"}

{limit.planType ? `Plan ${humanizeValue(limit.planType)}` : "Plan not reported"}

{limit.reachedType ? ( {humanizeValue(limit.reachedType)} ) : null}
{limit.primary ? (
Primary {formatPercent(limit.primary.usedPercent)}

Resets {formatTimestamp(limit.primary.resetsAt)}

) : null} {limit.secondary ? (
Secondary {formatPercent(limit.secondary.usedPercent)}

Resets {formatTimestamp(limit.secondary.resetsAt)}

) : null}
{limit.creditsBalance || limit.unlimitedCredits !== null ? (

Credits:{" "} {limit.unlimitedCredits ? "unlimited" : limit.creditsBalance ? limit.creditsBalance : limit.hasCredits === false ? "none" : "not reported"}

) : null}
); }; const TaskOutput = ({ taskId, emptyMessage, onCancel, }: { taskId: string | null; emptyMessage: string; onCancel?: (taskId: string) => void; }) => { const { state } = useDesktopAi(); const task = findTask(state.tasks, taskId); const surfaceState = getCopilotTaskSurfaceState(task); if (!task) { return (

{emptyMessage}

); } return (
{task.title}

{task.subtitle} · {getTaskStatusLabel(task.status)}

{getTaskStatusLabel(task.status)}
{surfaceState === "running" ? (
) : null} {task.error ?

{task.error}

: null} {task.status === "cancelled" && !task.text ? (

This Copilot task was cancelled locally.

) : null} {task.text ? (
{task.text}
) : null} {task.compiledScreen ? ( ) : null}
); }; const CompiledScreenResult = ({ compiled, }: { compiled: IslandflowAiCompiledScreen; }) => { const summary = getCompiledScreenSummary(compiled); return (
{summary.length > 0 ? (
{summary.map((item) => ( {item} ))}
) : (

No filter fields were compiled from this prompt.

)} {compiled.unhandledClauses.length > 0 ? (
Unhandled clauses
{compiled.unhandledClauses.map((item) => (
{item}
))}
) : null}
); }; const AccountSummary = ({ loggedIn, email, planType, }: { loggedIn: boolean; email: string | null; planType: IslandflowAiPlanType | null; }) => { return (

Desktop-only official Codex bridge

Analyst Copilot

Managed ChatGPT login stays user-scoped, deterministic smart-money classification stays in charge, and every AI turn is tracked with exact token telemetry from the app-server.

Account {loggedIn ? (email ?? "Connected") : "Disconnected"}
Plan {loggedIn ? humanizeValue(planType) : "Not connected"}
); }; const LoginStatePanel = () => { const { bridgeAvailable, shellAvailable, state, loginWithBrowser, loginWithDeviceCode, cancelLogin, logout, } = useDesktopAi(); const [busyAction, setBusyAction] = useState(null); const [actionError, setActionError] = useState(null); const loginState = state.account.login; const actionsDisabled = busyAction !== null || !bridgeAvailable; const bridgeNotice = getDesktopAiSettingsBridgeNotice( shellAvailable, bridgeAvailable, ); const runAction = async (label: string, action: () => Promise) => { setBusyAction(label); setActionError(null); try { await action(); } catch (error) { setActionError(error instanceof Error ? error.message : String(error)); } finally { setBusyAction(null); } }; return ( {state.account.loggedIn ? ( ) : bridgeNotice ? ( shellAvailable ? ( ) : null ) : ( <> )} {(loginState.status === "browser_pending" || loginState.status === "device_code_pending") && !state.account.loggedIn ? ( ) : null} } > {bridgeNotice ? (
{bridgeNotice.title}

{bridgeNotice.body}

) : null}
Profile slots
{state.profiles.map((profile) => (
{profile.label}

{profile.description}

{getDesktopAiProfileBadgeLabel( profile.selected, profile.statusLabel, bridgeAvailable, )}
))}
Session status
Transport {humanizeValue(state.transportStatus)}
Auth mode {humanizeValue(state.account.authMode)}
OpenAI auth required {state.account.requiresOpenaiAuth ? "Yes" : "No"}
{state.transportError ? (

{state.transportError}

) : null} {loginState.message ? (

{loginState.message}

) : null} {loginState.status === "browser_pending" ? (
Browser login in progress

Finish the ChatGPT sign-in flow in your browser. Islandflow will update automatically.

) : null} {loginState.status === "device_code_pending" ? (
Device code
{loginState.userCode}

Visit {loginState.verificationUrl} in any browser and enter the code above.

) : null} {actionError ?

{actionError}

: null}
); }; export function DesktopAiSettingsRoute() { const { bridgeAvailable, shellAvailable, state, updatePreferences } = useDesktopAi(); const [busyPreference, setBusyPreference] = useState< "model" | "reasoning" | null >(null); const [preferenceError, setPreferenceError] = useState(null); const rateLimits = Object.values(state.rateLimitsByLimitId); const selectedModel = state.preferences.model ?? ""; const selectedReasoning = state.preferences.reasoningEffort ?? ""; const modelControlsNotice = getDesktopAiSettingsBridgeNotice( shellAvailable, bridgeAvailable, ); const modelSelectLabel = getDesktopAiModelSelectLabel( shellAvailable, bridgeAvailable, state.account.loggedIn, state.models.length, ); const modelListEmptyCopy = getDesktopAiModelListEmptyCopy( shellAvailable, bridgeAvailable, state.account.loggedIn, ); const savePreference = async ( key: "model" | "reasoning", next: Partial<{ model: string | null; reasoningEffort: IslandflowAiReasoningEffort | null; }>, ) => { setBusyPreference(key); setPreferenceError(null); try { await updatePreferences(next); } catch (error) { setPreferenceError( error instanceof Error ? error.message : String(error), ); } finally { setBusyPreference(null); } }; return (
{!shellAvailable ? (

AI controls are intentionally read-only in the browser build. Open Islandflow Desktop to use managed ChatGPT login, structured Copilot turns, and app-server token telemetry.

) : null}
{modelControlsNotice ? (
{modelControlsNotice.title}

{modelControlsNotice.body}

) : state.models.length === 0 ? (
Managed models are not loaded yet

{modelListEmptyCopy}

) : null}
{state.models.length === 0 ? (

{modelListEmptyCopy}

) : ( state.models.map((model) => (
{model.displayName}

{model.description}

{model.model} {model.pricing ? ( {formatUsd(model.pricing.inputUsdPer1MTokens)} / 1M input ) : null}
)) )}
{state.models.find((model) => model.model === state.preferences.model) ?.pricing ? (

Normalized estimates use current API pricing for the selected model, not your literal ChatGPT subscription bill.

) : null} {preferenceError ? (

{preferenceError}

) : null}
{rateLimits.length === 0 ? (

No rate-limit snapshots have been reported yet.

) : (
{rateLimits.map((limit) => ( ))}
)}
{state.usage.recentTurns.length === 0 ? (

No tracked turns yet.

) : (
{state.usage.recentTurns.map((turn) => (
{turn.taskTitle ?? "Ad hoc turn"}

{turn.model ?? "default"} ·{" "} {formatTimestamp(turn.updatedAt)}

{formatTokens(turn.breakdown.totalTokens)} tok {formatUsd(turn.normalizedCostUsd)}
))}
)}
{state.tasks.length === 0 ? (

No Copilot tasks have been run yet.

) : (
{state.tasks.map((task) => (
{task.title}

{task.subtitle} · {humanizeValue(task.model)}

{getTaskStatusLabel(task.status)}
))}
)}
); } export const requireDesktopActionCopy = ( shellAvailable: boolean, bridgeAvailable: boolean, loggedIn: boolean, ): string => { if (!shellAvailable) { return "This control is desktop-only. Open Islandflow Desktop to run Copilot tasks."; } if (!bridgeAvailable) { return "Islandflow Desktop is open, but this window is missing the native AI bridge. Reload the window or restart the app."; } if (!loggedIn) { return "Connect a ChatGPT or Codex account in Settings before running Copilot analysis."; } return ""; }; const SmartMoneyTaskButton = ({ label, kind, symbol, disabled, busyKind, selected, cached, onRun, }: { label: string; kind: IslandflowAiTaskKind; symbol: string; disabled: boolean; busyKind: IslandflowAiTaskKind | null; selected: boolean; cached: boolean; onRun: (kind: IslandflowAiTaskKind) => void; }) => { return ( ); }; export function SmartMoneyCopilotPanel({ event, flowPacket, evidencePrints, relatedPackets, }: { event: SmartMoneyEvent; flowPacket: FlowPacket | null; evidencePrints: OptionPrint[]; relatedPackets: FlowPacket[]; }) { const { bridgeAvailable, shellAvailable, state, runTask, cancelTask } = useDesktopAi(); const [busyKind, setBusyKind] = useState(null); const [selectedKind, setSelectedKind] = useState("smart-money-explain"); const [activeTaskId, setActiveTaskId] = useState(null); const [taskCache, setTaskCache] = useState({}); const [taskError, setTaskError] = useState(null); const contextKey = useMemo(() => getSmartMoneyContextKey(event), [event]); const activeTask = useMemo( () => findTask(state.tasks, activeTaskId), [state.tasks, activeTaskId], ); const disabledCopy = requireDesktopActionCopy( shellAvailable, bridgeAvailable, state.account.loggedIn, ); const actionsDisabled = !bridgeAvailable || !state.account.loggedIn; const handleRun = async (kind: IslandflowAiTaskKind, options?: { regenerate?: boolean }) => { setSelectedKind(kind); const cachedTaskId = getCachedCopilotTaskId(taskCache, kind, contextKey); const cachedTask = findTask(state.tasks, cachedTaskId); if (!options?.regenerate && cachedTask) { setActiveTaskId(cachedTask.taskId); setTaskError(null); return; } setBusyKind(kind); setTaskError(null); try { const result = await runTask({ kind: kind as | "smart-money-explain" | "smart-money-skeptic" | "smart-money-burst-summary" | "watchlist-synthesis", context: { event, flowPacket, evidencePrints, relatedPackets, }, }); setActiveTaskId(result.taskId); setTaskCache((current) => ({ ...current, [createCopilotTaskCacheKey(kind, contextKey)]: result.taskId, })); } catch (error) { setTaskError(error instanceof Error ? error.message : String(error)); } finally { setBusyKind(null); } }; const handleCancel = async (taskId: string) => { setTaskError(null); try { await cancelTask(taskId); } catch (error) { setTaskError(error instanceof Error ? error.message : String(error)); } }; const canRegenerate = shouldShowCopilotRegenerate(activeTask); return (
Analyst Copilot

Structured interpretation only, the deterministic classifier remains the source of truth.

AI settings
void handleRun(kind)} /> void handleRun(kind)} /> void handleRun(kind)} /> void handleRun(kind)} />
{canRegenerate ? (
) : null} {disabledCopy ?

{disabledCopy}

: null} {taskError ?

{taskError}

: null} void handleCancel(taskId)} />
); } export function ReplayCopilotPanel({ ticker, flowFilters, alerts, smartMoneyEvents, classifierHits, flowPackets, optionPrints, }: { ticker: string | null; flowFilters: OptionFlowFilters; alerts: AlertEvent[]; smartMoneyEvents: SmartMoneyEvent[]; classifierHits: ClassifierHitEvent[]; flowPackets: FlowPacket[]; optionPrints: OptionPrint[]; }) { const { bridgeAvailable, shellAvailable, state, runTask, cancelTask } = useDesktopAi(); const [activeTaskId, setActiveTaskId] = useState(null); const [busy, setBusy] = useState(false); const [taskError, setTaskError] = useState(null); const activeTask = useMemo( () => findTask(state.tasks, activeTaskId), [state.tasks, activeTaskId], ); const disabledCopy = requireDesktopActionCopy( shellAvailable, bridgeAvailable, state.account.loggedIn, ); const actionsDisabled = busy || !bridgeAvailable || !state.account.loggedIn; const handleRun = async () => { setBusy(true); setTaskError(null); try { const result = await runTask({ kind: "replay-postmortem", context: { ticker, flowFilters, alerts, smartMoneyEvents, classifierHits, flowPackets, optionPrints, }, }); setActiveTaskId(result.taskId); } catch (error) { setTaskError(error instanceof Error ? error.message : String(error)); } finally { setBusy(false); } }; const handleCancel = async (taskId: string) => { setTaskError(null); try { await cancelTask(taskId); } catch (error) { setTaskError(error instanceof Error ? error.message : String(error)); } }; const canRegenerate = shouldShowCopilotRegenerate(activeTask); return ( AI settings } >

Copilot uses the current replay slice only: ticker scope, flow filters, visible alerts, classifier hits, packets, and option prints.

{disabledCopy ?

{disabledCopy}

: null} {taskError ?

{taskError}

: null} void handleCancel(taskId)} />
); } export function ScreenCompilerPanel({ currentFilters, onApplyFilters, }: { currentFilters: OptionFlowFilters; onApplyFilters: (next: OptionFlowFilters) => void; }) { const { bridgeAvailable, shellAvailable, state, runTask, cancelTask } = useDesktopAi(); const [prompt, setPrompt] = useState(""); const [activeTaskId, setActiveTaskId] = useState(null); const [busy, setBusy] = useState(false); const [taskError, setTaskError] = useState(null); const activeTask = useMemo( () => findTask(state.tasks, activeTaskId), [state.tasks, activeTaskId], ); const disabledCopy = requireDesktopActionCopy( shellAvailable, bridgeAvailable, state.account.loggedIn, ); const actionsDisabled = busy || !bridgeAvailable || !state.account.loggedIn; const handleCompile = async () => { const trimmedPrompt = prompt.trim(); if (!trimmedPrompt) { setTaskError("Write a screen request first."); return; } setBusy(true); setTaskError(null); try { const result = await runTask({ kind: "screen-compile", context: { prompt: trimmedPrompt, currentFilters, }, }); setActiveTaskId(result.taskId); } catch (error) { setTaskError(error instanceof Error ? error.message : String(error)); } finally { setBusy(false); } }; const handleCancel = async (taskId: string) => { setTaskError(null); try { await cancelTask(taskId); } catch (error) { setTaskError(error instanceof Error ? error.message : String(error)); } }; const compiledFilters = activeTask?.compiledScreen?.compiledFilters ?? null; const canRegenerate = shouldShowCopilotRegenerate(activeTask); return ( AI settings } >