Open-source Grok Bot alternative for named AI teammates. Local-first desktop, web, and mobile clients with per-bot tools, instructions, and memory. Independent fork of T3 Code.
feat(web): add the bot roster, plugins catalog, and settings dialog
Leo Orel9515f5dde323
diff --git a/apps/mobile/src/features/usage/UsageRouteScreen.tsx b/apps/mobile/src/features/usage/UsageRouteScreen.tsxindex 817e6d7f9..ec842b780 100644--- a/apps/mobile/src/features/usage/UsageRouteScreen.tsx+++ b/apps/mobile/src/features/usage/UsageRouteScreen.tsx@@ -1,97 +1,42 @@-import { useNavigation } from "@react-navigation/native";-import type { DailyTotals, MergedUsage } from "@t3tools/shared/usageMerge";-import {- enumerateDays,- enumerateHourStarts,- formatCount,- formatDayShort,- formatHourShort,- formatPercent,- formatTokens,- formatUsd,- makeWindow,-} from "@t3tools/shared/usageFormat";-import { useMemo, useState } from "react";-import { Platform, Pressable, RefreshControl, ScrollView, View } from "react-native";+import type { UsagePlanWindow, UsageProviderPlanLimits } from "@t3tools/contracts";+import type { MergedUsage } from "@t3tools/shared/usageMerge";+import { makeWindow } from "@t3tools/shared/usageFormat";+import { useEffect, useState } from "react";+import { Platform, RefreshControl, ScrollView, View } from "react-native";import { useSafeAreaInsets } from "react-native-safe-area-context";+import { useNavigation } from "@react-navigation/native";import { AndroidScreenHeader } from "../../components/AndroidScreenHeader";import { AppText as Text } from "../../components/AppText";import { NativeStackScreenOptions } from "../../native/StackHeader";import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";import { SettingsSection } from "../settings/components/SettingsSection";-import { UsageDailyChart } from "./UsageDailyChart";-import type { UsageChartMetric } from "./usageChartData";-import { PROVIDER_LABEL, useProviderColors } from "./usageProviders";-const WINDOW_OPTIONS = [- { days: 1, label: "Past 24h" },- { days: 7, label: "7 days" },- { days: 30, label: "30 days" },- { days: 90, label: "90 days" },-] as const;--const CHART_HEIGHT = 180;+const PLAN_LABELS = {+ "openai-codex": "ChatGPT",+ anthropic: "Claude",+ cursor: "Cursor",+ xai: "Grok",+ "kimi-for-coding": "Kimi For Coding",+} as const;export function UsageRouteScreen() {const navigation = useNavigation();const insets = useSafeAreaInsets();- const [windowSelection, setWindowSelection] = useState(() => ({- days: 30,- window: makeWindow(30),- }));- const [metric, setMetric] = useState<UsageChartMetric>("cost");- const { days: windowDays, window } = windowSelection;- const isPast24Hours = windowDays === 1;- const { merged, environments, isPending, isPartial, refresh } = useUsage(window);-- const days = useMemo(- () => enumerateDays(window.sinceDay, window.untilDay),- [window.sinceDay, window.untilDay],- );- const chartDays = useMemo(- () =>- isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined- ? enumerateHourStarts(window.sinceTime, window.untilTime)- : days,- [days, isPast24Hours, window.sinceTime, window.untilTime],- );- const chartTotals = useMemo(- (): readonly DailyTotals[] =>- isPast24Hours- ? merged.hourly.map((hour) => ({- day: hour.hourStart,- costUsd: hour.costUsd,- totalTokens: hour.totalTokens,- byProvider: hour.byProvider,- }))- : merged.daily,- [isPast24Hours, merged.daily, merged.hourly],- );-- // The pull spinner tracks re-scans of environments that have answered- // before. The initial scan renders its own placeholder, and an unreachable- // environment stays pending forever — neither may pin the spinner on.+ const [usageWindow] = useState(() => makeWindow(30));+ const { merged, environments, isPending, isPartial, refresh } = useUsage(usageWindow);const refreshing = environments.some((entry) => entry.isPending && entry.summary !== null);- const selectWindow = (days: number) => {- setWindowSelection({- days,- window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),- });- };- const refreshWindow = () => {- const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");- if (- nextWindow.sinceDay === window.sinceDay &&- nextWindow.untilDay === window.untilDay &&- nextWindow.sinceTime === window.sinceTime &&- nextWindow.untilTime === window.untilTime- ) {- refresh();- } else {- setWindowSelection({ days: windowDays, window: nextWindow });- }- };+ const planLimits = merged.planLimits.filter((entry) => entry.status === "ok");++ useEffect(() => {+ const timer = setInterval(+ () => {+ refresh();+ },+ 5 * 60 * 1000,+ );+ return () => clearInterval(timer);+ }, [refresh]);return (<View collapsable={false} className="flex-1 bg-sheet">@@ -107,352 +52,78 @@ export function UsageRouteScreen() {className="flex-1"contentContainerClassName="gap-6 px-5 pt-4"contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}- refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refreshWindow} />}+ refreshControl={<RefreshControl refreshing={refreshing} onRefresh={refresh} />}>- <SegmentedControl- options={WINDOW_OPTIONS.map((option) => ({ value: option.days, label: option.label }))}- selected={windowDays}- onSelect={selectWindow}- />-<UsageCoverageNotice environments={environments} merged={merged} isPartial={isPartial} />{isPending ? (<Text className="py-16 text-center text-base text-foreground-muted">- Scanning provider transcripts…+ Reading plan limits…</Text>) : environments.length === 0 ? (<Text className="py-16 text-center text-base text-foreground-muted">Connect an environment to see usage.</Text>+ ) : planLimits.length === 0 ? (+ <Text className="py-16 text-center text-base text-foreground-muted">+ Connect a subscription in Settings to see plan limits.+ </Text>) : (- <>- <ChartCard- merged={merged}- days={chartDays}- daily={chartTotals}- metric={metric}- onMetricChange={setMetric}- sinceDay={window.sinceDay}- untilDay={window.untilDay}- isPast24Hours={isPast24Hours}- timeZone={window.timeZone}- />- <ProviderSection merged={merged} metric={metric} />- <TotalsSection merged={merged} isPast24Hours={isPast24Hours} />- <ModelsSection merged={merged} />- </>+ planLimits.map((limits) => <PlanCard key={limits.provider} limits={limits} />))}</ScrollView></View>);}-function SegmentedControl<Value extends number | string>(props: {- readonly options: readonly { readonly value: Value; readonly label: string }[];- readonly selected: Value;- readonly onSelect: (value: Value) => void;-}) {- return (- <View className="flex-row overflow-hidden rounded-full border-continuous bg-card">- {props.options.map((option) => {- const active = option.value === props.selected;- return (- <Pressable- key={String(option.value)}- accessibilityRole="button"- accessibilityState={{ selected: active }}- onPress={() => props.onSelect(option.value)}- className={- active- ? "flex-1 items-center rounded-full bg-subtle-strong py-2"- : "flex-1 items-center py-2"- }- >- <Text- className={- active ? "text-sm font-t3-medium text-foreground" : "text-sm text-foreground-muted"- }- >- {option.label}- </Text>- </Pressable>- );- })}- </View>- );-}--/** Headline figure, the animated daily chart, and its legend, in one card. */-function ChartCard(props: {- readonly merged: MergedUsage;- readonly days: readonly string[];- readonly daily: readonly DailyTotals[];- readonly metric: UsageChartMetric;- readonly onMetricChange: (metric: UsageChartMetric) => void;- readonly sinceDay: string;- readonly untilDay: string;- readonly isPast24Hours: boolean;- readonly timeZone: string;-}) {- const { merged, metric } = props;- const colors = useProviderColors();- const hasActivity = props.daily.some((period) => period.totalTokens > 0);+function PlanCard(props: { readonly limits: UsageProviderPlanLimits }) {+ const title =+ props.limits.plan === null+ ? PLAN_LABELS[props.limits.provider]+ : `${PLAN_LABELS[props.limits.provider]} · ${props.limits.plan}`;return (- <View className="gap-4 rounded-[24px] border-continuous bg-card p-4">- <View className="flex-row items-start justify-between gap-3">- <View className="min-w-0 flex-1 gap-0.5">- <Text className="text-sm text-foreground-muted">- {metric === "cost" ? "Raw token cost" : "Processed tokens"}- </Text>- <Text className="text-4xl font-t3-bold tabular-nums text-foreground">- {metric === "cost" ? `${formatUsd(merged.costUsd)}*` : formatTokens(merged.totalTokens)}- </Text>- <Text className="text-sm text-foreground-muted">- {metric === "cost"- ? "* if billed at full API rate"- : `Across ${formatCount(merged.sessions)} sessions`}- </Text>- </View>- <MetricToggle metric={metric} onChange={props.onMetricChange} />- </View>-- {hasActivity ? (- <UsageDailyChart- days={props.days}- daily={props.daily}- metric={metric}- height={CHART_HEIGHT}- />+ <SettingsSection title={title} card>+ {props.limits.windows.length === 0 ? (+ <Text className="p-4 text-base text-foreground-muted">No limit data yet.</Text>) : (- <View style={{ height: CHART_HEIGHT }} className="items-center justify-center">- <Text className="text-base text-foreground-muted">No activity in this window.</Text>- </View>+ props.limits.windows.map((window, index) => (+ <PlanWindowRow+ key={`${window.kind}:${window.label}`}+ window={window}+ first={index === 0}+ />+ )))}-- <View className="flex-row items-center justify-between">- <Text className="text-xs text-foreground-tertiary">- {props.isPast24Hours- ? formatHourShort(props.days[0] ?? "", props.timeZone)- : formatDayShort(props.sinceDay)}- </Text>- <View className="flex-row items-center gap-4">- {merged.providers.map((provider) => (- <View key={provider.provider} className="flex-row items-center gap-1.5">- <View- className="size-2 rounded-full"- style={{ backgroundColor: colors[provider.provider] }}- />- <Text className="text-xs text-foreground-muted">- {PROVIDER_LABEL[provider.provider]}- </Text>- </View>- ))}- </View>- <Text className="text-xs text-foreground-tertiary">- {props.isPast24Hours- ? formatHourShort(props.days[props.days.length - 1] ?? "", props.timeZone)- : formatDayShort(props.untilDay)}- </Text>- </View>- </View>- );-}--function MetricToggle(props: {- readonly metric: UsageChartMetric;- readonly onChange: (metric: UsageChartMetric) => void;-}) {- return (- <View className="flex-row overflow-hidden rounded-full bg-subtle">- {(["cost", "tokens"] as const).map((option) => {- const active = option === props.metric;- return (- <Pressable- key={option}- accessibilityRole="button"- accessibilityState={{ selected: active }}- onPress={() => props.onChange(option)}- className={active ? "rounded-full bg-subtle-strong px-3 py-1.5" : "px-3 py-1.5"}- >- <Text- className={- active- ? "text-xs font-t3-medium uppercase text-foreground"- : "text-xs uppercase text-foreground-muted"- }- >- {option}- </Text>- </Pressable>- );- })}- </View>- );-}--function ProviderSection(props: {- readonly merged: MergedUsage;- readonly metric: UsageChartMetric;-}) {- const { merged, metric } = props;- const colors = useProviderColors();- if (merged.providers.length === 0) return null;-- // Ranked by whatever the toggle is showing, so the rows always descend.- // .sort() on a copy, not .toSorted(): Hermes doesn't ship the ES2023 method.- const ordered = [...merged.providers].sort((a, b) =>- metric === "cost" ? b.costUsd - a.costUsd : b.totalTokens - a.totalTokens,- );-- return (- <SettingsSection title="Providers" card>- {ordered.map((provider, index) => {- const share = metric === "cost" ? provider.costShare : provider.tokenShare;- return (- <View- key={provider.provider}- className={index === 0 ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}- >- <View className="flex-row items-baseline justify-between gap-3">- <View className="flex-row items-center gap-2">- <View- className="size-2.5 rounded-full"- style={{ backgroundColor: colors[provider.provider] }}- />- <Text className="text-lg text-foreground">{PROVIDER_LABEL[provider.provider]}</Text>- </View>- <Text className="text-lg tabular-nums text-foreground">- {metric === "cost"- ? formatUsd(provider.costUsd)- : formatTokens(provider.totalTokens)}- </Text>- </View>- <View className="h-1 flex-row overflow-hidden rounded-full bg-subtle">- <View- className="h-full rounded-full"- style={{ flex: share, backgroundColor: colors[provider.provider] }}- />- <View style={{ flex: 1 - share }} />- </View>- <Text className="text-sm text-foreground-muted">- {metric === "cost"- ? `${formatPercent(share)} of cost · ${formatTokens(provider.totalTokens)} tokens`- : `${formatPercent(share)} of tokens · ${formatUsd(provider.costUsd)}`}- </Text>- </View>- );- })}</SettingsSection>);}-function TotalsSection(props: { readonly merged: MergedUsage; readonly isPast24Hours: boolean }) {- const { merged } = props;- const activePeriods = (props.isPast24Hours ? merged.hourly : merged.daily).filter(- (period) => period.totalTokens > 0,- ).length;- const periodAverage = activePeriods === 0 ? 0 : merged.totalTokens / activePeriods;- const observedInput = merged.uncachedInputTokens + merged.cachedInputTokens;- const cachedShare = observedInput === 0 ? 0 : merged.cachedInputTokens / observedInput;-+function PlanWindowRow(props: { readonly window: UsagePlanWindow; readonly first: boolean }) {+ const remaining = Math.min(100, Math.max(0, 100 - props.window.usedPercent));return (- <SettingsSection title="Totals" card>- <View className="flex-row flex-wrap">- <MetricCell- label="Processed tokens"- value={formatTokens(merged.totalTokens)}- detail={`${formatTokens(periodAverage)} per active ${props.isPast24Hours ? "hour" : "day"}`}- />- <MetricCell- label="Cache savings"- value={formatUsd(merged.costQuality.cacheSavingsUsd)}- detail={- merged.costUsd > 0- ? `${(merged.costQuality.cacheSavingsUsd / merged.costUsd).toFixed(1)}x the raw cost`- : "vs full input rates"- }- />- <MetricCell- label="Cached input"- value={formatTokens(merged.cachedInputTokens)}- detail={`${formatPercent(cachedShare)} of observed input`}- />- <MetricCell- label="Uncached input"- value={formatTokens(merged.uncachedInputTokens)}- detail={`${formatTokens(merged.cacheCreationTokens)} cache writes`}- />- <MetricCell- label="Output"- value={formatTokens(merged.outputTokens)}- detail={`incl. ${formatTokens(merged.reasoningTokens)} reasoning`}- />- <MetricCell- label="Unpriced"- value={formatPercent(merged.costQuality.unpricedShare)}- detail="of records, excluded from cost"- />+ <View className={props.first ? "gap-2 p-4" : "gap-2 border-t border-border-subtle p-4"}>+ <View className="flex-row items-baseline justify-between gap-3">+ <Text className="text-lg text-foreground">{props.window.label}</Text>+ <Text className="text-lg tabular-nums text-foreground">{Math.round(remaining)}% left</Text></View>- </SettingsSection>- );-}--function MetricCell(props: {- readonly label: string;- readonly value: string;- readonly detail: string;-}) {- return (- <View className="w-1/2 gap-0.5 p-4">- <Text className="text-sm text-foreground-muted">{props.label}</Text>- <Text className="text-xl font-t3-medium tabular-nums text-foreground">{props.value}</Text>- <Text className="text-xs text-foreground-tertiary">{props.detail}</Text>+ <View className="h-1.5 overflow-hidden rounded-full bg-subtle">+ <View className="h-full bg-foreground" style={{ width: `${remaining}%` }} />+ </View>+ <Text className="text-sm text-foreground-muted">{formatReset(props.window.resetsAt)}</Text></View>);}-function ModelsSection(props: { readonly merged: MergedUsage }) {- const { merged } = props;- const colors = useProviderColors();- if (merged.models.length === 0) return null;-- return (- <SettingsSection title="By model" card>- {merged.models.map((model, index) => (- <View- key={`${model.provider}:${model.model}`}- className={- index === 0- ? "flex-row items-center gap-3 p-4"- : "flex-row items-center gap-3 border-t border-border-subtle p-4"- }- >- <View- className="size-2.5 shrink-0 rounded-full"- style={{ backgroundColor: colors[model.provider] }}- />- <View className="min-w-0 flex-1 gap-0.5">- <Text className="text-base text-foreground" numberOfLines={1}>- {model.model}- </Text>- <Text className="text-sm text-foreground-muted">- {formatPercent(model.costShare)} of cost · {formatTokens(model.totalTokens)} tokens- </Text>- </View>- <Text className="text-base tabular-nums text-foreground">{formatUsd(model.costUsd)}</Text>- </View>- ))}- </SettingsSection>- );+function formatReset(resetsAt: string | null): string {+ if (resetsAt === null) return "Reset time unknown";+ const deltaMs = Date.parse(resetsAt) - Date.now();+ if (Number.isNaN(deltaMs) || deltaMs <= 0) return "Resets soon";+ const hours = Math.round(deltaMs / (60 * 60 * 1000));+ if (hours < 48) return `Resets in ${hours}h`;+ return `Resets in ${Math.round(hours / 24)}d`;}-/**- * Says plainly when the totals are incomplete: an environment still answering,- * one that failed, or one whose transcripts another environment already- * reported.- */function UsageCoverageNotice(props: {readonly environments: readonly EnvironmentUsageStatus[];readonly merged: MergedUsage;@@ -462,13 +133,7 @@ function UsageCoverageNotice(props: {const stale = props.environments.filter((environment) =>props.merged.staleEnvironments.includes(environment.environmentId),);- const duplicateSources = props.merged.duplicateSources;- if (- failed.length === 0 &&- stale.length === 0 &&- duplicateSources.length === 0 &&- !props.isPartial- ) {+ if (failed.length === 0 && stale.length === 0 && !props.isPartial) {return null;}@@ -476,7 +141,7 @@ function UsageCoverageNotice(props: {<View className="gap-1 rounded-[16px] border-continuous bg-card px-4 py-3">{props.isPartial ? (<Text className="text-sm text-foreground-muted">- Some environments are still reporting. Totals are partial.+ Some environments are still reporting.</Text>) : null}{failed.map((environment) => (@@ -489,12 +154,6 @@ function UsageCoverageNotice(props: {{environment.label} runs an older server version and is excluded from totals.</Text>))}- {duplicateSources.length > 0 ? (- <Text className="text-sm text-foreground-muted">- Counted once across environments sharing a transcript directory:{" "}- {duplicateSources.join(", ")}- </Text>- ) : null}</View>);}diff --git a/apps/mobile/src/lib/mobileTheme.test.ts b/apps/mobile/src/lib/mobileTheme.test.tsindex d5744952b..6d3bb378d 100644--- a/apps/mobile/src/lib/mobileTheme.test.ts+++ b/apps/mobile/src/lib/mobileTheme.test.ts@@ -63,6 +63,7 @@ describe("mobile themes", () => {});it("shares all built-in desktop palettes", () => {+ expect(BUILT_IN_THEME_IDS).toContain("akeru-paper");expect(BUILT_IN_THEMES.map((theme) => theme.id)).toEqual(BUILT_IN_THEME_IDS);for (const themeId of BUILT_IN_THEME_IDS) {expect(getMobileThemeVariables(themeId, "light")["--color-screen"]).toMatch(/^#/);diff --git a/apps/web/THIRD_PARTY_NOTICES.md b/apps/web/THIRD_PARTY_NOTICES.mdindex c9a675ef4..aca5d8f59 100644--- a/apps/web/THIRD_PARTY_NOTICES.md+++ b/apps/web/THIRD_PARTY_NOTICES.md@@ -1,5 +1,26 @@# Third-Party Notices+## Provider icons++The provider SVGs in `public/provider-icons/` come from+[models.dev](https://models.dev/).++Copyright (c) 2025 models.dev++Licensed under the MIT License. The full license text is available in the+upstream repository: <https://github.com/anomalyco/models.dev/blob/dev/LICENSE>.++## Plugin logos++The brand and product logos in `public/plugin-logos/` come from+[SVGL](https://svgl.app/), [Simple Icons](https://simpleicons.org/), and the+products' official sites. They identify their respective plugins. All names,+logos, and trademarks remain the property of their owners.++Simple Icons is available under CC0 1.0. SVGL is available under the MIT+License. Official-site favicons retain their original ownership and trademark+terms.+## vscode-iconsThe custom file icon symbols in `src/pierre-icons.ts` are adapted from thediff --git a/apps/web/components.json b/apps/web/components.jsonindex 5977a2b06..08b0a68f5 100644--- a/apps/web/components.json+++ b/apps/web/components.json@@ -23,6 +23,7 @@},"registries": {"@coss": "https://coss.com/ui/r/{name}.json",- "@spell": "https://spell.sh/r/{name}.json"+ "@spell": "https://spell.sh/r/{name}.json",+ "@dither-kit": "https://tripwire.sh/r/{name}.json"}}diff --git a/apps/web/dither-kit.json b/apps/web/dither-kit.jsonnew file mode 100644index 000000000..cd6c7723e--- /dev/null+++ b/apps/web/dither-kit.json@@ -0,0 +1,152 @@+{+ "$schema": "https://tripwire.sh/schema/dither-kit.json",+ "lockfileVersion": 1,+ "registry": "https://tripwire.sh",+ "mode": "source",+ "components": {+ "area-chart": {+ "version": "0.1.0",+ "hash": "sha256:197d088204a38580fec861579c89e8c5aff7fe158222ce9b7a1a4b0a605e415e",+ "files": [+ {+ "path": "components/dither-kit/area-chart.tsx",+ "hash": "sha256:307883b537e005386a8090499eaf3ea636767a10235271181cb089c3477eab1e"+ },+ {+ "path": "components/dither-kit/area.tsx",+ "hash": "sha256:ecfb990f9083dd4c813eb431e3674822b7272076294de4ae038e81552d678532"+ },+ {+ "path": "components/dither-kit/cartesian-canvas.tsx",+ "hash": "sha256:180a1525cbe10ec35bc79f689bd018cfdf115ebb4e1e6b1ff31d4bd37ecc6f09"+ },+ {+ "path": "components/dither-kit/sparkline.tsx",+ "hash": "sha256:b5dab0b68af7ebc976ec51a74776761ac26d79f4aacd9c453a6e79c49e8d11ff"+ }+ ]+ },+ "bar-chart": {+ "version": "0.1.0",+ "hash": "sha256:fb4a2e9bba84e3558e0e162de42eaf07a741557bfa43167c0e319cdfa75acd0d",+ "files": [+ {+ "path": "components/dither-kit/bar-canvas.tsx",+ "hash": "sha256:80ed40b87eb3dbf3d9f768cf42b3b55f4f738db8b193c1a616f7abf525d83f87"+ },+ {+ "path": "components/dither-kit/bar-chart.tsx",+ "hash": "sha256:e19ce3540f15756aba615eb19072aeec81d8ac71e51219691cc1d0be004c18bb"+ },+ {+ "path": "components/dither-kit/bar.tsx",+ "hash": "sha256:2904ff1b0813ae20b976f5a78d57a314729ea3e890b18ba762bbb46d2f550057"+ }+ ]+ },+ "core": {+ "version": "0.1.0",+ "hash": "sha256:c2d71baa1313a822cbef24de39414e21df7029fc80ad297ab8471d3d727235e9",+ "files": [+ {+ "path": "components/dither-kit/block-legend.tsx",+ "hash": "sha256:4ddf215c6187ac0ca2640501c0342699bc210b33c1cec1d3e138ee3d38f77433"+ },+ {+ "path": "components/dither-kit/cartesian-root.tsx",+ "hash": "sha256:6b5297d75de22ae5a0fc1960bef0419a4984b54ff493e7acd527aa0ccb150098"+ },+ {+ "path": "components/dither-kit/chart-context.tsx",+ "hash": "sha256:955657f21fdbf7e04b80917be52b7c3839eb535b8d07f15053c06d9320683d8f"+ },+ {+ "path": "components/dither-kit/common-context.tsx",+ "hash": "sha256:aafb26404977148144a3d81da81a678d5956e14024f394ccdc7ae881dd07e52a"+ },+ {+ "path": "components/dither-kit/dither-paint.ts",+ "hash": "sha256:1bcd3d7de3ae3091caf63ed4c2c862d80d1899c9b55a70078acb12f7b44e51c7"+ },+ {+ "path": "components/dither-kit/dot.tsx",+ "hash": "sha256:207bf90662237064940d14a4d8411135d75027b97a9582c0e61c8af74ea5d65a"+ },+ {+ "path": "components/dither-kit/grid.tsx",+ "hash": "sha256:ad09d80b3898a4d3f588ff1f2f4f82984864c3918cb09d31350be6ac18d2446f"+ },+ {+ "path": "components/dither-kit/legend.tsx",+ "hash": "sha256:2a067ebdc484c7bd9efb2afc4e8a0aa6718a14ec44ccd7bb94c871d192e501e6"+ },+ {+ "path": "components/dither-kit/lib.ts",+ "hash": "sha256:41493601eb53a70f7629f6e50bad233f7185eaad42ba2397ca56ac1afcf1bb5f"+ },+ {+ "path": "components/dither-kit/palette.ts",+ "hash": "sha256:fd020c230ad818a5d9d6dfdfcb6ef50b0dba012c77f44f1a61449fc9a65947f7"+ },+ {+ "path": "components/dither-kit/polar-context.tsx",+ "hash": "sha256:514ac9a4984b036598a14ecd7acc29ee121e9259c8a85309d7ed3c1e22af6831"+ },+ {+ "path": "components/dither-kit/polar-root.tsx",+ "hash": "sha256:63cecb6193ce3cd296b93b018e2441ccdefcc055cdc31bf131c808f0cf0c0c52"+ },+ {+ "path": "components/dither-kit/polar.ts",+ "hash": "sha256:3ad3f99bac2ee21e6580abd6903720af11cedcb8d8c69a06c40690be6229672c"+ },+ {+ "path": "components/dither-kit/reference-line.tsx",+ "hash": "sha256:b0df8cf1144ab56fcce577bac4a39e06d9215a1fdf81bb112a4190a0445b138b"+ },+ {+ "path": "components/dither-kit/scales.ts",+ "hash": "sha256:62ec74acdd3e335b959423a228b47edd70c14f07a468a385d039f5c6b66ebc2b"+ },+ {+ "path": "components/dither-kit/series-context.tsx",+ "hash": "sha256:1802f1f488cc46542294f533c55fae03a4b067feca0761df75ce21de8a6a429a"+ },+ {+ "path": "components/dither-kit/tooltip.tsx",+ "hash": "sha256:d053ac2135c6f29d011cb0a83be29a797f8954ccbb02916402d2d3c2a52b17f2"+ },+ {+ "path": "components/dither-kit/use-chart-dimensions.ts",+ "hash": "sha256:74b7f2a08cce5b891348eed845fc8c218ed16fce362ef4f35587ec4cc864c834"+ },+ {+ "path": "components/dither-kit/x-axis.tsx",+ "hash": "sha256:7997bd96c341816a0f1cc6f966ad386fedc78be39e51201fa368dab1fd943d62"+ },+ {+ "path": "components/dither-kit/y-axis.tsx",+ "hash": "sha256:96d8cad3d7ca87a2a6f092399a60ba2f32612413a190f2885da67854229cdeff"+ }+ ]+ },+ "pie-chart": {+ "version": "0.1.0",+ "hash": "sha256:2c08ce4e2ebe3b522541b38f3e37d2b124ab7692c6501225a3558dbf3ea964ca",+ "files": [+ {+ "path": "components/dither-kit/pie-canvas.tsx",+ "hash": "sha256:bcf6f1d8024448b55a3a198afad0ee5db002b2748c5282bb27679422c6a6c2bf"+ },+ {+ "path": "components/dither-kit/pie-chart.tsx",+ "hash": "sha256:2dae2f8e6193e0bca31164ba7d7b829cc5295533cdb207783d6bdb4e346d2c13"+ },+ {+ "path": "components/dither-kit/pie.tsx",+ "hash": "sha256:1e44525a3119913b042b660be50c9c2c0e34a265ee8ed0aa32c65ce4ce9fd655"+ }+ ]+ }+ }+}diff --git a/apps/web/package.json b/apps/web/package.jsonindex b73eefc8d..babe0cfba 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -20,7 +20,11 @@"@dnd-kit/sortable": "^10.0.0","@dnd-kit/utilities": "^3.2.2","@effect/atom-react": "catalog:",+ "@fontsource-variable/geist": "^5.3.0",+ "@fontsource-variable/geist-mono": "^5.3.0","@formkit/auto-animate": "^0.9.0",+ "@hugeicons/core-free-icons": "^4.3.0",+ "@hugeicons/react": "^1.1.10","@legendapp/list": "catalog:","@lexical/react": "^0.41.0","@noble/hashes": "catalog:",@@ -32,14 +36,20 @@"@tanstack/react-pacer": "^0.19.4","@tanstack/react-router": "^1.160.2","class-variance-authority": "^0.7.1",+ "clsx": "^2.1.1","culori": "^4.0.2",+ "d3-scale": "^4.0.2",+ "d3-shape": "^3.2.0","effect": "catalog:","heic-to": "^1.5.2","jose": "catalog:","jsonc-parser": "3.3.1","jszip": "3.10.1",+ "katex": "^0.18.4","lexical": "^0.41.0","lucide-react": "^0.564.0",+ "mermaid": "^11.17.2",+ "motion": "^13.1.1","react": "19.2.6","react-dom": "19.2.6","react-markdown": "^10.1.0",@@ -47,6 +57,7 @@"rehype-sanitize": "^6.0.0","remark-breaks": "^4.0.0","remark-gfm": "^4.0.1",+ "remark-math": "^6.0.0","tailwind-merge": "^3.4.0","zustand": "^5.0.11"},@@ -59,6 +70,8 @@"@types/babel__core": "^7.20.5","@types/compression": "^1.8.1","@types/culori": "^4.0.1",+ "@types/d3-scale": "^4.0.9",+ "@types/d3-shape": "^3.2.0","@types/react": "~19.2.14","@types/react-dom": "~19.2.3","@vercel/config": "^0.3.0",@@ -66,6 +79,7 @@"babel-plugin-react-compiler": "1.0.0","compression": "^1.8.1","msw": "2.12.11",+ "react-grab": "^0.2.0","tailwindcss": "^4.0.0","vite": "catalog:","vite-plus": "catalog:"diff --git a/apps/web/public/plugin-logos/context-dark.png b/apps/web/public/plugin-logos/context-dark.pngnew file mode 100644index 000000000..a0d4aa9cfBinary files /dev/null and b/apps/web/public/plugin-logos/context-dark.png differdiff --git a/apps/web/public/plugin-logos/context.png b/apps/web/public/plugin-logos/context.pngnew file mode 100644index 000000000..a0d4aa9cfBinary files /dev/null and b/apps/web/public/plugin-logos/context.png differdiff --git a/apps/web/public/plugin-logos/exa.svg b/apps/web/public/plugin-logos/exa.svgnew file mode 100644index 000000000..730dc4a66--- /dev/null+++ b/apps/web/public/plugin-logos/exa.svg@@ -0,0 +1,6 @@+<svg width="129" height="129" viewBox="0 0 129 129" fill="none" xmlns="http://www.w3.org/2000/svg">+<path fill-rule="evenodd" clip-rule="evenodd" d="M106.417 9.30741C106.417 9.57392 106.324 9.83227 106.155 10.0388L61.5395 64.5L106.155 118.96C106.324 119.166 106.417 119.425 106.417 119.691V127.843C106.417 128.482 105.897 129 105.255 129H1.16175C0.520132 129 0 128.482 0 127.843V1.15695C0 0.517982 0.520131 0 1.16174 0H105.255C105.897 0 106.417 0.517984 106.417 1.15695V9.30741ZM19.0364 116.382H87.6921L53.363 74.4795L19.0364 116.382ZM12.6699 104.192L40.1426 70.6585H12.6699V104.192ZM12.6699 58.0409H39.8964L12.6699 24.8064V58.0409ZM53.363 54.5193L87.6921 12.6176H19.0364L53.363 54.5193Z" fill="#0143D9"/>+<path d="M176.198 117.65C166.094 117.65 157.323 115.553 149.886 111.36C142.589 107.167 136.905 101.017 132.835 92.9109C128.906 84.8045 126.941 75.0208 126.941 63.5599C126.941 53.3569 128.976 44.2022 133.046 36.0957C137.256 27.9892 143.01 21.6298 150.307 17.0175C157.744 12.4052 166.024 10.099 175.146 10.099C185.109 10.099 193.599 12.3353 200.616 16.8078C207.633 21.1406 212.965 27.3602 216.614 35.4667C220.263 43.4334 222.087 52.8677 222.087 63.7695V66.1766C222.087 66.8156 221.567 67.3336 220.925 67.3336H145.044C145.185 74.881 146.588 81.3802 149.254 86.8311C152.061 92.282 155.78 96.475 160.411 99.4101C165.182 102.205 170.515 103.603 176.409 103.603C183.285 103.603 189.179 102.066 194.091 98.9908C198.779 95.9225 201.741 91.008 202.977 84.2471C203.08 83.6853 203.565 83.267 204.139 83.267H219.737C220.429 83.267 220.969 83.8669 220.871 84.5494C220.038 90.3376 217.988 95.6406 214.72 100.458C211.211 105.63 206.159 109.823 199.564 113.037C193.108 116.112 185.32 117.65 176.198 117.65ZM202.721 54.5449C202.721 45.3203 200.265 37.9825 195.354 32.5316C190.582 27.0807 183.846 24.3552 175.146 24.3552C166.866 24.3552 160.06 27.2205 154.727 32.9509C149.395 38.6814 146.377 45.8794 145.676 54.5449H202.721Z" fill="black"/>+<path d="M364.585 117.65C358.13 117.65 352.236 116.392 346.903 113.876C341.571 111.36 337.361 107.796 334.273 103.184C331.186 98.4317 329.642 92.9808 329.642 86.8311C329.642 77.7462 332.73 70.688 338.904 65.6564C345.219 60.485 353.359 57.0607 363.322 55.3835L385.004 52.0291C387.67 51.6098 389.705 51.0507 391.108 50.3519C392.652 49.5133 393.704 48.465 394.266 47.2071C394.967 45.8095 395.318 44.0624 395.318 41.9659C395.318 36.515 393.424 32.2521 389.635 29.1772C385.846 25.9626 380.934 24.3552 374.9 24.3552C367.322 24.3552 361.498 26.2421 357.428 30.0158C353.595 33.4387 351.443 38.1016 350.971 44.0046C350.922 44.622 350.412 45.1106 349.79 45.1106H334.014C333.353 45.1106 332.823 44.5605 332.872 43.9032C333.312 38.0771 335.042 32.6792 338.062 27.7096C341.29 22.3985 345.921 18.1356 351.955 14.921C358.13 11.7063 365.287 10.099 373.426 10.099C381.706 10.099 388.793 11.6364 394.687 14.7113C400.721 17.7862 405.282 22.1888 408.369 27.9193C411.456 33.6497 413 40.4284 413 48.2554V113.348C413 113.987 412.48 114.505 411.838 114.505H396.901C396.259 114.505 395.739 113.987 395.739 113.348V109.473C395.739 108.076 395.739 106.678 395.739 105.28C395.739 103.743 395.739 102.275 395.739 100.878C393.213 106.189 389.214 110.312 383.741 113.247C378.408 116.182 372.023 117.65 364.585 117.65ZM367.111 103.603C372.444 103.603 377.215 102.485 381.425 100.249C385.775 97.8727 389.143 94.6581 391.529 90.6048C394.055 86.4118 395.318 81.6597 395.318 76.3486V61.4634C394.757 62.302 393.564 63.0707 391.74 63.7695C389.915 64.4684 387.389 65.1672 384.162 65.866L369.427 68.5915C362.971 69.8494 357.849 71.9459 354.06 74.881C350.271 77.8161 348.377 81.7995 348.377 86.8311C348.377 91.8627 350.131 95.916 353.639 98.9908C357.288 102.066 361.779 103.603 367.111 103.603Z" fill="black"/>+<path d="M285.673 62.9573L325.127 112.948C325.726 113.707 325.183 114.82 324.213 114.82H305.929C305.572 114.82 305.235 114.657 305.015 114.378L275.053 76.414L245.093 114.378C244.872 114.657 244.536 114.82 244.179 114.82H225.893C224.924 114.82 224.381 113.707 224.98 112.948L264.433 62.9573L227.177 15.7512C226.578 14.9921 227.121 13.8793 228.091 13.8793H246.375C246.732 13.8793 247.068 14.0423 247.289 14.3214L275.053 49.5006L302.818 14.3214C303.038 14.0423 303.375 13.8793 303.731 13.8793H322.016C322.985 13.8793 323.528 14.9921 322.929 15.7512L285.673 62.9573Z" fill="black"/>+</svg>diff --git a/apps/web/public/plugin-logos/firecrawl-dark.svg b/apps/web/public/plugin-logos/firecrawl-dark.svgnew file mode 100644index 000000000..c38014c3a--- /dev/null+++ b/apps/web/public/plugin-logos/firecrawl-dark.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="50" height="72" fill="none" viewBox="0 0 50 72"><path fill="#fff" d="M41.715 23.193c-2.762.82-4.844 2.675-6.37 4.69-.327.432-1.01.107-.88-.423 2.92-12.007-.937-21.986-12.961-26.898a.803.803 0 0 0-1.085.937c5.47 21.961-17.537 20.109-14.63 45.005.05.427-.43.72-.78.47-1.09-.782-2.307-2.415-3.142-3.562a.502.502 0 0 0-.887.16c-.665 2.404-.98 4.67-.98 6.92 0 8.749 4.497 16.45 11.304 20.915.39.255.89-.11.758-.557a13.5 13.5 0 0 1-.563-3.697c0-.788.05-1.593.173-2.343.285-1.885.94-3.68 2.04-5.314 3.772-5.663 11.334-11.132 10.127-18.56-.078-.47.477-.78.827-.457 5.328 4.868 6.383 11.415 5.508 17.287-.075.51.564.782.887.382a11.6 11.6 0 0 1 2.892-2.587c.27-.168.63-.04.733.26.602 1.752 1.497 3.397 2.342 5.042a13.46 13.46 0 0 1 .905 9.982.502.502 0 0 0 .755.57C45.5 66.95 50 59.248 50 50.494c0-3.043-.532-6.025-1.54-8.82-2.112-5.862-7.472-10.264-6.117-17.904.065-.365-.273-.682-.628-.577"/></svg>\ No newline at end of filediff --git a/apps/web/public/plugin-logos/firecrawl.svg b/apps/web/public/plugin-logos/firecrawl.svgnew file mode 100644index 000000000..d49dff46d--- /dev/null+++ b/apps/web/public/plugin-logos/firecrawl.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="50" height="72" fill="none" viewBox="0 0 50 72"><path fill="#fa5d19" d="M41.715 23.193c-2.762.82-4.844 2.675-6.37 4.69-.327.432-1.01.107-.88-.423 2.92-12.007-.937-21.986-12.961-26.898a.803.803 0 0 0-1.085.937c5.47 21.961-17.537 20.109-14.63 45.005.05.427-.43.72-.78.47-1.09-.782-2.307-2.415-3.142-3.562a.502.502 0 0 0-.887.16c-.665 2.404-.98 4.67-.98 6.92 0 8.749 4.497 16.45 11.304 20.915.39.255.89-.11.758-.557a13.5 13.5 0 0 1-.563-3.697c0-.788.05-1.593.173-2.343.285-1.885.94-3.68 2.04-5.314 3.772-5.663 11.334-11.132 10.127-18.56-.078-.47.477-.78.827-.457 5.328 4.868 6.383 11.415 5.508 17.287-.075.51.564.782.887.382a11.6 11.6 0 0 1 2.892-2.587c.27-.168.63-.04.733.26.602 1.752 1.497 3.397 2.342 5.042a13.46 13.46 0 0 1 .905 9.982.502.502 0 0 0 .755.57C45.5 66.95 50 59.248 50 50.494c0-3.043-.532-6.025-1.54-8.82-2.112-5.862-7.472-10.264-6.117-17.904.065-.365-.273-.682-.628-.577" style="fill:#fa5d19;fill:color(display-p3 .9816 .3634 .0984);fill-opacity:1"/></svg>\ No newline at end of filediff --git a/apps/web/public/plugin-logos/mcp-dark.svg b/apps/web/public/plugin-logos/mcp-dark.svgnew file mode 100644index 000000000..b81044239--- /dev/null+++ b/apps/web/public/plugin-logos/mcp-dark.svg@@ -0,0 +1 @@+<svg fill="#ffffff" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Model Context Protocol</title><path d="M13.85 0a4.16 4.16 0 0 0-2.95 1.217L1.456 10.66a.835.835 0 0 0 0 1.18.835.835 0 0 0 1.18 0l9.442-9.442a2.49 2.49 0 0 1 3.541 0 2.49 2.49 0 0 1 0 3.541L8.59 12.97l-.1.1a.835.835 0 0 0 0 1.18.835.835 0 0 0 1.18 0l.1-.098 7.03-7.034a2.49 2.49 0 0 1 3.542 0l.049.05a2.49 2.49 0 0 1 0 3.54l-8.54 8.54a1.96 1.96 0 0 0 0 2.755l1.753 1.753a.835.835 0 0 0 1.18 0 .835.835 0 0 0 0-1.18l-1.753-1.753a.266.266 0 0 1 0-.394l8.54-8.54a4.185 4.185 0 0 0 0-5.9l-.05-.05a4.16 4.16 0 0 0-2.95-1.218c-.2 0-.401.02-.6.048a4.17 4.17 0 0 0-1.17-3.552A4.16 4.16 0 0 0 13.85 0m0 3.333a.84.84 0 0 0-.59.245L6.275 10.56a4.186 4.186 0 0 0 0 5.902 4.186 4.186 0 0 0 5.902 0L19.16 9.48a.835.835 0 0 0 0-1.18.835.835 0 0 0-1.18 0l-6.985 6.984a2.49 2.49 0 0 1-3.54 0 2.49 2.49 0 0 1 0-3.54l6.983-6.985a.835.835 0 0 0 0-1.18.84.84 0 0 0-.59-.245"/></svg>\ No newline at end of filediff --git a/apps/web/public/plugin-logos/mcp.svg b/apps/web/public/plugin-logos/mcp.svgnew file mode 100644index 000000000..601fd4887--- /dev/null+++ b/apps/web/public/plugin-logos/mcp.svg@@ -0,0 +1 @@+<svg fill="#000000" role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Model Context Protocol</title><path d="M13.85 0a4.16 4.16 0 0 0-2.95 1.217L1.456 10.66a.835.835 0 0 0 0 1.18.835.835 0 0 0 1.18 0l9.442-9.442a2.49 2.49 0 0 1 3.541 0 2.49 2.49 0 0 1 0 3.541L8.59 12.97l-.1.1a.835.835 0 0 0 0 1.18.835.835 0 0 0 1.18 0l.1-.098 7.03-7.034a2.49 2.49 0 0 1 3.542 0l.049.05a2.49 2.49 0 0 1 0 3.54l-8.54 8.54a1.96 1.96 0 0 0 0 2.755l1.753 1.753a.835.835 0 0 0 1.18 0 .835.835 0 0 0 0-1.18l-1.753-1.753a.266.266 0 0 1 0-.394l8.54-8.54a4.185 4.185 0 0 0 0-5.9l-.05-.05a4.16 4.16 0 0 0-2.95-1.218c-.2 0-.401.02-.6.048a4.17 4.17 0 0 0-1.17-3.552A4.16 4.16 0 0 0 13.85 0m0 3.333a.84.84 0 0 0-.59.245L6.275 10.56a4.186 4.186 0 0 0 0 5.902 4.186 4.186 0 0 0 5.902 0L19.16 9.48a.835.835 0 0 0 0-1.18.835.835 0 0 0-1.18 0l-6.985 6.984a2.49 2.49 0 0 1-3.54 0 2.49 2.49 0 0 1 0-3.54l6.983-6.985a.835.835 0 0 0 0-1.18.84.84 0 0 0-.59-.245"/></svg>\ No newline at end of filediff --git a/apps/web/public/plugin-logos/parallel.svg b/apps/web/public/plugin-logos/parallel.svgnew file mode 100644index 000000000..ccd0c3198--- /dev/null+++ b/apps/web/public/plugin-logos/parallel.svg@@ -0,0 +1,13 @@+<svg width="96" height="96" viewBox="0 0 96 96" fill="none" xmlns="http://www.w3.org/2000/svg">+<circle cx="48" cy="48" r="48" fill="#ffffff"/>+<g transform="translate(11.0025 11.0) scale(1.088235)">+<path d="M67.271 26.6083H48.6399C48.6897 26.9014 48.7305 27.1991 48.7712 27.4967H19.1336C19.0793 27.8891 19.0249 28.286 18.9797 28.6783H0.235433C0.144881 29.2646 0.0633863 29.8554 0 30.4552H18.8076C18.7759 30.8476 18.7533 31.2445 18.7307 31.6368H49.1742C49.1878 31.93 49.2014 32.2276 49.2104 32.5253H67.9954V31.5782C67.8732 29.8825 67.6332 28.2228 67.271 26.6083Z" fill="#181818"/>+<path d="M49.1742 36.3677H18.7307C18.7488 36.7646 18.7759 37.1569 18.8076 37.5493H0C0.0633863 38.1446 0.140354 38.7354 0.235433 39.3262H18.9797C19.0249 39.723 19.0748 40.1154 19.1336 40.5078H48.7712C48.7305 40.8054 48.6852 41.0986 48.6399 41.3962H67.271C67.6332 39.7817 67.8732 38.122 67.9954 36.4263V35.4792H49.2104C49.2014 35.7769 49.1878 36.07 49.1742 36.3677Z" fill="#181818"/>+<path d="M47.8341 45.2431H20.0618C20.1614 45.64 20.2701 46.0323 20.3788 46.4247H2.16877C2.40421 47.0245 2.65775 47.6153 2.92488 48.2016H20.9175C21.0488 48.5985 21.1801 48.9908 21.3205 49.3832H46.5664C46.4577 49.6808 46.349 49.974 46.2358 50.2716H63.9252C64.9529 48.4 65.8041 46.4202 66.4651 44.3547H48.0424C47.9744 44.6523 47.902 44.9455 47.8296 45.2431H47.8341Z" fill="#181818"/>+<path d="M44.5696 54.1186H23.3307C23.5254 54.5154 23.7291 54.9123 23.9374 55.3002H7.34827C7.84178 55.909 8.3534 56.4998 8.88313 57.0771H24.9244C25.1598 57.4739 25.3998 57.8708 25.6443 58.2586H42.2606C42.0749 58.5563 41.8848 58.8539 41.6901 59.1471H56.9345C58.8768 57.3837 60.6109 55.3949 62.105 53.2301H44.9952C44.8549 53.5278 44.719 53.8254 44.5742 54.1186H44.5696Z" fill="#181818"/>+<path d="M38.8468 62.9895H29.0536C29.3841 63.3909 29.7191 63.7833 30.0632 64.1711H18.2145C22.8961 66.5974 28.2115 67.9865 33.8483 68C33.8845 68 33.9162 68 33.9479 68C33.9796 68 34.0158 68 34.0475 68C41.1377 67.9775 47.7209 65.8037 53.1675 62.0966H39.5531C39.3176 62.3942 39.0822 62.6919 38.8422 62.985L38.8468 62.9895Z" fill="#181818"/>+<path d="M29.0537 5.01499H38.8469C39.0868 5.30813 39.3223 5.60578 39.5577 5.90343H53.1722C47.721 2.19631 41.1424 0.0225494 34.0521 0C34.0159 0 33.9842 0 33.9525 0C33.9208 0 33.8846 0 33.8529 0C28.2116 0.0180395 22.9007 1.40257 18.2192 3.82889H30.0679C29.7238 4.21674 29.3887 4.61361 29.0582 5.01048L29.0537 5.01499Z" fill="#181818"/>+<path d="M23.3308 13.8904H44.5697C44.7146 14.1836 44.855 14.4812 44.9908 14.7789H62.1006C60.6065 12.6141 58.8724 10.6253 56.9301 8.86193H41.6856C41.8803 9.15507 42.0705 9.45272 42.2561 9.75037H25.6399C25.3954 10.1427 25.1554 10.5351 24.92 10.932H8.8787C8.34444 11.5047 7.83283 12.0955 7.34385 12.7089H23.9329C23.7247 13.1012 23.5255 13.4936 23.3263 13.8904H23.3308Z" fill="#181818"/>+<path d="M20.0663 22.7613H47.8386C47.911 23.0545 47.9835 23.3521 48.0514 23.6498H66.4741C65.8131 21.5843 64.9619 19.6044 63.9342 17.7328H46.2449C46.358 18.026 46.4667 18.3236 46.5754 18.6213H21.3295C21.1892 19.0136 21.0533 19.406 20.9266 19.8029H2.9339C2.66677 20.3846 2.41323 20.9754 2.17779 21.5798H20.3878C20.2791 21.9721 20.1704 22.3645 20.0708 22.7613H20.0663Z" fill="#181818"/>+</g>+</svg>diff --git a/apps/web/public/provider-icons/cursor.svg b/apps/web/public/provider-icons/cursor.svgnew file mode 100644index 000000000..04ad4e8cd--- /dev/null+++ b/apps/web/public/provider-icons/cursor.svg@@ -0,0 +1,6 @@+<svg viewBox="0 0 466.73 532.09" xmlns="http://www.w3.org/2000/svg">+ <path+ fill="currentColor"+ d="M457.43,125.94L244.42,2.96c-6.84-3.95-15.28-3.95-22.12,0L9.3,125.94c-5.75,3.32-9.3,9.46-9.3,16.11v247.99c0,6.65,3.55,12.79,9.3,16.11l213.01,122.98c6.84,3.95,15.28,3.95,22.12,0l213.01-122.98c5.75-3.32,9.3-9.46,9.3-16.11v-247.99c0-6.65-3.55-12.79-9.3-16.11h-.01ZM444.05,151.99l-205.63,356.16c-1.39,2.4-5.06,1.42-5.06-1.36v-233.21c0-4.66-2.49-8.97-6.53-11.31L24.87,145.67c-2.4-1.39-1.42-5.06,1.36-5.06h411.26c5.84,0,9.49,6.33,6.57,11.39h-.01Z"+ />+</svg>diff --git a/apps/web/public/provider-icons/kimi-for-coding.svg b/apps/web/public/provider-icons/kimi-for-coding.svgnew file mode 100644index 000000000..8f2af02e6--- /dev/null+++ b/apps/web/public/provider-icons/kimi-for-coding.svg@@ -0,0 +1,3 @@+<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M3.51531 15.81L10.908 17.7878C10.8981 18.3134 10.9136 18.8392 10.9545 19.3633L15.5704 20.5979C14.2013 21.163 12.7171 21.3928 11.2413 21.2683L11.1018 21.2559L11.0677 21.2528L11.0026 21.2458L10.9297 21.238C10.8891 21.2332 10.8486 21.228 10.808 21.2225L10.7251 21.2117L10.6399 21.1993C10.557 21.1872 10.4743 21.1741 10.3919 21.1598L10.3593 21.1536L10.3012 21.1435L10.2183 21.128L10.164 21.1164L10.0919 21.1016L10.0338 21.0892L9.96019 21.0737L9.88501 21.0559L9.81216 21.0389L9.75946 21.0257L9.69126 21.0086L9.62151 20.99L9.54789 20.9707L9.48434 20.9528L9.39986 20.9296L9.35181 20.9141L9.28671 20.8947L9.21464 20.873L9.13326 20.8467L9.08831 20.8319L9.02631 20.8118L8.95656 20.7878L8.90541 20.7692C8.89403 20.7653 8.88267 20.7615 8.87131 20.7575L8.81861 20.7382L8.74034 20.7095L8.69617 20.6924L8.63417 20.6692L8.56674 20.6421L8.49854 20.6149L8.43732 20.5901L8.36369 20.5591L8.31487 20.5374L8.26604 20.5165C8.25543 20.5119 8.24484 20.5073 8.23427 20.5026L8.18312 20.4793L8.10329 20.4429L8.06299 20.4243L7.98859 20.3886L7.94054 20.3654L7.87544 20.3344L7.80879 20.3003L7.73672 20.2639L7.69642 20.2429L7.61659 20.2003L7.57242 20.1771L7.52747 20.1523C7.51556 20.1456 7.50367 20.1389 7.49182 20.1321L7.41897 20.091L7.37247 20.0647L7.33294 20.0414L7.27714 20.0097L7.21359 19.9709L7.14152 19.9275L7.10122 19.9027L7.03612 19.8616L6.98885 19.8314L6.92762 19.7927L6.87337 19.7562L6.8323 19.7291C6.81831 19.7199 6.80436 19.7106 6.79045 19.7012L6.75635 19.678L6.72225 19.6547C6.71188 19.6475 6.70155 19.6403 6.69125 19.633L6.64707 19.602L6.58817 19.5602L6.5347 19.5214L6.47735 19.4796L6.43395 19.447L6.37505 19.4028L6.31615 19.3571L6.2495 19.3052L6.21462 19.2781L6.16502 19.2378L6.10767 19.1913L6.0387 19.1347L6.00305 19.1045L5.9674 19.0742C5.95625 19.0647 5.94515 19.0552 5.93407 19.0456L5.8992 19.0146L5.85192 18.9735L5.79767 18.9255L5.74497 18.8789L5.69692 18.834L5.645 18.786L5.60392 18.7472L5.53572 18.6821C5.51002 18.6572 5.48444 18.6321 5.459 18.6069L5.43653 18.5852L5.40475 18.5527L5.35128 18.4984L5.31253 18.4589L5.27378 18.4178C5.2295 18.3724 5.18609 18.3262 5.14358 18.2791L5.08158 18.2109L5.03353 18.1567L4.9785 18.0947L4.94595 18.0567L4.90488 18.0086L4.85993 17.9559L4.82428 17.9125C4.81728 17.904 4.8103 17.8955 4.80335 17.887L4.76848 17.8443L4.71733 17.7808L4.68555 17.7405L4.6468 17.6909L4.6313 17.6715C4.18786 17.0967 3.81331 16.4719 3.51531 15.81ZM2.72481 11.3196L11.5234 13.6733C11.3761 14.1864 11.2547 14.7065 11.1599 15.2318L19.543 17.4747C19.1266 18.0449 18.6469 18.5662 18.1132 19.0285L3.20918 15.0404L3.19678 15.0047L3.16966 14.9241C3.15647 14.8847 3.14356 14.8452 3.13091 14.8056L3.12548 14.7877C3.06583 14.5981 3.01233 14.4066 2.96506 14.2135L2.94181 14.1158L2.92786 14.0538L2.91158 13.9786L2.89763 13.9159L2.88368 13.8461L2.87051 13.781L2.85656 13.7082C2.83641 13.5989 2.81781 13.4888 2.80153 13.378L2.78836 13.2866L2.77983 13.2222L2.76976 13.1432C2.76457 13.1016 2.75966 13.06 2.75503 13.0184L2.75116 12.982C2.69326 12.4297 2.68444 11.8734 2.72481 11.3196ZM3.95938 7.32839L13.2191 9.80528C12.9339 10.2742 12.6727 10.7593 12.4363 11.2584L21.1899 13.6004C21.0799 14.2359 20.9047 14.8497 20.6722 15.4333L11.721 13.0386L2.79611 10.6516L2.80773 10.5741L2.81393 10.5361L2.82168 10.4842L2.83331 10.4168L2.84726 10.3408C2.86741 10.2261 2.89066 10.1122 2.91546 9.99825L2.93716 9.90215L2.95266 9.83628L2.97126 9.7611C2.98831 9.69135 3.00613 9.6216 3.02551 9.5534L3.04721 9.47435L3.06503 9.41003L3.08828 9.33253L3.10766 9.26898L3.13091 9.19458L3.15106 9.13103L3.17508 9.05741C3.37577 8.45541 3.63808 7.87573 3.95783 7.32761L3.95938 7.32839ZM7.40192 3.9184L16.1478 6.25734C15.6862 6.67623 15.2494 7.12157 14.8396 7.59111L20.9024 9.21318C21.1093 9.87348 21.2449 10.5648 21.3 11.2785L4.33215 6.74016L4.36703 6.68979L4.38795 6.65879L4.41895 6.61616L4.4546 6.56579L4.49723 6.50689L4.53908 6.45109L4.58868 6.38444L4.62743 6.33406L4.6716 6.27749L4.71423 6.22324L4.76073 6.16589L4.80335 6.11241L4.85373 6.05274L4.89558 6.00159L4.94673 5.94192L4.9878 5.89542L5.0436 5.83187L5.08468 5.78537L5.1366 5.72802L5.17845 5.68307L5.23503 5.62262L5.27998 5.57612L5.3288 5.52419L5.459 5.39244L5.5365 5.31649L5.58222 5.27309L5.64112 5.21807C6.17525 4.71752 6.76621 4.28132 7.40192 3.9184ZM12.0132 2.7001H12.0883L12.1519 2.70088L12.2054 2.70165L12.2472 2.7032L12.2999 2.70475L12.3356 2.70553L12.3945 2.70785L12.4309 2.7094L12.4774 2.71173L12.5192 2.71328L12.5867 2.71715L12.668 2.72258L12.7796 2.7311L12.8478 2.73653L12.8819 2.73963L12.9416 2.74583L13.0052 2.75203L13.0416 2.7559L13.1206 2.7652L13.1594 2.76985L13.2431 2.7807L13.3059 2.78845L13.3384 2.7931L13.3888 2.80085L13.5492 2.82565L13.6035 2.83495L13.6538 2.84348L13.7623 2.86363L13.8336 2.87758L13.9189 2.89462L13.9545 2.90237L14.0126 2.91477L14.0444 2.92252L14.0925 2.9326L14.125 2.94035L14.1754 2.95197L14.2134 2.96127L14.2684 2.97445L14.3428 2.99305L14.4296 3.0163L14.5172 3.03955L14.6047 3.06435L14.6435 3.07597L14.6977 3.09147L14.7582 3.11007L14.8148 3.1279L14.8535 3.1403L14.8923 3.1527L14.9512 3.17207L15.0279 3.19765L15.1069 3.22555L15.1441 3.23872L15.1937 3.25655L15.2658 3.2829L15.3511 3.31467L15.441 3.34955L15.5185 3.38055L15.5549 3.39605L15.6014 3.41465L15.6332 3.4286L15.682 3.44875L15.713 3.4627L15.7572 3.48207L15.8424 3.51927L15.9199 3.55492L15.9773 3.58205L16.0354 3.60995L16.0819 3.63165L16.1532 3.6673L16.2237 3.70217L16.3028 3.74247L16.3438 3.76417L16.3818 3.78432L16.4175 3.80292L16.464 3.8285L16.4957 3.84555L16.536 3.86802L16.6042 3.90677L16.6864 3.95327L16.7538 3.9928L16.798 4.01915L16.8391 4.04395L16.9135 4.08967L16.9817 4.1323L17.0576 4.18035L17.0855 4.19895L17.1351 4.23072L17.2002 4.27412L17.2312 4.29505L17.2793 4.3276L17.3273 4.36092L17.3451 4.3741C17.387 4.40277 17.4288 4.43222 17.4699 4.46244L17.5342 4.50894L17.5846 4.54614L17.628 4.57947L17.6947 4.62984L17.7582 4.67944L17.7892 4.70269L17.828 4.73447L17.8946 4.78794L17.9558 4.83832L18.0217 4.89334C18.5735 5.35834 19.0703 5.88767 19.5012 6.46736L8.29704 3.47045L8.34509 3.44952L8.39547 3.42782L8.45824 3.40147L8.52489 3.37435C8.61247 3.33947 8.70082 3.3046 8.78916 3.27282L8.86356 3.2457L8.93564 3.22012L9.00074 3.19687L9.07514 3.17285C9.14256 3.1496 9.21154 3.1279 9.27974 3.10697L9.35026 3.08605L9.41691 3.06667L9.49596 3.04342L9.56184 3.0256L9.63934 3.00545L9.70599 2.98685L9.77574 2.96902L9.84626 2.95197L9.91989 2.93492L9.98964 2.91942L10.0656 2.90315L10.1361 2.88765L10.2097 2.8737L10.281 2.85975L10.3585 2.8458L10.4291 2.8334L10.505 2.82023L10.5763 2.80938L10.6515 2.79775L10.7228 2.78768L10.8018 2.7776L10.8724 2.7683L10.9537 2.759L11.0235 2.75125L11.1049 2.7435C11.1769 2.73575 11.249 2.72955 11.3219 2.7249L11.404 2.7187L11.4738 2.71483L11.559 2.71018L11.6311 2.70708L11.7086 2.70398L11.7838 2.70243L11.8605 2.70088L12.0132 2.69933V2.7001Z" fill="currentColor"/>+</svg>diff --git a/apps/web/public/provider-icons/openai.svg b/apps/web/public/provider-icons/openai.svgnew file mode 100644index 000000000..000f65c34--- /dev/null+++ b/apps/web/public/provider-icons/openai.svg@@ -0,0 +1,3 @@+<svg width="24" height="24" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">+<path d="M32.8377 17.282C33.2127 16.25 33.3072 15.218 33.2127 14.1875C33.1197 13.1571 32.7447 12.1251 32.2752 11.1876C31.4322 9.78209 30.2127 8.6571 28.8072 8.0001C27.3072 7.34461 25.7127 7.15711 24.1197 7.53211C23.3698 6.78212 22.5253 6.12512 21.5878 5.65713C20.6503 5.18913 19.5253 5.00013 18.4948 5.00013C16.8851 4.99074 15.3125 5.48246 13.9948 6.40712C12.6824 7.34311 11.7449 8.6571 11.2754 10.1571C10.1504 10.4376 9.21289 10.9071 8.27539 11.4696C7.4324 12.1251 6.77541 12.9696 6.21291 13.8126C5.36992 15.2195 5.08792 16.8125 5.27542 18.407C5.46399 19.9968 6.11605 21.496 7.1504 22.718C6.79608 23.7086 6.66795 24.7659 6.77541 25.8124C6.86991 26.8444 7.2449 27.8749 7.7129 28.8124C8.55739 30.2194 9.77538 31.3444 11.1824 31.9999C12.6824 32.6569 14.2753 32.8444 15.8698 32.4694C16.6198 33.2194 17.4628 33.8749 18.4003 34.3444C19.3378 34.8139 20.4628 34.9999 21.4948 34.9999C23.1043 35.0097 24.6769 34.5185 25.9947 33.5944C27.3072 32.6569 28.2447 31.3444 28.7127 29.8444C29.7719 29.6432 30.7682 29.1934 31.6197 28.5319C32.4627 27.8749 33.2127 27.1249 33.6822 26.1874C34.5251 24.7819 34.8071 23.1875 34.6196 21.5945C34.4322 20 33.8697 18.5015 32.8377 17.282ZM21.5878 33.0304C20.0878 33.0304 18.9628 32.5609 17.9323 31.7179C17.9323 31.7179 18.0253 31.6234 18.1198 31.6234L24.1197 28.1554C24.2862 28.0803 24.4196 27.9469 24.4947 27.7804C24.5698 27.636 24.6021 27.4731 24.5877 27.3109V18.875L27.1197 20.375V27.3124C27.1455 28.0547 27.0215 28.7945 26.755 29.4878C26.4885 30.181 26.085 30.8134 25.5687 31.3473C25.0523 31.8811 24.4337 32.3054 23.7497 32.5949C23.0658 32.8843 22.3305 33.0314 21.5878 33.0304ZM9.49488 27.8749C8.83789 26.7499 8.55739 25.4374 8.83789 24.125C8.83789 24.125 8.93239 24.2195 9.02539 24.2195L15.0253 27.6874C15.1693 27.7638 15.3325 27.7966 15.4948 27.7819C15.6823 27.7819 15.8698 27.7819 15.9628 27.6874L23.2753 23.4695V26.3749L17.1823 29.9374C16.5506 30.3042 15.8527 30.5427 15.1287 30.6393C14.4046 30.7358 13.6686 30.6884 12.9629 30.4999C11.4629 30.1249 10.2449 29.1874 9.49488 27.8749ZM7.9004 14.8445C8.56239 13.7234 9.58826 12.8627 10.8074 12.4056V19.532C10.8074 19.718 10.8074 19.907 10.9004 20C10.9755 20.1665 11.1089 20.2998 11.2754 20.375L18.5878 24.5944L16.0573 26.0944L10.0574 22.625C9.41842 22.2639 8.85742 21.7797 8.40684 21.2004C7.95627 20.6211 7.62506 19.9582 7.4324 19.25C7.05741 17.8445 7.1504 16.157 7.9004 14.8445ZM28.6197 19.625L21.3073 15.407L23.8377 13.9071L29.8377 17.375C30.7752 17.9375 31.5252 18.6875 31.9947 19.625C32.4642 20.5625 32.7447 21.5945 32.6502 22.7195C32.5603 23.7755 32.1699 24.7837 31.5252 25.6249C30.8697 26.4694 30.0252 27.1249 28.9947 27.4999V20.375C28.9947 20.1875 28.9947 20 28.9002 19.907C28.9002 19.907 28.8072 19.718 28.6197 19.625ZM31.1502 15.875C31.1502 15.875 31.0572 15.782 30.9627 15.782L24.9627 12.3126C24.7752 12.2196 24.6822 12.2196 24.4947 12.2196C24.3072 12.2196 24.1197 12.2196 24.0252 12.3126L16.7128 16.532V13.6251L22.8073 10.0626C23.7448 9.50009 24.7752 9.31259 25.9002 9.31259C26.9322 9.31259 27.9627 9.68759 28.9002 10.3446C29.7447 11.0001 30.4947 11.8446 30.8697 12.7821C31.2447 13.7196 31.3377 14.8445 31.1502 15.875ZM15.4003 21.125L12.8699 19.625V12.5946C12.8699 11.5626 13.1503 10.4376 13.7128 9.59459C14.2753 8.6571 15.1198 8.0001 16.0573 7.53211C17.0127 7.05249 18.0956 6.88812 19.1503 7.06261C20.1823 7.15711 21.2128 7.62511 22.0573 8.2821C22.0573 8.2821 21.9628 8.3751 21.8698 8.3751L15.8698 11.8446C15.7033 11.9197 15.57 12.0531 15.4948 12.2196C15.4003 12.4071 15.4003 12.5001 15.4003 12.6876V21.125ZM16.7128 18.125L19.9948 16.25L23.2753 18.125V21.875L19.9948 23.75L16.7128 21.875V18.125Z" fill="currentColor"/>+</svg>diff --git a/apps/web/public/provider-icons/xai.svg b/apps/web/public/provider-icons/xai.svgnew file mode 100644index 000000000..ccd22443c--- /dev/null+++ b/apps/web/public/provider-icons/xai.svg@@ -0,0 +1,3 @@+<svg width="24" height="24" viewBox="0 0 40 40" xmlns="http://www.w3.org/2000/svg">+<path d="M12.4579 15.6036L26.1529 35H20.0656L6.37059 15.6036H12.4579ZM12.4524 26.3764L15.4974 30.6909L12.4551 35H6.36377L12.4524 26.3764ZM33.6365 7.15727V35H28.647V14.2236L33.6365 7.15727ZM33.6365 5L20.0656 24.2205L17.0206 19.9073L27.5451 5H33.6365Z" fill="currentColor"/>+</svg>diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.tsindex a245cbc54..e65a72329 100644--- a/apps/web/src/cloud/linkEnvironment.ts+++ b/apps/web/src/cloud/linkEnvironment.ts@@ -74,7 +74,7 @@ function ensureRelayClientAvailable(if (status.status === "available") return;if (status.status === "unsupported") {return yield* new CloudEnvironmentLinkError({- message: `T3 Code cannot install the relay client automatically on ${status.platform}-${status.arch}.`,+ message: `Akeru Bot cannot install the relay client automatically on ${status.platform}-${status.arch}.`,});}@@ -110,7 +110,7 @@ function ensureRelayClientAvailable(return yield* new CloudEnvironmentLinkError({message:installedStatus.status === "unsupported"- ? `T3 Code cannot install the relay client automatically on ${installedStatus.platform}-${installedStatus.arch}.`+ ? `Akeru Bot cannot install the relay client automatically on ${installedStatus.platform}-${installedStatus.arch}.`: "The relay client is still unavailable after installation.",});}diff --git a/apps/web/src/cloud/primaryCloudLinkState.ts b/apps/web/src/cloud/primaryCloudLinkState.tsindex 34fdacd21..7c090d3b5 100644--- a/apps/web/src/cloud/primaryCloudLinkState.ts+++ b/apps/web/src/cloud/primaryCloudLinkState.ts@@ -72,7 +72,7 @@ export function usePrimaryCloudLinkState() {let error: string | null = null;if (result._tag === "Failure") {const cause = Cause.squash(result.cause);- error = cause instanceof Error ? cause.message : "Could not read T3 Connect link state.";+ error = cause instanceof Error ? cause.message : "Could not read the environment link state.";}return {diff --git a/apps/web/src/cloud/useCloudLinkController.ts b/apps/web/src/cloud/useCloudLinkController.tsindex d91596880..964ef9a76 100644--- a/apps/web/src/cloud/useCloudLinkController.ts+++ b/apps/web/src/cloud/useCloudLinkController.ts@@ -24,7 +24,7 @@ export interface CloudLinkDesiredState {}/**- * Drives the primary environment's T3 Connect link. T3 Connect (managed+ * Drives the primary environment's managed relay link. The relay (managed* tunnel) and agent-activity publishing are independent capabilities backed by* a single relay link, so consumers express the full desired state and* `reconcileCloudState` applies it: unlink when neither is wanted, otherwise@@ -51,13 +51,13 @@ export function useCloudLinkController() {const [operationError, setOperationError] = useState<string | null>(null);const reportUpdateFailure = (cause: unknown) => {- const message = cause instanceof Error ? cause.message : "Could not update T3 Connect access.";+ const message = cause instanceof Error ? cause.message : "Could not update remote access.";const traceId = findErrorTraceId(cause);- console.error("[t3-connect] Could not update T3 Connect", { message, traceId, cause });+ console.error("[t3-connect] Could not update remote access", { message, traceId, cause });setOperationError(traceId ? `${message} Trace ID: ${traceId}` : message);toastManager.add({type: "error",- title: "Could not update T3 Connect",+ title: "Could not update remote access",description: message,data: traceId? {@@ -93,7 +93,7 @@ export function useCloudLinkController() {// actually holds now.if (!wantsLink) {// Unlink works without a relay token — a failed token read must not- // leave the user unable to turn T3 Connect off.+ // leave the user unable to turn remote access off.const unlinkResult = await unlinkPrimaryEnvironment({target,clerkToken: tokenResult._tag === "Success" ? (tokenResult.value ?? null) : null,@@ -112,7 +112,7 @@ export function useCloudLinkController() {}const clerkToken = tokenResult.value;if (!clerkToken) {- reportUpdateFailure(new Error("Sign in to T3 Connect before enabling this."));+ reportUpdateFailure(new Error("Sign in before enabling this."));return false;}if (!linked || managedTunnelActive !== desired.managedTunnel) {diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsxindex a3ba76679..121e7b77a 100644--- a/apps/web/src/components/AppSidebarLayout.tsx+++ b/apps/web/src/components/AppSidebarLayout.tsx@@ -7,18 +7,14 @@ import {type CSSProperties,type ReactNode,} from "react";-import { useLocation, useNavigate } from "@tanstack/react-router";import { isElectron } from "../env";import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";import { cn, isMacPlatform } from "../lib/utils";import { primaryServerKeybindingsAtom } from "../state/server";-import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings";-import LegacyThreadSidebar from "./LegacySidebar";-import ThreadSidebar from "./Sidebar";-import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";-import { SidebarChromeHeader } from "./sidebar/SidebarChrome";+import BotRosterSidebar from "./roster/BotRosterSidebar";+import { openSettings } from "~/settingsDialogStore";import {resolveSidebarStageFocusRingOffsetClass,useSidebarStageBackdropVariant,@@ -64,15 +60,16 @@ function readInitialThreadSidebarWidth(): number {}}-function SidebarControl() {+function SidebarControl({ stageArtworkVisible }: { stageArtworkVisible: boolean }) {const keybindings = useAtomValue(primaryServerKeybindingsAtom);- const { toggleSidebar } = useSidebar();+ const { isMobile, toggleSidebar } = useSidebar();const isSidebarVisible = useSidebarVisibility();- const environmentIdentificationMode = useEnvironmentIdentificationMode();- const stageBackdropVariant = useSidebarStageBackdropVariant(- environmentIdentificationMode === "artwork",- );+ const stageBackdropVariant = useSidebarStageBackdropVariant(stageArtworkVisible);const shortcutLabel = shortcutLabelForCommand(keybindings, "sidebar.toggle");+ // The roster has no collapse button. Its rail reopens through the shortcut+ // or the rail edge. Mobile and the legacy offcanvas sidebar still need this+ // global opener.+ const showTrigger = isMobile;useEffect(() => {const onKeyDown = (event: KeyboardEvent) => {@@ -95,6 +92,10 @@ function SidebarControl() {return () => window.removeEventListener("keydown", onKeyDown, true);}, [keybindings, toggleSidebar]);+ if (!showTrigger) {+ return null;+ }+return (// The right-side layout controls carry mr-px (border compensation inside// the panel), so the trigger mirrors it: both clusters sit one extra pixel@@ -137,12 +138,7 @@ function ProjectProjectionRetention() {}export function AppSidebarLayout({ children }: { children: ReactNode }) {- const navigate = useNavigate();- const legacySidebarEnabled = useLegacySidebarEnabled();- // Settings routes show the settings nav in place of whichever thread- // sidebar is active.- const pathname = useLocation({ select: (location) => location.pathname });- const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/");+ const stageArtworkVisible = false;const isMacosDesktop = isElectron && isMacPlatform(navigator.platform);const [sidebarWidth, setSidebarWidth] = useState(readInitialThreadSidebarWidth);// Subscribed rather than read once: the clamp must track live window size,@@ -196,24 +192,21 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {const unsubscribe = onMenuAction((action) => {if (action === "open-settings") {- const isSettingsRoute = /^\/settings(\/|$)/.test(pathname);- if (!isSettingsRoute) {- void navigate({ to: "/settings" });- }+ openSettings();}});return () => {unsubscribe?.();};- }, [navigate, pathname]);+ }, []);return (<SidebarProvider className="h-dvh! min-h-0!" defaultOpen style={sidebarProviderStyle}><ProjectProjectionRetention /><Sidebarside="left"- collapsible="offcanvas"+ collapsible="icon"data-app-sidebar=""className="border-r border-sidebar-border bg-sidebar text-sidebar-foreground"resizable={{@@ -226,20 +219,11 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {onResize: setSidebarWidth,}}>- {isOnSettings ? (- <>- <SidebarChromeHeader isElectron={isElectron} />- <SettingsSidebarNav pathname={pathname} />- </>- ) : legacySidebarEnabled ? (- <LegacyThreadSidebar />- ) : (- <ThreadSidebar />- )}+ <BotRosterSidebar /><SidebarRail onDoubleClick={resetSidebarWidth} /></Sidebar>{children}- <SidebarControl />+ <SidebarControl stageArtworkVisible={stageArtworkVisible} /></SidebarProvider>);}diff --git a/apps/web/src/components/ChatMarkdown.test.tsx b/apps/web/src/components/ChatMarkdown.test.tsxindex 2ca9ad4ae..92418b70d 100644--- a/apps/web/src/components/ChatMarkdown.test.tsx+++ b/apps/web/src/components/ChatMarkdown.test.tsx@@ -188,6 +188,30 @@ describe("orderedListGutterStyle", () => {});});+describe("ChatMarkdown rich formatting", () => {+ it("renders inline and display math", () => {+ const html = renderToStaticMarkup(+ <ChatMarkdown+ cwd={undefined}+ text={"Inline $E = mc^2$ and display:\n\n$$\n\\sum_{n=1}^N n\n$$"}+ />,+ );++ expect(html).toContain("<math");+ expect(html).toContain('display="block"');+ });++ it("reserves Mermaid fences for client-side diagrams", () => {+ const html = renderToStaticMarkup(+ <ChatMarkdown cwd={undefined} text={"```mermaid\ngraph LR\n A --> B\n```"} />,+ );++ expect(html).toContain('data-mermaid-diagram=""');+ expect(html).toContain("Rendering diagram");+ expect(html).not.toContain("chat-markdown-codeblock");+ });+});+describe("ChatMarkdown Windows file links", () => {const environmentId = EnvironmentId.make("env-windows");diff --git a/apps/web/src/components/ChatMarkdown.tsx b/apps/web/src/components/ChatMarkdown.tsxindex dd21a4e1b..365bf178c 100644--- a/apps/web/src/components/ChatMarkdown.tsx+++ b/apps/web/src/components/ChatMarkdown.tsx@@ -37,6 +37,7 @@ import React, {useCallback,memo,useEffect,+ useId,useMemo,useRef,useState,@@ -49,6 +50,9 @@ import rehypeRaw from "rehype-raw";import rehypeSanitize, { defaultSchema } from "rehype-sanitize";import remarkBreaks from "remark-breaks";import remarkGfm from "remark-gfm";+import remarkMath from "remark-math";+import katex from "katex";+import "katex/dist/katex.min.css";import { remarkGithubAlerts } from "../markdown-github-alerts";import { renderSkillInlineMarkdownChildren } from "./chat/SkillInlineText";import { CHAT_FILE_TAG_CHIP_CLASS_NAME, FileTagChipContent } from "./chat/FileTagChip";@@ -284,6 +288,8 @@ const CHAT_MARKDOWN_SANITIZE_SCHEMA = {const CHAT_MARKDOWN_REMARK_PLUGINS = [remarkGfm,+ remarkMath,+ remarkTagMathNodes,remarkGithubAlerts,remarkNormalizeListItemIndentation,remarkPreserveCodeMeta,@@ -292,6 +298,8 @@ const CHAT_MARKDOWN_REMARK_PLUGINS = [const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [remarkGfm,+ remarkMath,+ remarkTagMathNodes,remarkGithubAlerts,remarkNormalizeListItemIndentation,remarkBreaks,@@ -299,7 +307,7 @@ const CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS = [remarkNormalizeLinksAndTagInlineCode,] satisfies NonNullable<ReactMarkdownOptions["remarkPlugins"]>;-const CHAT_MARKDOWN_REHYPE_PLUGINS = [+const CHAT_MARKDOWN_REHYPE_PLUGINS_WITH_RAW_HTML = [rehypeRaw,rehypeNormalizeWindowsImageSrc,[rehypeSanitize, CHAT_MARKDOWN_SANITIZE_SCHEMA],@@ -383,12 +391,38 @@ type MarkdownAstNode = {type?: string;meta?: unknown;url?: string;+ value?: string;+ lang?: string;data?: {+ hName?: string;hProperties?: Record<string, unknown>;};children?: MarkdownAstNode[];};+function remarkTagMathNodes() {+ return (tree: MarkdownAstNode) => {+ const visit = (node: MarkdownAstNode) => {+ if (node.type === "inlineMath" && typeof node.value === "string") {+ node.type = "inlineCode";+ node.data = {+ ...node.data,+ hProperties: {+ ...node.data?.hProperties,+ dataMathExpression: node.value,+ },+ };+ } else if (node.type === "math" && typeof node.value === "string") {+ node.type = "code";+ node.lang = "math";+ }+ node.children?.forEach(visit);+ };++ visit(tree);+ };+}+function remarkPreserveCodeMeta() {return (tree: MarkdownAstNode) => {const visit = (node: MarkdownAstNode) => {@@ -671,6 +705,82 @@ function MarkdownDetails({);}+function MarkdownMathExpression({+ expression,+ displayMode,+}: {+ readonly expression: string;+ readonly displayMode: boolean;+}) {+ const html = katex.renderToString(expression, {+ displayMode,+ output: "htmlAndMathml",+ strict: "warn",+ throwOnError: false,+ trust: false,+ });+ return (+ <span+ className={displayMode ? "chat-markdown-math-block" : "chat-markdown-math-inline"}+ dangerouslySetInnerHTML={{ __html: html }}+ />+ );+}++function MarkdownMermaidDiagram({+ code,+ theme,+}: {+ readonly code: string;+ readonly theme: "light" | "dark";+}) {+ const reactId = useId();+ const [svg, setSvg] = useState<string | null>(null);+ const [failed, setFailed] = useState(false);++ useEffect(() => {+ let active = true;+ setSvg(null);+ setFailed(false);++ void import("mermaid")+ .then(async ({ default: mermaid }) => {+ mermaid.initialize({+ startOnLoad: false,+ securityLevel: "strict",+ theme: theme === "dark" ? "dark" : "default",+ });+ const result = await mermaid.render(`mermaid-${reactId.replaceAll(":", "")}`, code);+ if (active) setSvg(result.svg);+ })+ .catch((cause: unknown) => {+ reportMarkdownActionFailure({ operation: "render-mermaid", language: "mermaid" }, cause);+ if (active) setFailed(true);+ });++ return () => {+ active = false;+ };+ }, [code, reactId, theme]);++ return (+ <div+ className="chat-markdown-mermaid my-3 overflow-x-auto rounded-lg border border-border bg-muted/20 p-3"+ data-mermaid-diagram=""+ >+ {svg ? (+ <div aria-label="Mermaid diagram" role="img" dangerouslySetInnerHTML={{ __html: svg }} />+ ) : failed ? (+ <pre className="m-0">+ <code className="language-mermaid">{code}</code>+ </pre>+ ) : (+ <p className="m-0 text-xs text-muted-foreground">Rendering diagram…</p>+ )}+ </div>+ );+}+/*** Filename titles render icon + text; language-only titles render just the* icon (redundant next to its own name) and fall back to the language text@@ -1744,29 +1854,8 @@ function ChatMarkdown({}, []);const openChangeRequestLink = useOpenChangeRequestLink(threadRef);const resolveThreadPullRequest = useCallback(- (href: string): ThreadLinkedPullRequest | null => {- if (- threadRef === undefined ||- readThreadShell(threadRef) === null ||- threadServerConfig?.environment.capabilities.threadPullRequestLinking !== true- ) {- return null;- }- const parsed = parseChangeRequestUrl(href);- if (parsed === null) return null;- const project = findProjectForChangeRequest(- projects.filter((candidate) => candidate.environmentId === threadRef.environmentId),- parsed,- );- if (project === undefined) return null;- return {- projectId: project.id,- repository: project.repositoryIdentity?.displayName ?? parsed.repository,- number: parsed.number,- url: href,- };- },- [projects, threadRef, threadServerConfig],+ (_href: string): ThreadLinkedPullRequest | null => null,+ [],);const updateThreadPullRequestLink = useCallback(async (href: string, linked: boolean) => {@@ -2131,6 +2220,10 @@ function ChatMarkdown({);},code({ node, children, className, ...props }) {+ const mathExpression = node?.properties?.dataMathExpression;+ if (typeof mathExpression === "string") {+ return <MarkdownMathExpression expression={mathExpression} displayMode={false} />;+ }if (node?.properties?.dataInlineCode != null) {const codeText = nodeToPlainText(children);const fileLinkMeta =@@ -2185,6 +2278,12 @@ function ChatMarkdown({}const language = extractFenceLanguage(codeBlock.className);+ if (language.toLowerCase() === "math") {+ return <MarkdownMathExpression expression={codeBlock.code} displayMode />;+ }+ if (language.toLowerCase() === "mermaid") {+ return <MarkdownMermaidDiagram code={codeBlock.code} theme={resolvedTheme} />;+ }const fenceTitle = extractFenceTitle(extractPreCodeMeta(node));return (<MarkdownCodeBlock@@ -2248,7 +2347,7 @@ function ChatMarkdown({remarkPlugins={lineBreaks ? CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS : CHAT_MARKDOWN_REMARK_PLUGINS}- rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS : undefined}+ rehypePlugins={parseRawHtml ? CHAT_MARKDOWN_REHYPE_PLUGINS_WITH_RAW_HTML : undefined}skipHtml={false}components={markdownComponents}urlTransform={markdownUrlTransform}diff --git a/apps/web/src/components/ChatView.logic.test.ts b/apps/web/src/components/ChatView.logic.test.tsindex cb814dace..a850de04a 100644--- a/apps/web/src/components/ChatView.logic.test.ts+++ b/apps/web/src/components/ChatView.logic.test.ts@@ -26,7 +26,14 @@ import {isBranchMismatchDismissedForSession,reconcileMountedTerminalThreadIds,reconcileRetainedMountedThreadIds,+ buildFirstSendBootstrap,+ buildFirstSendTurnInput,resolveBackgroundDraftWorkspaceOptions,+ crossWorktreeSendBoundary,+ resolveComposerBranchForSend,+ resolveWorktreeSendGate,+ WORKTREE_BASE_BRANCH_MISSING_ERROR,+ WORKTREE_BRANCHES_LOADING_REASON,resolveDraftPromotionNavigationTarget,resolveThreadMetadataUpdateForNextTurn,resolveSendEnvMode,@@ -529,6 +536,471 @@ describe("resolveSendEnvMode", () => {});});+describe("resolveWorktreeSendGate", () => {+ it("is ready when no worktree base branch is needed", () => {+ expect(+ resolveWorktreeSendGate({+ needsWorktreeBaseBranch: false,+ refsLoadPending: true,+ resolvedBranch: null,+ }),+ ).toEqual({ state: "ready" });+ });++ it("is ready once a base branch resolved", () => {+ expect(+ resolveWorktreeSendGate({+ needsWorktreeBaseBranch: true,+ refsLoadPending: false,+ resolvedBranch: "main",+ }),+ ).toEqual({ state: "ready" });+ });++ it("disables send with a loading reason while refs load", () => {+ expect(+ resolveWorktreeSendGate({+ needsWorktreeBaseBranch: true,+ refsLoadPending: true,+ resolvedBranch: null,+ }),+ ).toEqual({ state: "loading", sendDisabledReason: WORKTREE_BRANCHES_LOADING_REASON });+ expect(WORKTREE_BRANCHES_LOADING_REASON).toBe("Loading repository branches");+ });++ it("surfaces the exact actionable error once refs settled without a branch", () => {+ expect(+ resolveWorktreeSendGate({+ needsWorktreeBaseBranch: true,+ refsLoadPending: false,+ resolvedBranch: null,+ }),+ ).toEqual({ state: "missing-base-branch", errorMessage: WORKTREE_BASE_BRANCH_MISSING_ERROR });+ expect(WORKTREE_BASE_BRANCH_MISSING_ERROR).toBe(+ "No base branch found. Create or check out a Git branch, or choose Current checkout in Project settings.",+ );+ });+});++describe("first-send turn payload", () => {+ const modelSelection = { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" };+ const message = {+ messageId: MessageId.make("message-1"),+ role: "user" as const,+ text: "Ship it",+ attachments: [],+ };+ const baseTurnInput = {+ threadId,+ message,+ modelSelection,+ titleSeed: "New thread",+ runtimeMode: "approval-required" as const,+ interactionMode: "default" as const,+ createdAt: now,+ };+ const makeCreateThread = (branch: string | null) => ({+ projectId,+ title: "New thread",+ modelSelection,+ runtimeMode: "approval-required" as const,+ interactionMode: "default" as const,+ branch,+ worktreePath: null,+ createdAt: now,+ });+ const sendScenario = (input: {+ effectiveEnvMode: "local" | "worktree";+ explicitBranch?: string | null;+ activeWorktreePath?: string | null;+ defaultBranchName?: string | null;+ currentGitBranch?: string | null;+ refsLoadPending?: boolean;+ isLocalDraftThread?: boolean;+ isFirstTurnSend?: boolean;+ startFromOrigin?: boolean;+ }) => {+ const resolvedBranch = resolveComposerBranchForSend({+ effectiveEnvMode: input.effectiveEnvMode,+ explicitBranch: input.explicitBranch ?? null,+ activeWorktreePath: input.activeWorktreePath ?? null,+ defaultBranchName: input.defaultBranchName ?? null,+ currentGitBranch: input.currentGitBranch ?? null,+ refsLoadPending: input.refsLoadPending ?? false,+ });+ const gate = resolveWorktreeSendGate({+ needsWorktreeBaseBranch:+ (input.isFirstTurnSend ?? true) &&+ input.effectiveEnvMode === "worktree" &&+ (input.activeWorktreePath ?? null) === null,+ refsLoadPending: input.refsLoadPending ?? false,+ resolvedBranch,+ });+ const baseBranchForWorktree =+ (input.isFirstTurnSend ?? true) &&+ input.effectiveEnvMode === "worktree" &&+ !(input.activeWorktreePath ?? null)+ ? resolvedBranch+ : null;+ const bootstrap = buildFirstSendBootstrap({+ isLocalDraftThread: input.isLocalDraftThread ?? true,+ baseBranchForWorktree,+ createThread: makeCreateThread(resolvedBranch),+ projectCwd: "/repo",+ worktreeBranch: "t3/tmp-branch",+ startFromOrigin: input.startFromOrigin ?? false,+ });+ const turnInput = buildFirstSendTurnInput({+ ...baseTurnInput,+ ...(bootstrap ? { bootstrap } : {}),+ });+ return { resolvedBranch, gate, turnInput };+ };++ it("builds the complete local draft turn input", () => {+ const { gate, turnInput } = sendScenario({ effectiveEnvMode: "local" });+ expect(gate).toEqual({ state: "ready" });+ expect(turnInput).toEqual({+ ...baseTurnInput,+ bootstrap: { createThread: makeCreateThread(null) },+ });+ });++ it("builds the complete configured-worktree turn input", () => {+ const { resolvedBranch, gate, turnInput } = sendScenario({+ effectiveEnvMode: "worktree",+ defaultBranchName: "origin/main",+ currentGitBranch: "feature/current",+ startFromOrigin: true,+ });+ expect(resolvedBranch).toBe("origin/main");+ expect(gate).toEqual({ state: "ready" });+ expect(turnInput).toEqual({+ ...baseTurnInput,+ bootstrap: {+ createThread: makeCreateThread("origin/main"),+ prepareWorktree: {+ projectCwd: "/repo",+ baseBranch: "origin/main",+ branch: "t3/tmp-branch",+ startFromOrigin: true,+ },+ runSetupScript: true,+ },+ });+ });++ it("puts the explicit branch in the complete turn input", () => {+ const { resolvedBranch, turnInput } = sendScenario({+ effectiveEnvMode: "worktree",+ explicitBranch: "feature/picked",+ defaultBranchName: "origin/main",+ });+ expect(resolvedBranch).toBe("feature/picked");+ expect(turnInput).toEqual({+ ...baseTurnInput,+ bootstrap: {+ createThread: makeCreateThread("feature/picked"),+ prepareWorktree: {+ projectCwd: "/repo",+ baseBranch: "feature/picked",+ branch: "t3/tmp-branch",+ },+ runSetupScript: true,+ },+ });+ });++ it("puts the checked-out branch fallback in the complete turn input", () => {+ const { resolvedBranch, turnInput } = sendScenario({+ effectiveEnvMode: "worktree",+ currentGitBranch: "feature/current",+ });+ expect(resolvedBranch).toBe("feature/current");+ expect(turnInput).toEqual({+ ...baseTurnInput,+ bootstrap: {+ createThread: makeCreateThread("feature/current"),+ prepareWorktree: {+ projectCwd: "/repo",+ baseBranch: "feature/current",+ branch: "t3/tmp-branch",+ },+ runSetupScript: true,+ },+ });+ });++ it("builds the complete existing-thread input without bootstrap", () => {+ const { gate, turnInput } = sendScenario({+ effectiveEnvMode: "local",+ isLocalDraftThread: false,+ isFirstTurnSend: false,+ });+ expect(gate).toEqual({ state: "ready" });+ expect(turnInput).toEqual(baseTurnInput);+ });++ it("builds the complete existing-worktree input without bootstrap or an invented branch", () => {+ const { resolvedBranch, gate, turnInput } = sendScenario({+ effectiveEnvMode: "worktree",+ activeWorktreePath: "/repo/.worktrees/t3-1",+ isLocalDraftThread: false,+ defaultBranchName: "origin/main",+ });+ expect(resolvedBranch).toBeNull();+ expect(gate).toEqual({ state: "ready" });+ expect(turnInput).toEqual(baseTurnInput);+ });++ it("builds the complete background-draft turn input and next-draft workspace options", () => {+ const { resolvedBranch, turnInput } = sendScenario({+ effectiveEnvMode: "worktree",+ defaultBranchName: "origin/main",+ startFromOrigin: true,+ });+ expect(turnInput).toEqual({+ ...baseTurnInput,+ bootstrap: {+ createThread: makeCreateThread("origin/main"),+ prepareWorktree: {+ projectCwd: "/repo",+ baseBranch: "origin/main",+ branch: "t3/tmp-branch",+ startFromOrigin: true,+ },+ runSetupScript: true,+ },+ });+ expect(+ resolveBackgroundDraftWorkspaceOptions({+ envMode: "worktree",+ branch: resolvedBranch,+ startFromOrigin: true,+ }),+ ).toEqual({+ envMode: "worktree",+ branch: "origin/main",+ worktreePath: null,+ startFromOrigin: true,+ });+ });++ const makeBoundaryContinuationSpies = () => {+ const clearPrompt = vi.fn();+ const clearAttachments = vi.fn();+ const clearContexts = vi.fn();+ const appendOptimisticMessage = vi.fn();+ const dispatchTurn = vi.fn();+ const setThreadError = vi.fn();+ const send = vi.fn(() => {+ clearPrompt();+ clearAttachments();+ clearContexts();+ appendOptimisticMessage();+ dispatchTurn();+ return "turn-started";+ });+ return {+ clearPrompt,+ clearAttachments,+ clearContexts,+ appendOptimisticMessage,+ dispatchTurn,+ setThreadError,+ send,+ };+ };++ it("blocks the supplied continuation while worktree refs load", async () => {+ const { resolvedBranch, gate } = sendScenario({+ effectiveEnvMode: "worktree",+ refsLoadPending: true,+ defaultBranchName: null,+ currentGitBranch: null,+ });+ expect(resolvedBranch).toBeNull();+ expect(gate).toEqual({+ state: "loading",+ sendDisabledReason: WORKTREE_BRANCHES_LOADING_REASON,+ });++ const continuation = makeBoundaryContinuationSpies();+ const outcome = await crossWorktreeSendBoundary({+ gate,+ requiresWorktreeCreation: true,+ threadId,+ setThreadError: continuation.setThreadError,+ send: continuation.send,+ });+ expect(outcome).toEqual({ outcome: "blocked-loading" });+ expect(continuation.send).not.toHaveBeenCalled();+ expect(continuation.clearPrompt).not.toHaveBeenCalled();+ expect(continuation.clearAttachments).not.toHaveBeenCalled();+ expect(continuation.clearContexts).not.toHaveBeenCalled();+ expect(continuation.appendOptimisticMessage).not.toHaveBeenCalled();+ expect(continuation.dispatchTurn).not.toHaveBeenCalled();+ expect(continuation.setThreadError).not.toHaveBeenCalled();+ });++ it("sets the missing-branch error without running the supplied continuation", async () => {+ const { gate } = sendScenario({+ effectiveEnvMode: "worktree",+ defaultBranchName: null,+ currentGitBranch: null,+ });+ expect(gate).toEqual({+ state: "missing-base-branch",+ errorMessage:+ "No base branch found. Create or check out a Git branch, or choose Current checkout in Project settings.",+ });++ const continuation = makeBoundaryContinuationSpies();+ const outcome = await crossWorktreeSendBoundary({+ gate,+ requiresWorktreeCreation: true,+ threadId,+ setThreadError: continuation.setThreadError,+ send: continuation.send,+ });+ expect(outcome).toEqual({ outcome: "blocked-missing-base-branch" });+ expect(continuation.setThreadError).toHaveBeenCalledExactlyOnceWith(+ threadId,+ WORKTREE_BASE_BRANCH_MISSING_ERROR,+ );+ expect(continuation.send).not.toHaveBeenCalled();+ expect(continuation.clearPrompt).not.toHaveBeenCalled();+ expect(continuation.clearAttachments).not.toHaveBeenCalled();+ expect(continuation.clearContexts).not.toHaveBeenCalled();+ expect(continuation.appendOptimisticMessage).not.toHaveBeenCalled();+ expect(continuation.dispatchTurn).not.toHaveBeenCalled();+ });++ it("runs the supplied continuation once for a resolved worktree base", async () => {+ const { gate } = sendScenario({+ effectiveEnvMode: "worktree",+ defaultBranchName: "origin/main",+ });+ expect(gate).toEqual({ state: "ready" });++ const continuation = makeBoundaryContinuationSpies();+ const outcome = await crossWorktreeSendBoundary({+ gate,+ requiresWorktreeCreation: true,+ threadId,+ setThreadError: continuation.setThreadError,+ send: continuation.send,+ });+ expect(outcome).toEqual({ outcome: "sent", result: "turn-started" });+ expect(continuation.send).toHaveBeenCalledTimes(1);+ expect(continuation.dispatchTurn).toHaveBeenCalledTimes(1);+ expect(continuation.setThreadError).not.toHaveBeenCalled();+ });+});++describe("buildFirstSendBootstrap", () => {+ const createThread = {+ projectId,+ title: "New thread",+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },+ runtimeMode: "approval-required" as const,+ interactionMode: "default" as const,+ branch: null,+ worktreePath: null,+ createdAt: now,+ };+ const base = {+ isLocalDraftThread: true,+ baseBranchForWorktree: null,+ createThread,+ projectCwd: "/repo",+ worktreeBranch: "t3/tmp-branch",+ startFromOrigin: false,+ };++ it("sends a local-checkout draft with its model and runtime mode and no worktree", () => {+ expect(buildFirstSendBootstrap(base)).toEqual({ createThread });+ });++ it("prepares a worktree only when a base branch resolved", () => {+ expect(buildFirstSendBootstrap({ ...base, baseBranchForWorktree: "main" })).toEqual({+ createThread,+ prepareWorktree: {+ projectCwd: "/repo",+ baseBranch: "main",+ branch: "t3/tmp-branch",+ },+ runSetupScript: true,+ });+ expect(+ buildFirstSendBootstrap({ ...base, baseBranchForWorktree: "main", startFromOrigin: true })+ ?.prepareWorktree?.startFromOrigin,+ ).toBe(true);+ });++ it("carries no bootstrap for a started server thread", () => {+ expect(buildFirstSendBootstrap({ ...base, isLocalDraftThread: false })).toBeUndefined();+ });+});++describe("resolveComposerBranchForSend", () => {+ const worktreeSend = {+ effectiveEnvMode: "worktree" as const,+ explicitBranch: null,+ activeWorktreePath: null,+ defaultBranchName: "origin/main",+ currentGitBranch: "feature/checked-out",+ refsLoadPending: false,+ };++ it("lets an explicit branch win over every fallback", () => {+ expect(+ resolveComposerBranchForSend({ ...worktreeSend, explicitBranch: "feature/picked" }),+ ).toBe("feature/picked");+ expect(+ resolveComposerBranchForSend({+ ...worktreeSend,+ effectiveEnvMode: "local",+ explicitBranch: "feature/picked",+ }),+ ).toBe("feature/picked");+ });++ it("falls back to the repo default branch for a new worktree send", () => {+ expect(resolveComposerBranchForSend(worktreeSend)).toBe("origin/main");+ });++ it("uses the checked-out branch when no default branch is known", () => {+ expect(resolveComposerBranchForSend({ ...worktreeSend, defaultBranchName: null })).toBe(+ "feature/checked-out",+ );+ });++ it("stays unresolved before refs have loaded", () => {+ expect(resolveComposerBranchForSend({ ...worktreeSend, refsLoadPending: true })).toBeNull();+ });++ it("stays unresolved when neither a default nor a checked-out branch exists", () => {+ expect(+ resolveComposerBranchForSend({+ ...worktreeSend,+ defaultBranchName: null,+ currentGitBranch: null,+ }),+ ).toBeNull();+ });++ it("does not invent a worktree base for local sends", () => {+ expect(resolveComposerBranchForSend({ ...worktreeSend, effectiveEnvMode: "local" })).toBeNull();+ });++ it("does not rebase an existing worktree onto the default branch", () => {+ expect(+ resolveComposerBranchForSend({ ...worktreeSend, activeWorktreePath: "/tmp/worktree" }),+ ).toBeNull();+ });+});+describe("resolveBackgroundDraftWorkspaceOptions", () => {it("keeps New worktree selected without reusing the launched worktree", () => {expect(diff --git a/apps/web/src/components/ChatView.logic.ts b/apps/web/src/components/ChatView.logic.tsindex 83bea23b6..e0660fd98 100644--- a/apps/web/src/components/ChatView.logic.ts+++ b/apps/web/src/components/ChatView.logic.ts@@ -1,3 +1,4 @@+import type { StartThreadTurnInput } from "@t3tools/client-runtime/operations";import {type EnvironmentId,isProviderDriverKind,@@ -326,6 +327,161 @@ export function resolveSendEnvMode(input: {return input.isGitRepo ? input.requestedEnvMode : "local";}+export const WORKTREE_BRANCHES_LOADING_REASON = "Loading repository branches";+export const WORKTREE_BASE_BRANCH_MISSING_ERROR =+ "No base branch found. Create or check out a Git branch, or choose Current checkout in Project settings.";++export type WorktreeSendGate =+ | { state: "ready" }+ | { state: "loading"; sendDisabledReason: string }+ | { state: "missing-base-branch"; errorMessage: string };++/**+ * Gates a first send that must create a worktree. While refs load, the send+ * button is disabled with a loading reason. Once refs settle without any+ * resolvable base branch, send stays enabled so submitting surfaces an+ * actionable error instead of a dead button.+ */+export function resolveWorktreeSendGate(input: {+ needsWorktreeBaseBranch: boolean;+ refsLoadPending: boolean;+ resolvedBranch: string | null;+}): WorktreeSendGate {+ if (!input.needsWorktreeBaseBranch || input.resolvedBranch !== null) {+ return { state: "ready" };+ }+ if (input.refsLoadPending) {+ return { state: "loading", sendDisabledReason: WORKTREE_BRANCHES_LOADING_REASON };+ }+ return { state: "missing-base-branch", errorMessage: WORKTREE_BASE_BRANCH_MISSING_ERROR };+}++/**+ * Runs the supplied send continuation only when worktree branch resolution+ * permits it. Loading blocks silently. A missing base branch writes the+ * actionable thread error and blocks.+ */+export async function crossWorktreeSendBoundary<Result>(input: {+ gate: WorktreeSendGate;+ requiresWorktreeCreation: boolean;+ threadId: ThreadId;+ setThreadError: (threadId: ThreadId, error: string | null) => void;+ send: () => Result | Promise<Result>;+}): Promise<+ | { outcome: "sent"; result: Result }+ | { outcome: "blocked-loading" }+ | { outcome: "blocked-missing-base-branch" }+> {+ if (input.requiresWorktreeCreation && input.gate.state === "loading") {+ return { outcome: "blocked-loading" };+ }+ if (input.requiresWorktreeCreation && input.gate.state === "missing-base-branch") {+ input.setThreadError(input.threadId, input.gate.errorMessage);+ return { outcome: "blocked-missing-base-branch" };+ }+ return { outcome: "sent", result: await input.send() };+}++type FirstSendTurnInput = Required<+ Pick<+ StartThreadTurnInput,+ | "threadId"+ | "message"+ | "modelSelection"+ | "titleSeed"+ | "runtimeMode"+ | "interactionMode"+ | "createdAt"+ >+> &+ Pick<StartThreadTurnInput, "bootstrap">;++/** Builds the complete `thread.turn.start` input for ChatView's first-send path. */+export function buildFirstSendTurnInput(input: FirstSendTurnInput): StartThreadTurnInput {+ return {+ threadId: input.threadId,+ message: input.message,+ modelSelection: input.modelSelection,+ titleSeed: input.titleSeed,+ runtimeMode: input.runtimeMode,+ interactionMode: input.interactionMode,+ ...(input.bootstrap === undefined ? {} : { bootstrap: input.bootstrap }),+ createdAt: input.createdAt,+ };+}++/**+ * Builds the first-turn bootstrap for a send. A local draft always carries+ * `createThread` so the server can materialize it; `prepareWorktree` is added+ * only when a worktree send resolved its base branch. Any other send carries+ * no bootstrap.+ */+export function buildFirstSendBootstrap<CreateThread>(input: {+ isLocalDraftThread: boolean;+ baseBranchForWorktree: string | null;+ createThread: CreateThread;+ projectCwd: string;+ worktreeBranch: string;+ startFromOrigin: boolean;+}):+ | {+ createThread?: CreateThread;+ prepareWorktree?: {+ projectCwd: string;+ baseBranch: string;+ branch: string;+ startFromOrigin?: boolean;+ };+ runSetupScript?: boolean;+ }+ | undefined {+ if (!input.isLocalDraftThread && input.baseBranchForWorktree === null) {+ return undefined;+ }+ return {+ ...(input.isLocalDraftThread ? { createThread: input.createThread } : {}),+ ...(input.baseBranchForWorktree !== null+ ? {+ prepareWorktree: {+ projectCwd: input.projectCwd,+ baseBranch: input.baseBranchForWorktree,+ branch: input.worktreeBranch,+ ...(input.startFromOrigin ? { startFromOrigin: true } : {}),+ },+ runSetupScript: true,+ }+ : {}),+ };+}++/**+ * Resolves the branch a send carries now that the composer has no branch+ * selector. An explicit choice (draft context, thread metadata, or a pending+ * override) always wins. A first send in worktree mode falls back to the repo+ * default branch (origin/HEAD), then the checked-out branch, once refs have+ * loaded. Local sends and existing worktrees never invent a base branch, and+ * an unresolved worktree base keeps the existing send-time error.+ */+export function resolveComposerBranchForSend(input: {+ effectiveEnvMode: DraftThreadEnvMode;+ explicitBranch: string | null;+ activeWorktreePath: string | null;+ defaultBranchName: string | null;+ currentGitBranch: string | null;+ refsLoadPending: boolean;+}): string | null {+ if (input.explicitBranch) {+ return input.explicitBranch;+ }+ if (input.effectiveEnvMode !== "worktree" || input.activeWorktreePath) {+ return null;+ }+ if (input.refsLoadPending) {+ return null;+ }+ return input.defaultBranchName ?? input.currentGitBranch;+}+export function resolveBackgroundDraftWorkspaceOptions(input: {envMode: DraftThreadEnvMode;branch: string | null;diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxdeleted file mode 100644index f0188af47..000000000--- a/apps/web/src/components/ChatView.tsx+++ /dev/null@@ -1,7334 +0,0 @@-import {- type ApprovalRequestId,- DEFAULT_MODEL,- defaultInstanceIdForDriver,- type EnvironmentId,- type MessageId,- type ModelSelection,- type ProjectScript,- type ProjectId,- type ProviderApprovalDecision,- type PreviewAnnotationPayload,- ProviderInstanceId,- type ServerProvider,- type ResolvedKeybindingsConfig,- type ScopedThreadRef,- type ThreadId,- type TurnId,- type KeybindingCommand,- OrchestrationThreadActivity,- ProviderInteractionMode,- ProviderDriverKind,- RuntimeMode,- TerminalOpenInput,-} from "@t3tools/contracts";-import {- connectionStatusTitle,- type EnvironmentConnectionPresentation,-} from "@t3tools/client-runtime/connection";-import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors";-import {- changeRequestAutoSettles,- effectiveSettled,- effectiveSnoozed,- threadWokeAt,-} from "@t3tools/client-runtime/state/thread-settled";-import {- codexFeedbackMessage,- parseCodexFeedbackCommand,- submitCodexFeedback,- type CodexFeedbackSubmission,-} from "@t3tools/client-runtime/state/threads";-import {- parseScopedThreadKey,- scopedThreadKey,- scopeProjectRef,- scopeThreadRef,-} from "@t3tools/client-runtime/environment";-import {- applyClaudePromptEffortPrefix,- createModelSelection,- resolvePromptInjectedEffort,-} from "@t3tools/shared/model";-import { CHAT_LIST_ANCHOR_OFFSET } from "@t3tools/shared/chatList";-import { projectScriptCwd, projectScriptRuntimeEnv } from "@t3tools/shared/projectScripts";-import { truncate } from "@t3tools/shared/String";-import {- getTerminalLabel,- nextTerminalId,- resolveTerminalSessionLabel,-} from "@t3tools/shared/terminalLabels";-import { Debouncer } from "@tanstack/react-pacer";-import { useAtomValue } from "@effect/atom-react";-import {- lazy,- memo,- Suspense,- useCallback,- useEffect,- useLayoutEffect,- useMemo,- useRef,- useState,-} from "react";-import { flushSync } from "react-dom";-import { useNavigate } from "@tanstack/react-router";-import { useShallow } from "zustand/react/shallow";-import {- isAtomCommandInterrupted,- mapAtomCommandResult,- settlePromise,- squashAtomCommandFailure,- type AtomCommandResult,-} from "@t3tools/client-runtime/state/runtime";-import * as Cause from "effect/Cause";-import * as Schema from "effect/Schema";-import { AsyncResult } from "effect/unstable/reactivity";-import { isElectron } from "../env";-import { readLocalApi } from "../localApi";-import { useDiffPanelStore } from "../diffPanelStore";-import {- collapseExpandedComposerCursor,- type ComposerSubmissionIntent,- parseStandaloneComposerSlashCommand,-} from "../composer-logic";-import {- derivePendingApprovals,- derivePendingUserInputs,- derivePhase,- deriveTimelineEntries,- deriveActiveWorkStartedAt,- deriveActivePlanState,- deriveTurnPlans,- findLatestProposedPlan,- deriveWorkLogEntries,- hasActionableProposedPlan,- isLatestTurnSettled,-} from "../session-logic";-import { type LegendListRef } from "@legendapp/list/react";-import { getAnchoredTurnMetrics, type TimelineScrollMode } from "./chat/timelineScrollAnchoring";-import {- buildPendingUserInputAnswers,- derivePendingUserInputProgress,- setPendingUserInputCustomAnswer,- togglePendingUserInputOptionSelection,- type PendingUserInputDraftAnswer,-} from "../pendingUserInput";-import { useUiStateStore } from "../uiStateStore";-import {- buildPlanImplementationThreadTitle,- buildPlanImplementationPrompt,- resolvePlanFollowUpSubmission,-} from "../proposedPlan";-import {- DEFAULT_INTERACTION_MODE,- DEFAULT_RUNTIME_MODE,- DEFAULT_THREAD_TERMINAL_ID,- MAX_TERMINALS_PER_GROUP,- type ChatMessage,- type SessionPhase,- type Thread,- type TurnDiffSummary,-} from "../types";-import { useTheme } from "../hooks/useTheme";-import { writeTextToClipboard } from "../hooks/useCopyToClipboard";-import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";-import { isCommandPaletteOpen } from "../commandPaletteBus";-import { buildTemporaryWorktreeBranchName } from "@t3tools/shared/git";-import { useMediaQuery } from "../hooks/useMediaQuery";-import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../rightPanelLayout";-import {- selectActiveRightPanel,- selectActiveRightPanelSurface,- selectThreadRightPanelState,- type RightPanelSurface,- updatePullRequestTabStatus,- useRightPanelStore,-} from "../rightPanelStore";-import {- isPreviewSupportedInRuntime,- setActivePreviewTab,- useThreadPreviewState,-} from "../previewStateStore";-import { previewRuntimeTabId } from "../browser/previewRuntimeTabId";-import { addBrowserSurface } from "./preview/addBrowserSurface";-import { closePreviewSession } from "./preview/closePreviewSession";-import { ThreadPreviewMiniPlayer } from "./preview/ThreadPreviewMiniPlayer";-import { subscribePreviewAction } from "./preview/previewActionBus";-import { getConfiguredPreviewUrls } from "./preview/previewEmptyStateLogic";-import { makeWorkspaceFileDropHandlers } from "./chat/workspaceFileDrop";-import {- selectThreadPreviewMiniPlayer,- usePreviewMiniPlayerStore,-} from "../previewMiniPlayerStore";-import { isThreadOwnPullRequest } from "./pullRequest/pullRequestDetail.logic";-import { PullRequestDetailPanel } from "./pullRequest/PullRequestDetailPanel";-import { PullRequestDetailGhost } from "./pullRequest/PullRequestGhosts";-import { PullRequestsUnavailableState } from "./pullRequest/PullRequestsUnavailableState";-import { RightPanelTabs, type PullRequestTabStatus } from "./RightPanelTabs";-import { AgentsPanel } from "./AgentsPanel";-import {- deriveAgentPanelModel,- foldSubagentActivities,-} from "@t3tools/client-runtime/state/subagentRuntime";-import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider";-import { BranchToolbar } from "./BranchToolbar";-import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";-import ThreadTerminalDrawer from "./ThreadTerminalDrawer";-import {- AlarmClockIcon,- CheckCircle2Icon,- ChevronDownIcon,- GitBranchIcon,- Minimize2Icon,- PaperclipIcon,- WifiOffIcon,-} from "lucide-react";-import { cn, randomHex } from "~/lib/utils";-import { stackedThreadToast, toastManager } from "./ui/toast";-import { decodeProjectScriptKeybindingRule } from "~/lib/projectScriptKeybindings";-import { type NewProjectScriptInput } from "./ProjectScriptsControl";-import {- buildProjectScript,- commandForProjectScript,- nextProjectScriptId,- projectScriptIdFromCommand,-} from "~/projectScripts";-import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";-import { useBrowserHistoryStore } from "~/browserHistoryStore";-import { registerFaviconProjectForThread } from "~/browserFaviconStore";-import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";-import {- applyProviderInstanceSettings,- deriveProviderInstanceEntries,- NO_PROVIDER_MODEL_SELECTION,-} from "../providerInstances";-import {- useClientSettings,- useClientSettingsHydrated,- useEnvironmentSettings,-} from "../hooks/useSettings";-import { useNowMinute } from "../hooks/useNowMinute";-import { useNewThreadHandler } from "../hooks/useHandleNewThread";-import { useThreadActions } from "../hooks/useThreadActions";-import { resolveAppModelSelectionForInstance } from "../modelSelection";-import { confirmTerminalClose, isTerminalCloseConfirmPending } from "../lib/terminalCloseConfirm";-import { getTerminalFocusOwner } from "../lib/terminalFocus";-import {- preventRepeatedTerminalCloseShortcut,- preventTerminalCloseShortcut,-} from "../lib/terminalCloseShortcut";-import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";-import {- derivePhysicalProjectKey,- deriveLogicalProjectKeyFromSettings,- selectProjectGroupingSettings,-} from "../logicalProject";-import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping";-import { buildDraftThreadRouteParams, buildThreadRouteParams } from "../threadRoutes";-import {- beginBackgroundDraftSubmissionByRef,- clearBackgroundDraftSubmissionByRef,- composerDraftHasUserContent,- type ComposerImageAttachment,- type DraftThreadEnvMode,- finalizePromotedDraftThreadByRef,- markPromotedDraftThreadByRef,- useComposerDraftStore,- type DraftId,-} from "../composerDraftStore";-import {- appendTerminalContextsToPrompt,- formatTerminalContextLabel,- type TerminalContextDraft,- type TerminalContextSelection,-} from "../lib/terminalContext";-import {- appendElementContextsToPrompt,- type ElementContextDraft,- formatElementContextLabel,-} from "../lib/elementContext";-import { appendPreviewAnnotationPrompt } from "../lib/previewAnnotation";-import { appendReviewCommentsToPrompt, type ReviewCommentContext } from "../reviewCommentContext";-import { environmentCatalog } from "../connection/catalog";-import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";-import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions";-import { projectEnvironment } from "../state/projects";-import { useEnvironmentQuery } from "../state/query";-import {- primaryServerAvailableEditorsAtom,- primaryServerKeybindingsAtom,- primaryServerSettingsAtom,- serverEnvironment,-} from "../state/server";-import { terminalEnvironment } from "../state/terminal";-import { threadEnvironment, useEnvironmentThread } from "../state/threads";-import {- requestOlderThreadTurns,- threadHasOlderTurns,-} from "@t3tools/client-runtime/state/threads";-import { vcsEnvironment } from "../state/vcs";-import { useEnvironments, usePrimaryEnvironment } from "../state/environments";-import {- useProject,- useProjects,- useThread,- useThreadRefs,- useThreadShell,-} from "../state/entities";-import { environmentShell } from "../state/shell";-import { ChatComposer, type ChatComposerHandle } from "./chat/ChatComposer";-import { DraftHeroHeadline } from "./chat/DraftHeroHeadline";-import { ExpandedImageDialog } from "./chat/ExpandedImageDialog";-import { PullRequestThreadDialog } from "./PullRequestThreadDialog";-import { MessagesTimeline } from "./chat/MessagesTimeline";-import { resolveTimelineIsAtEnd } from "./chat/MessagesTimeline.logic";-import { ChatHeader } from "./chat/ChatHeader";-import { PanelLayoutControls, RightPanelMaximizeControl } from "./chat/PanelLayoutControls";-import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview";-import { NoActiveThreadState } from "./NoActiveThreadState";-import { WorkspacePageHeader } from "./WorkspacePageHeader";-import {- resolveEffectiveEnvMode,- resolveLocalCheckoutBranchMismatch,- shouldShowComposerContextStrip,- shouldShowEnvironmentIndicator,-} from "./BranchToolbar.logic";-import {- getProviderStatusBannerKey,- ProviderStatusBanner,- shouldShowProviderStatusBanner,-} from "./chat/ProviderStatusBanner";-import {- dismissThreadErrorBannerForSession,- getThreadErrorBannerKey,- isThreadErrorBannerDismissedForSession,- shouldShowThreadErrorBanner,- ThreadErrorBanner,-} from "./chat/ThreadErrorBanner";-import {- resolveDisplayedThreadPr,- threadChangeRequestSnapshotsAtom,- useLinkedThreadPullRequest,-} from "./ThreadStatusIndicators";-import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";-import {- hasAvailableClaudeCompactionProvider,- hasDismissedResumeCompaction,- shouldOfferResumeCompaction,-} from "./chat/ContextWindowMeter.logic";-import { deriveLatestContextWindowSnapshot, formatContextWindowTokens } from "../lib/contextWindow";-import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";-import {- DRAFT_HERO_TRANSITION_ANIMATION_ID,- DRAFT_HERO_TRANSITION_DURATION_MS,- DRAFT_HERO_TRANSITION_EASING,- MOBILE_COMPOSER_VIEW_TRANSITION_NAME,- MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,- runMobileComposerTransition,-} from "./chat/draftHeroTransition";-import {- MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,- branchMismatchKey,- buildExpiredTerminalContextToastCopy,- buildLocalDraftThread,- buildLoadingThreadFromShell,- buildThreadTurnInterruptInput,- collectUserMessageBlobPreviewUrls,- createLocalDispatchSnapshot,- deriveComposerSendState,- dismissBranchMismatchForSession,- hasEnvironmentReconnectWarningGraceElapsed,- scheduleEnvironmentReconnectWarning,- hasServerAcknowledgedLocalDispatch,- isBranchMismatchDismissedForSession,- shouldDockDraftHeroForSubmission,- shouldReleaseTimelineAnchorForToolActivity,- shouldShowBranchMismatchBanner,- getStartedThreadModelChangeBlockReason,- LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,- LastInvokedScriptByProjectSchema,- type LocalDispatchSnapshot,- PullRequestDialogState,- cloneComposerImageForRetry,- deriveLockedProvider,- readFileAsDataUrl,- reconcileMountedTerminalThreadIds,- resolveBackgroundDraftWorkspaceOptions,- resolveDraftHeroState,- resolveThreadMetadataUpdateForNextTurn,- resolveSendEnvMode,- revokeBlobPreviewUrl,- revokeUserMessagePreviewUrls,- shouldWriteThreadErrorToCurrentServerThread,- startNewThreadForProject,- waitForStartedServerThread,-} from "./ChatView.logic";-import type { ThreadSyncPhase } from "../threadSync";-import { useLocalStorage } from "~/hooks/useLocalStorage";-import { useComposerHandleContext } from "../composerHandleContext";-import {- awaitAttachmentUploads,- getUploadedAttachments,- releaseAttachmentUploads,- startAttachmentUpload,-} from "../lib/attachmentUploadQueue";-import { sanitizeThreadErrorMessage } from "~/rpc/transportError";-import { RightPanelSheet } from "./RightPanelSheet";-import { previewEnvironment } from "../state/preview";-import { useAtomCommand } from "../state/use-atom-command";-import { Button } from "./ui/button";-import {- AlertDialog,- AlertDialogClose,- AlertDialogDescription,- AlertDialogFooter,- AlertDialogHeader,- AlertDialogPopup,- AlertDialogTitle,-} from "./ui/alert-dialog";-import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";-import { ServerUpdateAction, ServerUpdateProgress } from "./ServerUpdateAction";-import {- buildVersionMismatchDismissalKey,- dismissVersionMismatch,- isVersionMismatchDismissed,- resolveServerConfigVersionMismatch,- resolveServerSelfUpdateCapability,- serverUpdateGuidance,-} from "../versionSkew";-import { useAssetUrls } from "../assets/assetUrls";--const IMAGE_ONLY_BOOTSTRAP_PROMPT =- "[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]";-const EMPTY_ACTIVITIES: OrchestrationThreadActivity[] = [];-const EMPTY_PROVIDERS: ServerProvider[] = [];-const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = [];-const EMPTY_PENDING_USER_INPUT_ANSWERS: Record<string, PendingUserInputDraftAnswer> = {};-function useDraftHeroLayoutTransition(isDraftHeroState: boolean) {- const transitionGroupRef = useRef<HTMLDivElement | null>(null);- const composerAnchorRef = useRef<HTMLDivElement | null>(null);- const previousStateRef = useRef(isDraftHeroState);- const previousComposerRectRef = useRef<DOMRect | null>(null);- const animationRef = useRef<Animation | null>(null);- const attachTransitionGroupRef = (element: HTMLDivElement | null) => {- transitionGroupRef.current = element;- };- const attachComposerAnchorRef = (element: HTMLDivElement | null) => {- composerAnchorRef.current = element;- };- const captureComposerRect = () => {- previousComposerRectRef.current = composerAnchorRef.current?.getBoundingClientRect() ?? null;- };-- useLayoutEffect(() => {- const transitionGroup = transitionGroupRef.current;- const nextComposerRect = composerAnchorRef.current?.getBoundingClientRect() ?? null;- const stateChanged = previousStateRef.current !== isDraftHeroState;- const prefersReducedMotion =- typeof window !== "undefined" &&- window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;- const mobileComposerTransitionActive =- typeof document !== "undefined" &&- document.documentElement.dataset.mobileComposerRouteTransition === "true";-- animationRef.current?.cancel();- animationRef.current = null;-- const previousComposerRect = previousComposerRectRef.current;- if (- stateChanged &&- !prefersReducedMotion &&- !mobileComposerTransitionActive &&- transitionGroup &&- previousComposerRect &&- nextComposerRect &&- typeof transitionGroup.animate === "function"- ) {- const translateX = previousComposerRect.left - nextComposerRect.left;- const translateY = previousComposerRect.top - nextComposerRect.top;- if (Math.abs(translateX) >= 0.5 || Math.abs(translateY) >= 0.5) {- const animation = transitionGroup.animate(- [- { transform: `translate3d(${translateX}px, ${translateY}px, 0)` },- { transform: "translate3d(0, 0, 0)" },- ],- {- duration: DRAFT_HERO_TRANSITION_DURATION_MS,- easing: DRAFT_HERO_TRANSITION_EASING,- },- );- animation.id = DRAFT_HERO_TRANSITION_ANIMATION_ID;- animationRef.current = animation;- void animation.finished- .catch(() => undefined)- .then(() => {- if (animationRef.current !== animation) {- return;- }- animationRef.current = null;- });- }- }-- previousStateRef.current = isDraftHeroState;- previousComposerRectRef.current = nextComposerRect;- }, [isDraftHeroState]);-- return [attachTransitionGroupRef, attachComposerAnchorRef, captureComposerRect] as const;-}-const PreviewPanel = lazy(() =>- import("./preview/PreviewPanel").then((module) => ({ default: module.PreviewPanel })),-);-const DiffPanel = lazy(() => import("./DiffPanel"));-const FilePreviewPanel = lazy(() => import("./files/FilePreviewPanel"));-const EMPTY_PENDING_FILE_SURFACE_IDS: ReadonlySet<string> = new Set();-const TYPE_TO_FOCUS_EDITABLE_SELECTOR = [- "input",- "textarea",- "select",- '[contenteditable="true"]',- '[contenteditable="plaintext-only"]',- '[role="textbox"]',-].join(",");-const TYPE_TO_FOCUS_INTERACTIVE_SELECTOR = [- "button",- "a[href]",- "summary",- '[role="button"]',- '[role="checkbox"]',- '[role="menuitem"]',- '[role="option"]',- '[role="radio"]',- '[role="switch"]',- '[role="tab"]',-].join(",");-const TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR = [- '[data-slot="dialog"]',- '[data-slot="menu-popup"]',- '[data-slot="select-popup"]',- '[data-slot="popover-popup"]',- '[data-slot="combobox-popup"]',- '[data-slot="autocomplete-popup"]',-].join(",");--type EnvironmentUnavailableState = {- readonly environmentId: EnvironmentId;- readonly label: string;- readonly connection: EnvironmentConnectionPresentation;-};--function eventPathContainsSelector(event: Event, selector: string): boolean {- const path = event.composedPath();- if (path.length === 0 && event.target) {- path.push(event.target);- }- return path.some((target) => target instanceof Element && target.closest(selector));-}--function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {- if (event.defaultPrevented || event.isComposing) return false;- if (event.metaKey || event.ctrlKey || event.altKey) return false;- if (event.key.length !== 1) return false;-- if (eventPathContainsSelector(event, TYPE_TO_FOCUS_EDITABLE_SELECTOR)) return false;- if (eventPathContainsSelector(event, TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false;- if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false;-- // The right-panel surface launcher claims its shortcut letters while it is- // visible (data attribute set in RightPanelTabs); those keys open surfaces- // instead of typing into the composer.- const launcherKeys = document- .querySelector("[data-surface-launcher-keys]")- ?.getAttribute("data-surface-launcher-keys");- if (launcherKeys && launcherKeys.toLowerCase().includes(event.key.toLowerCase())) return false;-- return true;-}--function formatOutgoingPrompt(params: {- provider: ProviderDriverKind;- model: string | null;- models: ReadonlyArray<ServerProvider["models"][number]>;- effort: string | null;- text: string;-}): string {- const caps = getProviderModelCapabilities(params.models, params.model, params.provider);- const promptEffort = resolvePromptInjectedEffort(caps, params.effort);- return applyClaudePromptEffortPrefix(params.text, promptEffort);-}-const SCRIPT_TERMINAL_COLS = 120;-const SCRIPT_TERMINAL_ROWS = 30;--type ChatViewProps =- | {- environmentId: EnvironmentId;- threadId: ThreadId;- onDiffPanelOpen?: () => void;- reserveTitleBarControlInset?: boolean;- forceExpandedMobileComposer?: boolean;- threadSyncPhase?: ThreadSyncPhase | null;- routeKind: "server";- draftId?: never;- }- | {- environmentId: EnvironmentId;- threadId: ThreadId;- onDiffPanelOpen?: () => void;- reserveTitleBarControlInset?: boolean;- forceExpandedMobileComposer?: boolean;- threadSyncPhase?: never;- routeKind: "draft";- draftId: DraftId;- };--interface TerminalLaunchContext {- threadId: ThreadId;- cwd: string;- worktreePath: string | null;-}--type PersistentTerminalLaunchContext = Pick<TerminalLaunchContext, "cwd" | "worktreePath">;--function useLocalDispatchState(input: {- activeThread: Thread | undefined;- activeLatestTurn: Thread["latestTurn"] | null;- phase: SessionPhase;- activePendingApproval: ApprovalRequestId | null;- activePendingUserInput: ApprovalRequestId | null;- threadError: string | null | undefined;-}) {- const [localDispatch, setLocalDispatch] = useState<LocalDispatchSnapshot | null>(null);- const latestUserMessage = input.activeThread?.messages.findLast(- (message) => message.role === "user",- );- const latestUserMessageId = latestUserMessage?.id ?? null;-- const resetLocalDispatch = useCallback(() => {- setLocalDispatch(null);- }, []);-- const serverAcknowledgedLocalDispatch = useMemo(- () =>- hasServerAcknowledgedLocalDispatch({- localDispatch,- phase: input.phase,- latestTurn: input.activeLatestTurn,- latestUserMessageId,- session: input.activeThread?.session ?? null,- hasPendingApproval: input.activePendingApproval !== null,- hasPendingUserInput: input.activePendingUserInput !== null,- threadError: input.threadError,- }),- [- input.activeLatestTurn,- input.activePendingApproval,- input.activePendingUserInput,- input.activeThread?.session,- input.phase,- input.threadError,- latestUserMessageId,- localDispatch,- ],- );- const activeLocalDispatch = serverAcknowledgedLocalDispatch ? null : localDispatch;- const beginLocalDispatch = useCallback(- (options?: { preparingWorktree?: boolean; submissionIntent?: ComposerSubmissionIntent }) => {- const preparingWorktree = Boolean(options?.preparingWorktree);- setLocalDispatch((current) => {- const active = serverAcknowledgedLocalDispatch ? null : current;- if (active) {- const submissionIntent = options?.submissionIntent ?? active.submissionIntent;- return active.preparingWorktree === preparingWorktree &&- active.submissionIntent === submissionIntent- ? active- : { ...active, preparingWorktree, submissionIntent };- }- return createLocalDispatchSnapshot(input.activeThread, options);- });- },- [input.activeThread, serverAcknowledgedLocalDispatch],- );-- return {- beginLocalDispatch,- resetLocalDispatch,- localDispatchStartedAt: activeLocalDispatch?.startedAt ?? null,- latestUserMessageAt: latestUserMessage?.createdAt ?? null,- isPreparingWorktree: activeLocalDispatch?.preparingWorktree ?? false,- isSendBusy: activeLocalDispatch !== null,- backgroundSubmissionPending: localDispatch?.submissionIntent === "background",- };-}--/** Same terminal ids (order ignored) — avoids reconcile when only server session ordering differs. */-function terminalIdListsEqual(left: readonly string[], right: readonly string[]): boolean {- if (left.length !== right.length) {- return false;- }- if (left.length === 0) {- return true;- }- const sortedLeft = left.toSorted((a, b) => a.localeCompare(b));- const sortedRight = right.toSorted((a, b) => a.localeCompare(b));- for (let index = 0; index < sortedLeft.length; index += 1) {- if (sortedLeft[index] !== sortedRight[index]) {- return false;- }- }- return true;-}--/**- * Server knows about fewer sessions than the client, but every server id still exists locally.- * Typical right after `terminal.open`: known-session list lags; reconciling would drop the new id- * and later re-add it as a separate group (no split layout).- */-function serverTerminalIdsStrictSubsetOfClient(- serverIds: readonly string[],- clientIds: readonly string[],-): boolean {- if (serverIds.length >= clientIds.length || clientIds.length === 0) {- return false;- }- const clientSet = new Set(clientIds);- for (const id of serverIds) {- if (!clientSet.has(id)) {- return false;- }- }- return true;-}--interface PersistentThreadTerminalDrawerProps {- threadRef: { environmentId: EnvironmentId; threadId: ThreadId };- threadId: ThreadId;- visible: boolean;- launchContext: PersistentTerminalLaunchContext | null;- focusRequestId: number;- splitShortcutLabel: string | undefined;- splitVerticalShortcutLabel: string | undefined;- newShortcutLabel: string | undefined;- closeShortcutLabel: string | undefined;- keybindings: ResolvedKeybindingsConfig;- onAddTerminalContext: (selection: TerminalContextSelection) => void;-}--const PersistentThreadTerminalDrawer = memo(function PersistentThreadTerminalDrawer({- threadRef,- threadId,- visible,- launchContext,- focusRequestId,- splitShortcutLabel,- splitVerticalShortcutLabel,- newShortcutLabel,- closeShortcutLabel,- keybindings,- onAddTerminalContext,-}: PersistentThreadTerminalDrawerProps) {- const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");- const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");- const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close");- const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));- const serverThread = useThread(threadRef, { waitForShell: draftThread !== null });- const projectRef = serverThread- ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)- : draftThread- ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)- : null;- const project = useProject(projectRef);- const terminalUiState = useTerminalUiStateStore((state) =>- selectThreadTerminalUiState(state.terminalUiStateByThreadKey, threadRef),- );- const knownTerminalSessions = useKnownTerminalSessions({- environmentId: threadRef.environmentId,- threadId,- });- const panelSurfaces = useRightPanelStore(- (state) => selectThreadRightPanelState(state.byThreadKey, threadRef).surfaces,- );- const panelTerminalIds = useMemo(- () =>- new Set(- panelSurfaces.flatMap((surface) =>- surface.kind === "terminal" ? surface.terminalIds : [],- ),- ),- [panelSurfaces],- );- const drawerTerminalSessions = useMemo(- () =>- knownTerminalSessions.filter((session) => !panelTerminalIds.has(session.target.terminalId)),- [knownTerminalSessions, panelTerminalIds],- );- const terminalLabelsById = useMemo(() => {- const next = new Map<string, string>();- for (const session of drawerTerminalSessions) {- next.set(- session.target.terminalId,- resolveTerminalSessionLabel(session.target.terminalId, session.state.summary),- );- }- return next;- }, [drawerTerminalSessions]);- const terminalLaunchLocationsById = useMemo(() => {- const next = new Map<- string,- {- readonly cwd: string;- readonly worktreePath: string | null;- readonly runtimeEnv: Record<string, string>;- }- >();- if (!project) {- return next;- }-- for (const session of drawerTerminalSessions) {- const summary = session.state.summary;- if (!summary) {- continue;- }- const worktreePathForLaunch =- launchContext !== null ? launchContext.worktreePath : summary.worktreePath;- next.set(session.target.terminalId, {- cwd: launchContext?.cwd ?? summary.cwd,- worktreePath: worktreePathForLaunch,- runtimeEnv: projectScriptRuntimeEnv({- project: { cwd: project.workspaceRoot },- worktreePath: worktreePathForLaunch,- }),- });- }-- return next;- }, [drawerTerminalSessions, launchContext, project]);- const serverOrderedTerminalIds = useMemo(- () => drawerTerminalSessions.map((session) => session.target.terminalId),- [drawerTerminalSessions],- );- // Every client-side id source participates in allocation: the server list- // lags fresh opens, and panel terminals are filtered out of the drawer's- // sessions — an id collision attaches two viewports to one PTY session.- const allocatableTerminalIds = useMemo(- () => [- ...new Set([- ...serverOrderedTerminalIds,- ...terminalUiState.terminalIds,- ...panelTerminalIds,- ]),- ],- [panelTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds],- );- const storeSetTerminalHeight = useTerminalUiStateStore((state) => state.setTerminalHeight);- const storeSplitTerminal = useTerminalUiStateStore((state) => state.splitTerminal);- const storeSplitTerminalVertical = useTerminalUiStateStore(- (state) => state.splitTerminalVertical,- );- const storeNewTerminal = useTerminalUiStateStore((state) => state.newTerminal);- const storeSetActiveTerminal = useTerminalUiStateStore((state) => state.setActiveTerminal);- const storeCloseTerminal = useTerminalUiStateStore((state) => state.closeTerminal);- const reconcileTerminalIds = useTerminalUiStateStore((state) => state.reconcileTerminalIds);-- useEffect(() => {- if (terminalIdListsEqual(serverOrderedTerminalIds, terminalUiState.terminalIds)) {- return;- }- if (- serverTerminalIdsStrictSubsetOfClient(serverOrderedTerminalIds, terminalUiState.terminalIds)- ) {- return;- }- reconcileTerminalIds(threadRef, serverOrderedTerminalIds);- }, [reconcileTerminalIds, serverOrderedTerminalIds, terminalUiState.terminalIds, threadRef]);- const [localFocusRequestId, setLocalFocusRequestId] = useState(0);- const worktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;- const effectiveWorktreePath = useMemo(() => {- if (launchContext !== null) {- return launchContext.worktreePath;- }- return worktreePath;- }, [launchContext, worktreePath]);- const cwd = useMemo(- () =>- launchContext?.cwd ??- (project- ? projectScriptCwd({- project: { cwd: project.workspaceRoot },- worktreePath: effectiveWorktreePath,- })- : null),- [effectiveWorktreePath, launchContext?.cwd, project],- );- const runtimeEnv = useMemo(- () =>- project- ? projectScriptRuntimeEnv({- project: { cwd: project.workspaceRoot },- worktreePath: effectiveWorktreePath,- })- : {},- [effectiveWorktreePath, project],- );-- const bumpFocusRequestId = useCallback(() => {- if (!visible) {- return;- }- setLocalFocusRequestId((value) => value + 1);- }, [visible]);-- const setTerminalHeight = useCallback(- (height: number) => {- storeSetTerminalHeight(threadRef, height);- },- [storeSetTerminalHeight, threadRef],- );-- const splitTerminal = useCallback(() => {- if (!cwd) {- return;- }- const terminalId = nextTerminalId(allocatableTerminalIds);- storeSplitTerminal(threadRef, terminalId);- bumpFocusRequestId();- void openTerminal({- environmentId: threadRef.environmentId,- input: {- threadId,- terminalId,- cwd,- ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}),- env: runtimeEnv,- },- });- }, [- allocatableTerminalIds,- bumpFocusRequestId,- cwd,- effectiveWorktreePath,- runtimeEnv,- storeSplitTerminal,- threadId,- threadRef,- openTerminal,- ]);- const splitTerminalVertical = useCallback(() => {- if (!cwd) {- return;- }- const terminalId = nextTerminalId(allocatableTerminalIds);- storeSplitTerminalVertical(threadRef, terminalId);- bumpFocusRequestId();- void openTerminal({- environmentId: threadRef.environmentId,- input: {- threadId,- terminalId,- cwd,- ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}),- env: runtimeEnv,- },- });- }, [- allocatableTerminalIds,- bumpFocusRequestId,- cwd,- effectiveWorktreePath,- openTerminal,- runtimeEnv,- storeSplitTerminalVertical,- threadId,- threadRef,- ]);-- const createNewTerminal = useCallback(() => {- if (!cwd) {- return;- }- const terminalId = nextTerminalId(allocatableTerminalIds);- storeNewTerminal(threadRef, terminalId);- bumpFocusRequestId();- void openTerminal({- environmentId: threadRef.environmentId,- input: {- threadId,- terminalId,- cwd,- ...(effectiveWorktreePath != null ? { worktreePath: effectiveWorktreePath } : {}),- env: runtimeEnv,- },- });- }, [- bumpFocusRequestId,- cwd,- effectiveWorktreePath,- allocatableTerminalIds,- runtimeEnv,- storeNewTerminal,- threadId,- threadRef,- openTerminal,- ]);-- const activateTerminal = useCallback(- (terminalId: string) => {- storeSetActiveTerminal(threadRef, terminalId);- bumpFocusRequestId();- },- [bumpFocusRequestId, storeSetActiveTerminal, threadRef],- );-- const closeTerminal = useCallback(- (terminalId: string) => {- const fallbackExitWrite = () =>- writeTerminal({- environmentId: threadRef.environmentId,- input: { threadId, terminalId, data: "exit\n" },- });-- void (async () => {- const closeResult = await closeTerminalMutation({- environmentId: threadRef.environmentId,- input: {- threadId,- terminalId,- deleteHistory: true,- },- });- if (closeResult._tag === "Failure" && !isAtomCommandInterrupted(closeResult)) {- await fallbackExitWrite();- }- })();-- storeCloseTerminal(threadRef, terminalId);- bumpFocusRequestId();- },- [- bumpFocusRequestId,- storeCloseTerminal,- threadId,- threadRef,- closeTerminalMutation,- writeTerminal,- ],- );-- const handleAddTerminalContext = useCallback(- (selection: TerminalContextSelection) => {- if (!visible) {- return;- }- onAddTerminalContext(selection);- },- [onAddTerminalContext, visible],- );-- if (!project || !terminalUiState.terminalOpen || !cwd) {- return null;- }-- return (- <div className={visible ? undefined : "hidden"}>- <ThreadTerminalDrawer- threadRef={threadRef}- threadId={threadId}- cwd={cwd}- worktreePath={effectiveWorktreePath}- runtimeEnv={runtimeEnv}- visible={visible}- height={terminalUiState.terminalHeight}- // Known-session order is MRU and changes on focus; persisted store order keeps sidebar labels stable.- terminalIds={terminalUiState.terminalIds}- activeTerminalId={terminalUiState.activeTerminalId}- terminalGroups={terminalUiState.terminalGroups}- activeTerminalGroupId={terminalUiState.activeTerminalGroupId}- focusRequestId={focusRequestId + localFocusRequestId + (visible ? 1 : 0)}- onSplitTerminal={splitTerminal}- onSplitTerminalVertical={splitTerminalVertical}- onNewTerminal={createNewTerminal}- splitShortcutLabel={visible ? splitShortcutLabel : undefined}- splitVerticalShortcutLabel={visible ? splitVerticalShortcutLabel : undefined}- newShortcutLabel={visible ? newShortcutLabel : undefined}- closeShortcutLabel={visible ? closeShortcutLabel : undefined}- keybindings={keybindings}- onActiveTerminalChange={activateTerminal}- onCloseTerminal={closeTerminal}- onHeightChange={setTerminalHeight}- onAddTerminalContext={handleAddTerminalContext}- terminalLabelsById={terminalLabelsById}- terminalLaunchLocationsById={terminalLaunchLocationsById}- />- </div>- );-});--interface PersistentThreadTerminalPanelProps {- threadRef: ScopedThreadRef;- surface: Extract<RightPanelSurface, { kind: "terminal" }>;- launchContext: PersistentTerminalLaunchContext | null;- focusRequestId: number;- keybindings: ResolvedKeybindingsConfig;- onAddTerminalContext: (selection: TerminalContextSelection) => void;- onSplitTerminal: () => void;- onSplitTerminalVertical: () => void;- onNewTerminal: () => void;- onActiveTerminalChange: (terminalId: string) => void;- onCloseTerminal: (terminalId: string) => void;- splitShortcutLabel?: string | undefined;- splitVerticalShortcutLabel?: string | undefined;- newShortcutLabel?: string | undefined;- closeShortcutLabel?: string | undefined;-}--const PersistentThreadTerminalPanel = memo(function PersistentThreadTerminalPanel({- threadRef,- surface,- launchContext,- focusRequestId,- keybindings,- onAddTerminalContext,- onSplitTerminal,- onSplitTerminalVertical,- onNewTerminal,- onActiveTerminalChange,- onCloseTerminal,- splitShortcutLabel,- splitVerticalShortcutLabel,- newShortcutLabel,- closeShortcutLabel,-}: PersistentThreadTerminalPanelProps) {- const draftThread = useComposerDraftStore((store) => store.getDraftThreadByRef(threadRef));- const serverThread = useThread(threadRef, { waitForShell: draftThread !== null });- const projectRef = serverThread- ? scopeProjectRef(serverThread.environmentId, serverThread.projectId)- : draftThread- ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)- : null;- const project = useProject(projectRef);- const knownTerminalSessions = useKnownTerminalSessions({- environmentId: threadRef.environmentId,- threadId: threadRef.threadId,- });- const threadWorktreePath = serverThread?.worktreePath ?? draftThread?.worktreePath ?? null;- const activeSummary =- knownTerminalSessions.find((session) => session.target.terminalId === surface.activeTerminalId)- ?.state.summary ?? null;- const worktreePath =- launchContext?.worktreePath ?? activeSummary?.worktreePath ?? threadWorktreePath;- const cwd = useMemo(- () =>- launchContext?.cwd ??- activeSummary?.cwd ??- (project- ? projectScriptCwd({- project: { cwd: project.workspaceRoot },- worktreePath,- })- : null),- [activeSummary?.cwd, launchContext?.cwd, project, worktreePath],- );- const runtimeEnv = useMemo(- () =>- project- ? projectScriptRuntimeEnv({- project: { cwd: project.workspaceRoot },- worktreePath,- })- : {},- [project, worktreePath],- );- const terminalLabelsById = useMemo(() => {- const labels = new Map<string, string>();- for (const terminalId of surface.terminalIds) {- const summary =- knownTerminalSessions.find((session) => session.target.terminalId === terminalId)?.state- .summary ?? null;- labels.set(terminalId, resolveTerminalSessionLabel(terminalId, summary));- }- return labels;- }, [knownTerminalSessions, surface.terminalIds]);- const terminalLaunchLocationsById = useMemo(() => {- const locations = new Map<- string,- {- readonly cwd: string;- readonly worktreePath: string | null;- readonly runtimeEnv: Record<string, string>;- }- >();- for (const terminalId of surface.terminalIds) {- const summary =- knownTerminalSessions.find((session) => session.target.terminalId === terminalId)?.state- .summary ?? null;- const terminalWorktreePath =- launchContext?.worktreePath ?? summary?.worktreePath ?? threadWorktreePath;- const terminalCwd =- launchContext?.cwd ??- summary?.cwd ??- (project- ? projectScriptCwd({- project: { cwd: project.workspaceRoot },- worktreePath: terminalWorktreePath,- })- : null);- if (!terminalCwd || !project) continue;- locations.set(terminalId, {- cwd: terminalCwd,- worktreePath: terminalWorktreePath,- runtimeEnv: projectScriptRuntimeEnv({- project: { cwd: project.workspaceRoot },- worktreePath: terminalWorktreePath,- }),- });- }- return locations;- }, [- knownTerminalSessions,- launchContext?.cwd,- launchContext?.worktreePath,- project,- surface.terminalIds,- threadWorktreePath,- ]);-- if (!project || !cwd) return null;-- return (- <ThreadTerminalDrawer- mode="panel"- threadRef={threadRef}- threadId={threadRef.threadId}- cwd={cwd}- worktreePath={worktreePath}- runtimeEnv={runtimeEnv}- height={0}- terminalIds={surface.terminalIds}- activeTerminalId={surface.activeTerminalId}- terminalGroups={[- {- id: surface.id,- terminalIds: surface.terminalIds,- ...(surface.splitDirection === "vertical" ? { splitDirection: "vertical" as const } : {}),- },- ]}- activeTerminalGroupId={surface.id}- focusRequestId={focusRequestId}- onSplitTerminal={onSplitTerminal}- onSplitTerminalVertical={onSplitTerminalVertical}- onNewTerminal={onNewTerminal}- splitShortcutLabel={splitShortcutLabel}- splitVerticalShortcutLabel={splitVerticalShortcutLabel}- newShortcutLabel={newShortcutLabel}- closeShortcutLabel={closeShortcutLabel}- onActiveTerminalChange={onActiveTerminalChange}- onCloseTerminal={onCloseTerminal}- onHeightChange={() => undefined}- onAddTerminalContext={onAddTerminalContext}- terminalLabelsById={terminalLabelsById}- terminalLaunchLocationsById={terminalLaunchLocationsById}- keybindings={keybindings}- />- );-});--// Errors surface through two maps (draft-keyed and thread-keyed) whose entries-// can race around promotion, so each write carries its time to let the latest-// one win when they collide.-type LocalThreadErrorEntry = {- readonly message: string | null;- readonly at: number;-};--function chatActionErrorMessage(error: unknown): string {- return error instanceof Error ? error.message : "An error occurred.";-}--/**- * Drops the send-time anchored end space. That space is what holds a sent- * message near the top while its turn streams, and it keeps LegendList's- * maintainScrollAtEnd switched off for as long as it is installed — ChatView- * drives the streaming scrolls itself, but only in "anchoring-new-turn" mode.- * So every return to the live edge has to release the anchor too, otherwise the- * timeline settles into "following-end" with nothing following anything.- */-function releaseChatTimelineAnchor<T extends { readonly messageId: MessageId | null }>(- current: T,-): T {- return current.messageId === null ? current : { ...current, messageId: null };-}--function ChatViewContent(props: ChatViewProps) {- const {- environmentId,- threadId,- routeKind,- onDiffPanelOpen,- reserveTitleBarControlInset = true,- forceExpandedMobileComposer = false,- } = props;- const draftId = routeKind === "draft" ? props.draftId : null;- const threadSyncPhase = routeKind === "server" ? (props.threadSyncPhase ?? null) : null;- const threadDetailLoading = threadSyncPhase === "loading";- const handleNewThread = useNewThreadHandler();- const { settleThread } = useThreadActions();- const routeThreadRef = useMemo(- () => scopeThreadRef(environmentId, threadId),- [environmentId, threadId],- );- const routeThreadKey = useMemo(() => scopedThreadKey(routeThreadRef), [routeThreadRef]);- const updateProject = useAtomCommand(projectEnvironment.update, { reportFailure: false });- const upsertKeybinding = useAtomCommand(serverEnvironment.upsertKeybinding, {- reportFailure: false,- });- const openTerminal = useAtomCommand(terminalEnvironment.open, "terminal open");- const writeTerminal = useAtomCommand(terminalEnvironment.write, "terminal write");- const closeTerminalMutation = useAtomCommand(terminalEnvironment.close, "terminal close");- const createThread = useAtomCommand(threadEnvironment.create, { reportFailure: false });- const deleteThread = useAtomCommand(threadEnvironment.delete, { reportFailure: false });- const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {- reportFailure: false,- });- const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false });- const setThreadRuntimeMode = useAtomCommand(threadEnvironment.setRuntimeMode, {- reportFailure: false,- });- const setThreadInteractionMode = useAtomCommand(threadEnvironment.setInteractionMode, {- reportFailure: false,- });- const startThreadTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });- const uploadThreadFeedback = useAtomCommand(threadEnvironment.uploadFeedback, {- reportFailure: false,- });- const interruptThreadTurn = useAtomCommand(threadEnvironment.interruptTurn, {- reportFailure: false,- });- const respondToThreadApproval = useAtomCommand(threadEnvironment.respondToApproval, {- reportFailure: false,- });- const respondToThreadUserInput = useAtomCommand(threadEnvironment.respondToUserInput, {- reportFailure: false,- });- const revertThreadCheckpoint = useAtomCommand(threadEnvironment.revertCheckpoint, {- reportFailure: false,- });- const openPreview = useAtomCommand(previewEnvironment.open, { reportFailure: false });- const closePreview = useAtomCommand(previewEnvironment.close, "preview close");- const { environments } = useEnvironments();- const primaryEnvironment = usePrimaryEnvironment();- const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });- const environmentById = useMemo(- () => new Map(environments.map((environment) => [environment.environmentId, environment])),- [environments],- );- const composerDraftTarget: ScopedThreadRef | DraftId =- routeKind === "server" ? routeThreadRef : props.draftId;- const draftThread = useComposerDraftStore((store) =>- routeKind === "server"- ? store.getDraftSessionByRef(routeThreadRef)- : draftId- ? store.getDraftSession(draftId)- : null,- );- const routeServerThreadShell = useThreadShell(routeKind === "server" ? routeThreadRef : null);- const serverThread = useThread(routeThreadRef, { waitForShell: draftThread !== null });- const loadingServerThread = useMemo(- () =>- threadDetailLoading && routeServerThreadShell- ? buildLoadingThreadFromShell(routeServerThreadShell)- : null,- [routeServerThreadShell, threadDetailLoading],- );- const activeServerThread = serverThread ?? loadingServerThread;- // Pagination window state for the routed server thread: drives the- // "load earlier turns" header when the loaded window has older history.- const routeThreadState = useEnvironmentThread(- routeKind === "server" ? routeThreadRef.environmentId : null,- routeKind === "server" ? routeThreadRef.threadId : null,- );- const loadEarlierTurns = useMemo(() => {- if (routeKind !== "server" || !threadHasOlderTurns(routeThreadState)) {- return null;- }- return {- loading: routeThreadState.page._tag === "Some" && routeThreadState.page.value.loadingOlder,- onLoadEarlier: () => {- requestOlderThreadTurns(routeThreadRef.environmentId, routeThreadRef.threadId);- },- };- }, [routeKind, routeThreadRef, routeThreadState]);- const markThreadVisited = useUiStateStore((store) => store.markThreadVisited);- const settings = useEnvironmentSettings(environmentId);- // New-thread defaults live in the primary environment's settings.json (the- // settings UI never writes to remote environments), so read them from the- // primary server rather than the thread's environment.- const primaryServerSettings = useAtomValue(primaryServerSettingsAtom);- const setStickyComposerModelSelection = useComposerDraftStore(- (store) => store.setStickyModelSelection,- );- const timestampFormat = settings.timestampFormat;- const navigate = useNavigate();- const { resolvedTheme } = useTheme();- // Granular store selectors — avoid subscribing to prompt changes.- const composerRuntimeMode = useComposerDraftStore(- (store) => store.getComposerDraft(composerDraftTarget)?.runtimeMode ?? null,- );- const composerInteractionMode = useComposerDraftStore(- (store) => store.getComposerDraft(composerDraftTarget)?.interactionMode ?? null,- );- const composerActiveProvider = useComposerDraftStore(- (store) => store.getComposerDraft(composerDraftTarget)?.activeProvider ?? null,- );- const composerHasUnsentContent = useComposerDraftStore((store) =>- composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)),- );- const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);- const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);- const setComposerDraftTerminalContexts = useComposerDraftStore(- (store) => store.setTerminalContexts,- );- const setComposerDraftElementContexts = useComposerDraftStore(- (store) => store.setElementContexts,- );- const setComposerDraftPreviewAnnotations = useComposerDraftStore(- (store) => store.setPreviewAnnotations,- );- const setComposerDraftReviewComments = useComposerDraftStore((store) => store.setReviewComments);- const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection);- const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode);- const setComposerDraftInteractionMode = useComposerDraftStore(- (store) => store.setInteractionMode,- );- const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);- const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);- const getDraftSessionByLogicalProjectKey = useComposerDraftStore(- (store) => store.getDraftSessionByLogicalProjectKey,- );- const getDraftSession = useComposerDraftStore((store) => store.getDraftSession);- const setLogicalProjectDraftThreadId = useComposerDraftStore(- (store) => store.setLogicalProjectDraftThreadId,- );- const promptRef = useRef("");- const composerImagesRef = useRef<ComposerImageAttachment[]>([]);- const composerTerminalContextsRef = useRef<TerminalContextDraft[]>([]);- const composerElementContextsRef = useRef<ElementContextDraft[]>([]);- const localComposerRef = useRef<ChatComposerHandle | null>(null);- const composerRef = useComposerHandleContext() ?? localComposerRef;- const [isWorkspaceFileDragActive, setIsWorkspaceFileDragActive] = useState(false);- const [showScrollToBottom, setShowScrollToBottom] = useState(false);- const [expandedImage, setExpandedImage] = useState<ExpandedImagePreview | null>(null);- const [optimisticUserMessages, setOptimisticUserMessages] = useState<ChatMessage[]>([]);- const [feedbackSubmissionsByThreadKey, setFeedbackSubmissionsByThreadKey] = useState<- Record<string, ReadonlyArray<CodexFeedbackSubmission>>- >({});- const feedbackSubmissions = useMemo(- () => feedbackSubmissionsByThreadKey[routeThreadKey] ?? [],- [feedbackSubmissionsByThreadKey, routeThreadKey],- );- const feedbackUploading = feedbackSubmissions.some(- (submission) => submission.status === "uploading",- );- const optimisticUserMessagesRef = useRef(optimisticUserMessages);- optimisticUserMessagesRef.current = optimisticUserMessages;- const [localDraftErrorsByDraftId, setLocalDraftErrorsByDraftId] = useState<- Record<string, LocalThreadErrorEntry>- >({});- const [localServerErrorsByThreadKey, setLocalServerErrorsByThreadKey] = useState<- Record<string, LocalThreadErrorEntry>- >({});- const [isConnecting, _setIsConnecting] = useState(false);- const [isRevertingCheckpoint, setIsRevertingCheckpoint] = useState(false);- const [maximizedRightPanelThreadKey, setMaximizedRightPanelThreadKey] = useState<string | null>(- null,- );- const [respondingRequestIds, setRespondingRequestIds] = useState<ApprovalRequestId[]>([]);- const [respondingUserInputRequestIds, setRespondingUserInputRequestIds] = useState<- ApprovalRequestId[]- >([]);-- useEffect(() => {- setIsWorkspaceFileDragActive(false);- }, [draftId, routeThreadKey]);-- useEffect(() => {- if (!isWorkspaceFileDragActive) return;- const clearWorkspaceFileDrag = () => setIsWorkspaceFileDragActive(false);- window.addEventListener("dragend", clearWorkspaceFileDrag);- return () => window.removeEventListener("dragend", clearWorkspaceFileDrag);- }, [isWorkspaceFileDragActive]);- const [pendingUserInputAnswersByRequestId, setPendingUserInputAnswersByRequestId] = useState<- Record<string, Record<string, PendingUserInputDraftAnswer>>- >({});- const [pendingUserInputQuestionIndexByRequestId, setPendingUserInputQuestionIndexByRequestId] =- useState<Record<string, number>>({});- const shouldUseRightPanelSheet = useMediaQuery(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY);- const [terminalFocusRequestId, setTerminalFocusRequestId] = useState(0);- const [pullRequestDialogState, setPullRequestDialogState] =- useState<PullRequestDialogState | null>(null);- const [terminalUiLaunchContext, setTerminalUiLaunchContext] =- useState<TerminalLaunchContext | null>(null);- const [attachmentPreviewHandoffByMessageId, setAttachmentPreviewHandoffByMessageId] = useState<- Record<string, string[]>- >({});- const [pendingServerThreadEnvMode, setPendingServerThreadEnvMode] =- useState<DraftThreadEnvMode | null>(null);- const [pendingServerThreadBranch, setPendingServerThreadBranch] = useState<string | null>();- const [- pendingServerThreadStartFromOriginByThreadId,- setPendingServerThreadStartFromOriginByThreadId,- ] = useState<Record<string, boolean>>({});- const [lastInvokedScriptByProjectId, setLastInvokedScriptByProjectId] = useLocalStorage(- LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,- {},- LastInvokedScriptByProjectSchema,- );- const legendListRef = useRef<LegendListRef | null>(null);- const [composerOverlayElement, setComposerOverlayElement] = useState<HTMLDivElement | null>(null);- const [composerOverlayHeight, setComposerOverlayHeight] = useState(0);- const isAtEndRef = useRef(true);- const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});- const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});- const sendInFlightRef = useRef(false);- const feedbackUploadsInFlightRef = useRef(new Set<string>());- const terminalUiOpenByThreadRef = useRef<Record<string, boolean>>({});-- useLayoutEffect(() => {- if (!composerOverlayElement) return;-- const updateHeight = () => {- const nextHeight = Math.ceil(composerOverlayElement.getBoundingClientRect().height);- if (nextHeight <= 0) return;- setComposerOverlayHeight((currentHeight) =>- currentHeight === nextHeight ? currentHeight : nextHeight,- );- };-- updateHeight();- if (typeof ResizeObserver === "undefined") return;-- const observer = new ResizeObserver(updateHeight);- observer.observe(composerOverlayElement);- return () => observer.disconnect();- }, [composerOverlayElement]);-- const terminalUiState = useTerminalUiStateStore((state) =>- selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef),- );- const openTerminalThreadKeys = useTerminalUiStateStore(- useShallow((state) =>- Object.entries(state.terminalUiStateByThreadKey).flatMap(- ([nextThreadKey, nextTerminalUiState]) =>- nextTerminalUiState.terminalOpen ? [nextThreadKey] : [],- ),- ),- );- const storeSetTerminalOpen = useTerminalUiStateStore((s) => s.setTerminalOpen);- const storeEnsureTerminal = useTerminalUiStateStore((state) => state.ensureTerminal);- const storeSplitTerminal = useTerminalUiStateStore((s) => s.splitTerminal);- const storeSplitTerminalVertical = useTerminalUiStateStore((s) => s.splitTerminalVertical);- const storeNewTerminal = useTerminalUiStateStore((s) => s.newTerminal);- const storeSetActiveTerminal = useTerminalUiStateStore((s) => s.setActiveTerminal);- const storeCloseTerminal = useTerminalUiStateStore((s) => s.closeTerminal);- const serverThreadRefs = useThreadRefs();- const serverThreadKeys = useMemo(() => serverThreadRefs.map(scopedThreadKey), [serverThreadRefs]);- const draftThreadsByThreadKey = useComposerDraftStore((store) => store.draftThreadsByThreadKey);- const draftThreadKeys = useMemo(- () =>- Object.values(draftThreadsByThreadKey).map((draftThread) =>- scopedThreadKey(scopeThreadRef(draftThread.environmentId, draftThread.threadId)),- ),- [draftThreadsByThreadKey],- );- const [mountedTerminalThreadKeys, setMountedTerminalThreadKeys] = useState<string[]>([]);- const mountedTerminalThreadRefs = useMemo(- () =>- mountedTerminalThreadKeys.flatMap((mountedThreadKey) => {- const mountedThreadRef = parseScopedThreadKey(mountedThreadKey);- return mountedThreadRef ? [{ key: mountedThreadKey, threadRef: mountedThreadRef }] : [];- }),- [mountedTerminalThreadKeys],- );-- const fallbackDraftProjectRef = draftThread- ? scopeProjectRef(draftThread.environmentId, draftThread.projectId)- : null;- const fallbackDraftProject = useProject(fallbackDraftProjectRef);- const localDraftError = activeServerThread- ? null- : ((draftId ? localDraftErrorsByDraftId[draftId]?.message : null) ?? null);- const localServerError = localServerErrorsByThreadKey[routeThreadKey]?.message ?? null;- // Draft errors are keyed by draftId while server errors are keyed by thread- // key, so a pending draft entry must migrate when the server thread loads or- // a failed send would silently disappear on promotion. When both keys hold- // an entry, the most recent write wins.- useEffect(() => {- if (!activeServerThread || !draftId) {- return;- }- const pendingDraftEntry = localDraftErrorsByDraftId[draftId];- if (pendingDraftEntry === undefined) {- return;- }- setLocalDraftErrorsByDraftId((existing) => {- if (existing[draftId] === undefined) {- return existing;- }- const next = { ...existing };- delete next[draftId];- return next;- });- setLocalServerErrorsByThreadKey((existing) => {- const currentEntry = existing[routeThreadKey];- if (- currentEntry !== undefined &&- (currentEntry.at > pendingDraftEntry.at ||- currentEntry.message === pendingDraftEntry.message)- ) {- return existing;- }- return {- ...existing,- [routeThreadKey]: pendingDraftEntry,- };- });- }, [activeServerThread, draftId, localDraftErrorsByDraftId, routeThreadKey]);- const localDraftThread = useMemo(- () =>- draftThread- ? buildLocalDraftThread(- threadId,- draftThread,- fallbackDraftProject?.defaultModelSelection ?? NO_PROVIDER_MODEL_SELECTION,- )- : undefined,- [draftThread, fallbackDraftProject?.defaultModelSelection, threadId],- );- // Promotion is data-driven: the draft route keeps rendering while the- // server thread (same pre-allocated ref) starts, so live state must not- // depend on which route is mounted.- const isServerThread = activeServerThread !== null;- const activeThread = activeServerThread ?? localDraftThread;- const threadError = isServerThread- ? (localServerError ?? activeServerThread?.session?.lastError ?? null)- : localDraftError;- // Dismissals can only mask the shown error, never clear it: a server thread- // keeps its error in session.lastError, so clearing the local shadow would- // just fall through to the persisted one. Mask the current error until a- // different error arrives, mirroring the provider status banner.- const threadErrorBannerKey = getThreadErrorBannerKey(routeThreadKey, threadError);- const visibleThreadError = shouldShowThreadErrorBanner(- routeThreadKey,- threadError,- isThreadErrorBannerDismissedForSession(threadErrorBannerKey),- )- ? threadError- : null;- // Dismissing only mutates the session-scoped mask set, which does not- // trigger a render on its own; setThreadError(null) can also bail when the- // local shadow is already empty and the banner is driven purely by- // session.lastError. Bump a tick so the banner hides immediately. Mirrors- // the branch mismatch banner.- const [, setThreadErrorBannerDismissTick] = useState(0);- const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE;- // Plan mode is legacy (Settings → Beta). With the flag off the effective- // mode is forced to "default" — even for threads with a stored plan mode —- // so nobody is trapped in plan mode while its toggle is hidden. The next- // send persists "default" back to the thread.- const interactionMode = settings.planModeEnabled- ? (composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE)- : DEFAULT_INTERACTION_MODE;- const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;- const canCheckoutPullRequestIntoThread = isLocalDraftThread;- const activeThreadId = activeThread?.id ?? null;- const activeThreadEnvironmentId = activeThread?.environmentId ?? null;- const runningTerminalIds = useThreadRunningTerminalIds({- environmentId: activeThread?.environmentId ?? null,- threadId: activeThreadId,- });- const activeThreadKnownSessionsRaw = useKnownTerminalSessions({- environmentId: activeThread?.environmentId ?? null,- threadId: activeThreadId,- });- const activeThreadKnownSessions = useMemo(() => {- if (activeThreadId === null) {- return [];- }- return activeThreadKnownSessionsRaw.filter(- (session) => session.target.threadId === activeThreadId,- );- }, [activeThreadId, activeThreadKnownSessionsRaw]);- const activeServerOrderedTerminalIds = useMemo(- () => activeThreadKnownSessions.map((session) => session.target.terminalId),- [activeThreadKnownSessions],- );- const activeKnownTerminalIds = useMemo(- () => [...new Set([...activeServerOrderedTerminalIds, ...terminalUiState.terminalIds])],- [activeServerOrderedTerminalIds, terminalUiState.terminalIds],- );- const activeTerminalLabelsById = useMemo(() => {- const labels = new Map<string, string>();- for (const session of activeThreadKnownSessions) {- labels.set(- session.target.terminalId,- resolveTerminalSessionLabel(session.target.terminalId, session.state.summary),- );- }- return labels;- }, [activeThreadKnownSessions]);- const activeThreadRef = useMemo(- () =>- activeThreadEnvironmentId && activeThreadId- ? scopeThreadRef(activeThreadEnvironmentId, activeThreadId)- : null,- [activeThreadEnvironmentId, activeThreadId],- );- const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;- const changeRequestSnapshotByKey = useAtomValue(threadChangeRequestSnapshotsAtom);- const [timelineAnchor, setTimelineAnchor] = useState<{- readonly threadKey: string | null;- readonly messageId: MessageId | null;- }>({ threadKey: activeThreadKey, messageId: null });- if (timelineAnchor.threadKey !== activeThreadKey) {- setTimelineAnchor({ threadKey: activeThreadKey, messageId: null });- }- const timelineAnchorMessageId = timelineAnchor.messageId;- const activeRightPanelKind = useRightPanelStore((state) =>- selectActiveRightPanel(state.byThreadKey, activeThreadRef),- );- const diffOpen = activeRightPanelKind === "diff";- const rightPanelState = useRightPanelStore((state) =>- selectThreadRightPanelState(state.byThreadKey, activeThreadRef),- );- const activeRightPanelSurface = useRightPanelStore((state) =>- selectActiveRightPanelSurface(state.byThreadKey, activeThreadRef),- );- const [pullRequestTabStatuses, setPullRequestTabStatuses] = useState<- Record<string, PullRequestTabStatus>- >({});- // Keyed by the surface the panel is showing rather than by a key rebuilt from the status, so- // the tab is found again whether or not that surface was opened with an environment on it.- const activePullRequestSurfaceId =- activeRightPanelSurface?.kind === "pull-request" ? activeRightPanelSurface.id : undefined;- const handlePullRequestTabStatusChange = useCallback(- (status: PullRequestTabStatus) => {- const id = activePullRequestSurfaceId;- if (id === undefined) return;- setPullRequestTabStatuses((current) => updatePullRequestTabStatus(current, id, status));- },- [activePullRequestSurfaceId],- );- const activeFileSurface =- activeRightPanelSurface?.kind === "file" ? activeRightPanelSurface : null;- const activePreviewState = useThreadPreviewState(activeThreadRef);- const activePreviewServerEpoch = activePreviewState.serverEpoch;- const resolvePreviewRuntimeTabId = useMemo(- () =>- activeThreadRef- ? (tabId: string) => previewRuntimeTabId(activeThreadRef, activePreviewServerEpoch, tabId)- : undefined,- [activeThreadRef, activePreviewServerEpoch],- );- const activePreviewMiniPlayer = usePreviewMiniPlayerStore((state) =>- selectThreadPreviewMiniPlayer(state.byThreadKey, activeThreadRef),- );- const panelTerminalIds = useMemo(- () =>- new Set(- rightPanelState.surfaces.flatMap((surface) =>- surface.kind === "terminal" ? surface.terminalIds : [],- ),- ),- [rightPanelState.surfaces],- );- const allocatableActiveTerminalIds = useMemo(- () => [...new Set([...activeKnownTerminalIds, ...panelTerminalIds])],- [activeKnownTerminalIds, panelTerminalIds],- );- const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime();- const rightPanelOpen = rightPanelState.isOpen;- const canMaximizeRightPanel = rightPanelOpen && !shouldUseRightPanelSheet;- const rightPanelMaximized =- canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey;- const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUseRightPanelSheet;-- useEffect(() => {- if (!activeThreadRef) return;- useRightPanelStore- .getState()- .reconcileBrowserSurfaces(activeThreadRef, Object.keys(activePreviewState.sessions));- }, [activePreviewState.sessions, activeThreadRef]);-- useEffect(() => {- if (!activeThreadRef || !activePreviewMiniPlayer) return;- const miniTabStillExists = Boolean(activePreviewState.sessions[activePreviewMiniPlayer.tabId]);- const sameTabOpenInPanel =- previewPanelOpen &&- activeRightPanelSurface?.kind === "preview" &&- activeRightPanelSurface.resourceId === activePreviewMiniPlayer.tabId;- if (!miniTabStillExists || sameTabOpenInPanel) {- usePreviewMiniPlayerStore.getState().close(activeThreadRef);- }- }, [- activePreviewMiniPlayer,- activePreviewState.sessions,- activeRightPanelSurface,- activeThreadRef,- previewPanelOpen,- ]);-- const existingOpenTerminalThreadKeys = useMemo(() => {- const existingThreadKeys = new Set<string>([...serverThreadKeys, ...draftThreadKeys]);- return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey));- }, [draftThreadKeys, openTerminalThreadKeys, serverThreadKeys]);- const activeLatestTurn = activeThread?.latestTurn ?? null;- const activeRunningTurnId =- (activeThread?.session?.status === "running" ? activeThread.session.activeTurnId : null) ??- (activeLatestTurn?.state === "running" ? activeLatestTurn.turnId : null);- // Reading a finished thread clears the sidebar's Done badge. The visit is- // stamped at the turn's completion time — not now/updatedAt — so it clears- // exactly the completion the user is looking at: a wake or completion that- // lands later still gets its signal (markThreadVisited never moves the- // timestamp backwards).- useEffect(() => {- const completedAt = serverThread?.latestTurn?.completedAt;- if (!serverThread?.id || !completedAt) return;- markThreadVisited(- scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)),- completedAt,- );- }, [- markThreadVisited,- serverThread?.environmentId,- serverThread?.id,- serverThread?.latestTurn?.completedAt,- ]);- useEffect(() => {- setMountedTerminalThreadKeys((currentThreadIds) => {- const nextThreadIds = reconcileMountedTerminalThreadIds({- currentThreadIds,- openThreadIds: existingOpenTerminalThreadKeys,- activeThreadId: activeThreadKey,- activeThreadTerminalOpen: Boolean(activeThreadKey && terminalUiState.terminalOpen),- maxHiddenThreadCount: MAX_HIDDEN_MOUNTED_TERMINAL_THREADS,- });- return currentThreadIds.length === nextThreadIds.length &&- currentThreadIds.every((nextThreadId, index) => nextThreadId === nextThreadIds[index])- ? currentThreadIds- : nextThreadIds;- });- }, [activeThreadKey, existingOpenTerminalThreadKeys, terminalUiState.terminalOpen]);- const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);- const activeProjectRef = useMemo(- () =>- activeThread ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) : null,- [activeThread?.environmentId, activeThread?.projectId],- );- const activeProject = useProject(activeProjectRef);- const handleNewThreadInActiveProject = useCallback(() => {- startNewThreadForProject(activeProjectRef, handleNewThread);- }, [activeProjectRef, handleNewThread]);- const activeEnvironmentShell = useEnvironmentQuery(- activeThread ? environmentShell.stateAtom(activeThread.environmentId) : null,- );- const activeEnvironmentBootstrapComplete = activeEnvironmentShell.data?.snapshot._tag === "Some";- const activeProjectKey = activeProject- ? `${activeProject.environmentId}:${activeProject.workspaceRoot}`- : null;- const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);- const clientSettingsHydrated = useClientSettingsHydrated();- const [pendingFileSurfaceIdsByProject, setPendingFileSurfaceIdsByProject] = useState<- ReadonlyMap<string, ReadonlySet<string>>- >(() => new Map());- const pendingFileSurfaceIds = activeProjectKey- ? (pendingFileSurfaceIdsByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS)- : EMPTY_PENDING_FILE_SURFACE_IDS;- const handleFilePendingChange = useCallback(- (relativePath: string, pending: boolean) => {- if (!activeProjectKey) return;- setPendingFileSurfaceIdsByProject((currentByProject) => {- const current = currentByProject.get(activeProjectKey) ?? EMPTY_PENDING_FILE_SURFACE_IDS;- const surfaceId = `file:${relativePath}`;- if (current.has(surfaceId) === pending) return currentByProject;- const next = new Set(current);- if (pending) next.add(surfaceId);- else next.delete(surfaceId);- const nextByProject = new Map(currentByProject);- if (next.size === 0) nextByProject.delete(activeProjectKey);- else nextByProject.set(activeProjectKey, next);- return nextByProject;- });- },- [activeProjectKey],- );- const configuredPreviewUrls = useMemo(- () => getConfiguredPreviewUrls(activeProject?.scripts),- [activeProject?.scripts],- );-- useEffect(() => {- if (!activeThreadRef || !activeEnvironmentBootstrapComplete) return;- useRightPanelStore.getState().reconcileFileSurfaces(activeThreadRef, activeProject !== null);- }, [activeEnvironmentBootstrapComplete, activeProject, activeThreadRef]);-- // Compute the list of environments this logical project spans, used to- // drive the environment picker in BranchToolbar.- const allProjects = useProjects();- const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;- useEffect(() => {- if (!activeThreadRef || !activeProjectRef) return;- registerFaviconProjectForThread(activeThreadRef, activeProjectRef);- }, [activeProjectRef, activeThreadRef]);- useEffect(() => {- if (!clientSettingsHydrated || !activeThreadRef || !activeProject) return;- // Reuse the sidebar's grouping so history follows the project rows the user- // sees. Deriving the key from the active project alone would miss the- // identity a duplicate row borrows from its siblings.- const logicalKeyByPhysicalKey = buildPhysicalToLogicalProjectKeyMap({- projects: allProjects,- settings: projectGroupingSettings,- primaryEnvironmentId,- });- useBrowserHistoryStore- .getState()- .registerThreadProject(- activeThreadRef,- logicalKeyByPhysicalKey.get(derivePhysicalProjectKey(activeProject)) ??- deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings),- );- }, [- activeProject,- activeThreadRef,- allProjects,- clientSettingsHydrated,- primaryEnvironmentId,- projectGroupingSettings,- ]);- const activeEnvironment =- activeThread == null ? null : (environmentById.get(activeThread.environmentId) ?? null);- const activeEnvironmentConnectionPhase = activeEnvironment?.connection.phase ?? "available";- const activeEnvironmentUnavailable =- activeEnvironment !== null && activeEnvironmentConnectionPhase !== "connected";- const activeReconnectingEnvironmentId =- activeEnvironmentConnectionPhase === "connecting" ||- activeEnvironmentConnectionPhase === "reconnecting"- ? (activeEnvironment?.environmentId ?? null)- : null;- const [reconnectWarningGraceElapsedEnvironmentId, setReconnectWarningGraceElapsedEnvironmentId] =- useState<EnvironmentId | null>(null);- const reconnectWarningGraceElapsed = hasEnvironmentReconnectWarningGraceElapsed(- activeReconnectingEnvironmentId,- reconnectWarningGraceElapsedEnvironmentId,- );- useEffect(() => {- setReconnectWarningGraceElapsedEnvironmentId(null);- if (activeReconnectingEnvironmentId === null) return;- return scheduleEnvironmentReconnectWarning(() =>- setReconnectWarningGraceElapsedEnvironmentId(activeReconnectingEnvironmentId),- );- }, [activeReconnectingEnvironmentId]);- const activeEnvironmentUnavailableLabel = activeEnvironment?.label ?? null;- const activeEnvironmentUnavailableState = useMemo<EnvironmentUnavailableState | null>(() => {- if (!activeEnvironmentUnavailable || !activeEnvironmentUnavailableLabel || !activeEnvironment) {- return null;- }-- return {- environmentId: activeEnvironment.environmentId,- label: activeEnvironmentUnavailableLabel,- connection: activeEnvironment.connection,- };- }, [activeEnvironment, activeEnvironmentUnavailable, activeEnvironmentUnavailableLabel]);- const handleReconnectActiveEnvironment = useCallback(- async (environmentId: EnvironmentId) => {- const result = await retryEnvironment(environmentId);- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Could not reconnect environment",- description: error instanceof Error ? error.message : "Failed to reconnect.",- }),- );- }- },- [retryEnvironment],- );- const logicalProjectEnvironments = useMemo(() => {- if (!activeProject) return [];- const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);- const memberProjects = allProjects.filter(- (p) => deriveLogicalProjectKeyFromSettings(p, projectGroupingSettings) === logicalKey,- );- const seen = new Set<string>();- const envs: Array<{- environmentId: EnvironmentId;- projectId: ProjectId;- label: string;- isPrimary: boolean;- }> = [];- for (const p of memberProjects) {- if (seen.has(p.environmentId)) continue;- seen.add(p.environmentId);- const isPrimary = p.environmentId === primaryEnvironmentId;- const label = environmentById.get(p.environmentId)?.label ?? p.environmentId;- envs.push({- environmentId: p.environmentId,- projectId: p.id,- label,- isPrimary,- });- }- // Sort: primary first, then alphabetical- envs.sort((a, b) => {- if (a.isPrimary !== b.isPrimary) return a.isPrimary ? -1 : 1;- return a.label.localeCompare(b.label);- });- return envs;- }, [activeProject, allProjects, projectGroupingSettings, primaryEnvironmentId, environmentById]);- const hasMultipleEnvironments = logicalProjectEnvironments.length > 1;- const activeEnvironmentOption =- logicalProjectEnvironments.find(- (environment) => environment.environmentId === activeThread?.environmentId,- ) ?? null;- const showComposerEnvironmentIndicator = shouldShowEnvironmentIndicator({- activeEnvironment: activeEnvironmentOption,- canPickEnvironment: hasMultipleEnvironments,- });-- const openPullRequestDialog = useCallback(- (reference?: string) => {- if (!canCheckoutPullRequestIntoThread) {- return;- }- setPullRequestDialogState({- initialReference: reference ?? null,- key: Date.now(),- });- },- [canCheckoutPullRequestIntoThread],- );-- const closePullRequestDialog = useCallback(() => {- setPullRequestDialogState(null);- }, []);-- const openOrReuseProjectDraftThread = useCallback(- async (input: { branch: string; worktreePath: string | null; envMode: DraftThreadEnvMode }) => {- if (!activeProject) {- throw new Error("No active project is available for this pull request.");- }- const activeProjectRef = scopeProjectRef(activeProject.environmentId, activeProject.id);- const logicalProjectKey = deriveLogicalProjectKeyFromSettings(- activeProject,- projectGroupingSettings,- );- const storedDraftSession = getDraftSessionByLogicalProjectKey(logicalProjectKey);- if (storedDraftSession) {- setDraftThreadContext(storedDraftSession.draftId, input);- setLogicalProjectDraftThreadId(- logicalProjectKey,- activeProjectRef,- storedDraftSession.draftId,- {- threadId: storedDraftSession.threadId,- ...input,- },- );- if (routeKind !== "draft" || draftId !== storedDraftSession.draftId) {- await navigate({- to: "/draft/$draftId",- params: buildDraftThreadRouteParams(storedDraftSession.draftId),- });- }- return storedDraftSession.threadId;- }-- const activeDraftSession = routeKind === "draft" && draftId ? getDraftSession(draftId) : null;- if (- !isServerThread &&- activeDraftSession?.logicalProjectKey === logicalProjectKey &&- draftId- ) {- setDraftThreadContext(draftId, input);- setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, draftId, {- threadId: activeDraftSession.threadId,- createdAt: activeDraftSession.createdAt,- runtimeMode: activeDraftSession.runtimeMode,- interactionMode: activeDraftSession.interactionMode,- ...input,- });- return activeDraftSession.threadId;- }-- const nextDraftId = newDraftId();- const nextThreadId = newThreadId();- setLogicalProjectDraftThreadId(logicalProjectKey, activeProjectRef, nextDraftId, {- threadId: nextThreadId,- createdAt: new Date().toISOString(),- runtimeMode: DEFAULT_RUNTIME_MODE,- interactionMode: DEFAULT_INTERACTION_MODE,- ...input,- });- await navigate({- to: "/draft/$draftId",- params: buildDraftThreadRouteParams(nextDraftId),- });- return nextThreadId;- },- [- activeProject,- draftId,- getDraftSession,- getDraftSessionByLogicalProjectKey,- isServerThread,- navigate,- projectGroupingSettings,- routeKind,- setDraftThreadContext,- setLogicalProjectDraftThreadId,- ],- );-- const handlePreparedPullRequestThread = useCallback(- async (input: { branch: string; worktreePath: string | null }) => {- await openOrReuseProjectDraftThread({- branch: input.branch,- worktreePath: input.worktreePath,- envMode: input.worktreePath ? "worktree" : "local",- });- },- [openOrReuseProjectDraftThread],- );-- const selectedProviderByThreadId = composerActiveProvider ?? null;- const threadProvider =- activeThread?.modelSelection.instanceId ??- activeProject?.defaultModelSelection?.instanceId ??- null;- const lockedProvider = deriveLockedProvider({- thread: activeThread,- selectedProvider: selectedProviderByThreadId,- threadProvider,- });- // Once a thread selects an environment, never substitute the primary- // environment's config while the selected environment is still loading.- const serverConfig = activeThread- ? (activeEnvironment?.serverConfig ?? null)- : (primaryEnvironment?.serverConfig ?? null);- const pullRequestsCapabilityKnown = serverConfig !== null;- const supportsPullRequests = serverConfig?.environment.capabilities.pullRequests === true;- const attachmentEnvironmentConfig = environmentById.get(environmentId)?.serverConfig ?? null;- const attachmentUploadsCapabilityKnown = attachmentEnvironmentConfig !== null;- const supportsAttachmentUploads =- attachmentEnvironmentConfig?.environment.capabilities.attachmentUploads === true;- const versionMismatch = resolveServerConfigVersionMismatch(serverConfig);- const versionMismatchDismissKey =- versionMismatch && activeThread- ? buildVersionMismatchDismissalKey(activeThread.environmentId, versionMismatch)- : null;- const [dismissedVersionMismatchKey, setDismissedVersionMismatchKey] = useState<string | null>(- null,- );- const versionMismatchDismissed =- versionMismatchDismissKey === dismissedVersionMismatchKey ||- isVersionMismatchDismissed(versionMismatchDismissKey);- const showVersionMismatchBanner =- versionMismatch !== null && versionMismatchDismissKey !== null && !versionMismatchDismissed;- const hasMultipleRegisteredEnvironments = environments.length > 1;- const versionMismatchServerLabel =- hasMultipleRegisteredEnvironments && activeThread- ? `${environmentById.get(activeThread.environmentId)?.label ?? serverConfig?.environment.label ?? activeThread.environmentId} server`- : "server";- const serverUpdateEnvironmentId = activeThread?.environmentId ?? null;- const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);- const serverUpdateState = useAtomValue(- serverEnvironment.updateStateAtom(serverUpdateEnvironmentId),- );- const systemComposerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {- const items: ComposerBannerStackItem[] = [];- const updateRunning = serverUpdateState.status === "running";- const unavailableConnection = activeEnvironmentUnavailableState?.connection ?? null;- const environmentReconnecting =- unavailableConnection !== null &&- (unavailableConnection.phase === "connecting" ||- unavailableConnection.phase === "reconnecting");- // Reconnecting to a version-skewed server with no update in flight- // usually means the server is restarting mid-update and a refresh wiped- // the in-memory update state. Fold the reconnect and version banners- // into one calm line instead of stacking "Failed to connect" on- // "versions differ". A failed update never folds: its error and retry- // action must stay visible.- const reconnectingThroughVersionSkew =- serverUpdateState.status === "idle" && environmentReconnecting && versionMismatch !== null;- // While an update runs, transient connect blips are expected (the server- // restarts) and the update banner already shows progress. Hard failure- // phases still surface so the Reconnect action stays reachable.- const suppressUnavailableBanner =- environmentReconnecting &&- (updateRunning || (!reconnectingThroughVersionSkew && !reconnectWarningGraceElapsed));- if (activeEnvironmentUnavailableState && unavailableConnection && !suppressUnavailableBanner) {- if (reconnectingThroughVersionSkew) {- items.push({- id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,- variant: "default",- // Live connection status: calm styling, but it must front the stack.- urgent: true,- icon: (- <span- className="size-1.5 animate-status-pulse rounded-full bg-foreground"- aria-hidden="true"- />- ),- title: `${unavailableConnection.phase === "connecting" ? "Connecting" : "Reconnecting"} to ${activeEnvironmentUnavailableState.label}`,- description: "It may be finishing an update. One moment.",- });- } else {- items.push({- id: `environment-unavailable:${activeEnvironmentUnavailableState.environmentId}`,- variant: unavailableConnection.phase === "error" ? "error" : "warning",- icon: <WifiOffIcon />,- title: `${activeEnvironmentUnavailableState.label}: ${connectionStatusTitle(unavailableConnection)}`,- description:- unavailableConnection.error ??- "Reconnect this environment before sending messages or running actions.",- actions: (- <>- <Button- size="xs"- disabled={environmentReconnecting}- onClick={() =>- void handleReconnectActiveEnvironment(- activeEnvironmentUnavailableState.environmentId,- )- }- >- {environmentReconnecting ? "Reconnecting..." : "Reconnect"}- </Button>- <Button- size="xs"- variant="outline"- onClick={() => void navigate({ to: "/settings/connections" })}- >- Connections- </Button>- </>- ),- });- }- }- if (- serverUpdateEnvironmentId &&- !reconnectingThroughVersionSkew &&- (serverUpdateState.status !== "idle" ||- (showVersionMismatchBanner && versionMismatch && versionMismatchDismissKey))- ) {- const updateInProgress = serverUpdateState.status === "running";- const updateFailed = serverUpdateState.status === "failed";- items.push({- id: `server-version:${serverUpdateEnvironmentId}`,- variant: updateFailed ? "error" : "default",- // A running update is live progress the user is waiting on; only the- // idle "update available" offer is calm enough to stack behind.- urgent: updateInProgress,- // In-flight and failed states carry their own status dot inside- // ServerUpdateProgress; only the idle offer needs an icon.- icon:- updateInProgress || updateFailed ? null : (- <span- className="size-1.5 rounded-full border border-muted-foreground/40"- aria-hidden="true"- />- ),- title:- updateInProgress || updateFailed ? (- `${updateFailed ? "Could not update" : "Updating"} ${versionMismatchServerLabel}`- ) : versionMismatch ? (- <Tooltip>- <TooltipTrigger- render={- <button type="button" className="cursor-help rounded-sm text-left">- Server update available- </button>- }- />- <TooltipPopup side="top">- {versionMismatchServerLabel} {versionMismatch.serverVersion}{" "}- <span aria-hidden="true">→</span> {versionMismatch.clientVersion}- </TooltipPopup>- </Tooltip>- ) : (- "Server update available"- ),- description:- updateInProgress || updateFailed ? (- <ServerUpdateProgress state={serverUpdateState} />- ) : versionMismatchSelfUpdate === "desktop-managed" ? (- serverUpdateGuidance(versionMismatchSelfUpdate, versionMismatchServerLabel)- ) : null,- // The desktop-managed guidance is already the description; the action- // slot would only repeat it.- actions:- updateInProgress ||- !versionMismatch ||- versionMismatchSelfUpdate === "desktop-managed" ? undefined : (- <ServerUpdateAction- environmentId={serverUpdateEnvironmentId}- serverLabel={versionMismatchServerLabel}- selfUpdate={versionMismatchSelfUpdate}- targetVersion={versionMismatch.clientVersion}- label={updateFailed ? "Retry" : "Update"}- />- ),- ...(updateInProgress || updateFailed || !versionMismatchDismissKey- ? {}- : {- dismissLabel: "Dismiss update notice",- onDismiss: () => {- dismissVersionMismatch(versionMismatchDismissKey);- setDismissedVersionMismatchKey(versionMismatchDismissKey);- },- }),- });- }- return items;- }, [- activeEnvironmentUnavailableState,- reconnectWarningGraceElapsed,- handleReconnectActiveEnvironment,- navigate,- setDismissedVersionMismatchKey,- showVersionMismatchBanner,- serverUpdateState,- versionMismatch,- versionMismatchDismissKey,- serverUpdateEnvironmentId,- versionMismatchSelfUpdate,- versionMismatchServerLabel,- ]);- const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;- const unlockedSelectedProvider = resolveSelectableProvider(- providerStatuses,- selectedProviderByThreadId ?? threadProvider,- );- const selectedProvider: ProviderDriverKind = lockedProvider ?? unlockedSelectedProvider;- const phase = derivePhase(activeThread?.session ?? null);- const threadActivities = activeThread?.activities ?? EMPTY_ACTIVITIES;- const activeContextWindow = useMemo(- () => deriveLatestContextWindowSnapshot(threadActivities),- [threadActivities],- );- const workLogEntries = useMemo(() => deriveWorkLogEntries(threadActivities), [threadActivities]);- const turnPlans = useMemo(() => deriveTurnPlans(threadActivities), [threadActivities]);- // Native subagent fold: memoized by activity-list identity, shared by the- // Agents surface, live strip, and workflow cards. v2Projection is null- // until orchestration-v2 lands (source precedence lives in the derive).- // sessionLive derives interruption for agents orphaned by session death.- const agentSessionLive = phase !== "disconnected";- const agentPanelModel = useMemo(- () =>- deriveAgentPanelModel({- agents: foldSubagentActivities(threadActivities, { sessionLive: agentSessionLive }),- }),- [agentSessionLive, threadActivities],- );- const pendingApprovals = useMemo(- () => derivePendingApprovals(threadActivities),- [threadActivities],- );- const pendingUserInputs = useMemo(- () => derivePendingUserInputs(threadActivities),- [threadActivities],- );- const activePendingUserInput = pendingUserInputs[0] ?? null;- const activePendingDraftAnswers = useMemo(- () =>- activePendingUserInput- ? (pendingUserInputAnswersByRequestId[activePendingUserInput.requestId] ??- EMPTY_PENDING_USER_INPUT_ANSWERS)- : EMPTY_PENDING_USER_INPUT_ANSWERS,- [activePendingUserInput, pendingUserInputAnswersByRequestId],- );- const activePendingQuestionIndex = activePendingUserInput- ? (pendingUserInputQuestionIndexByRequestId[activePendingUserInput.requestId] ?? 0)- : 0;- const activePendingProgress = useMemo(- () =>- activePendingUserInput- ? derivePendingUserInputProgress(- activePendingUserInput.questions,- activePendingDraftAnswers,- activePendingQuestionIndex,- )- : null,- [activePendingDraftAnswers, activePendingQuestionIndex, activePendingUserInput],- );- const activePendingResolvedAnswers = useMemo(- () =>- activePendingUserInput- ? buildPendingUserInputAnswers(activePendingUserInput.questions, activePendingDraftAnswers)- : null,- [activePendingDraftAnswers, activePendingUserInput],- );- const activePendingIsResponding = activePendingUserInput- ? respondingUserInputRequestIds.includes(activePendingUserInput.requestId)- : false;- const activeProposedPlan = useMemo(() => {- if (!latestTurnSettled) {- return null;- }- return findLatestProposedPlan(- activeThread?.proposedPlans ?? [],- activeLatestTurn?.turnId ?? null,- );- }, [activeLatestTurn?.turnId, activeThread?.proposedPlans, latestTurnSettled]);- const activePlan = useMemo(- () => deriveActivePlanState(threadActivities, activeLatestTurn?.turnId ?? undefined),- [activeLatestTurn?.turnId, threadActivities],- );- // Current step for the in-chat working row: only for the running turn's own- // plan (deriveActivePlanState falls back to older turns' plans, which must- // not label fresh work). Falls back to the first pending step so an- // all-pending freshly written plan labels the row, matching the chip and- // the server's planProgress.- const workingStepLabel = useMemo(() => {- if (!activePlan || activePlan.turnId !== (activeLatestTurn?.turnId ?? null)) {- return null;- }- return (- activePlan.steps.find((step) => step.status === "inProgress")?.step ??- activePlan.steps.find((step) => step.status === "pending")?.step ??- null- );- }, [activeLatestTurn?.turnId, activePlan]);- const showPlanFollowUpPrompt =- pendingUserInputs.length === 0 &&- interactionMode === "plan" &&- latestTurnSettled &&- hasActionableProposedPlan(activeProposedPlan);- const activePendingApproval = pendingApprovals[0] ?? null;- const {- beginLocalDispatch,- resetLocalDispatch,- localDispatchStartedAt,- latestUserMessageAt,- isPreparingWorktree,- isSendBusy,- backgroundSubmissionPending,- } = useLocalDispatchState({- activeThread,- activeLatestTurn,- phase,- activePendingApproval: activePendingApproval?.requestId ?? null,- activePendingUserInput: activePendingUserInput?.requestId ?? null,- threadError,- });- const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint;- const activeWorkStartedAt = deriveActiveWorkStartedAt(- activeLatestTurn,- activeThread?.session ?? null,- localDispatchStartedAt,- latestUserMessageAt,- );- useEffect(() => {- attachmentPreviewHandoffByMessageIdRef.current = attachmentPreviewHandoffByMessageId;- }, [attachmentPreviewHandoffByMessageId]);- const clearAttachmentPreviewHandoff = useCallback(- (messageId: MessageId, previewUrls?: ReadonlyArray<string>) => {- delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];- const currentPreviewUrls =- previewUrls ?? attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];- setAttachmentPreviewHandoffByMessageId((existing) => {- if (!(messageId in existing)) {- return existing;- }- const next = { ...existing };- delete next[messageId];- attachmentPreviewHandoffByMessageIdRef.current = next;- return next;- });- for (const previewUrl of currentPreviewUrls) {- revokeBlobPreviewUrl(previewUrl);- }- },- [],- );- const clearAttachmentPreviewHandoffs = useCallback(() => {- attachmentPreviewPromotionInFlightByMessageIdRef.current = {};- for (const previewUrls of Object.values(attachmentPreviewHandoffByMessageIdRef.current)) {- for (const previewUrl of previewUrls) {- revokeBlobPreviewUrl(previewUrl);- }- }- attachmentPreviewHandoffByMessageIdRef.current = {};- setAttachmentPreviewHandoffByMessageId({});- }, []);- useEffect(() => {- return () => {- clearAttachmentPreviewHandoffs();- for (const message of optimisticUserMessagesRef.current) {- revokeUserMessagePreviewUrls(message);- }- };- }, [clearAttachmentPreviewHandoffs]);- const handoffAttachmentPreviews = useCallback((messageId: MessageId, previewUrls: string[]) => {- if (previewUrls.length === 0) return;-- const previousPreviewUrls = attachmentPreviewHandoffByMessageIdRef.current[messageId] ?? [];- const nextPreviewUrlSet = new Set(previewUrls);- for (const previewUrl of previousPreviewUrls) {- if (!nextPreviewUrlSet.has(previewUrl)) {- revokeBlobPreviewUrl(previewUrl);- }- }- setAttachmentPreviewHandoffByMessageId((existing) => {- const next = {- ...existing,- [messageId]: previewUrls,- };- attachmentPreviewHandoffByMessageIdRef.current = next;- return next;- });- }, []);- const serverMessages = activeThread?.messages;- const serverAttachmentIds = useMemo(() => {- const attachmentIds = new Set<string>();- for (const message of serverMessages ?? []) {- for (const attachment of message.attachments ?? []) {- attachmentIds.add(attachment.id);- }- }- return [...attachmentIds];- }, [serverMessages]);- const serverAttachmentResources = useMemo(- () =>- serverAttachmentIds.map((attachmentId) => ({- _tag: "attachment" as const,- attachmentId,- })),- [serverAttachmentIds],- );- const serverAttachmentUrls = useAssetUrls(environmentId, serverAttachmentResources);- const serverAttachmentUrlById = useMemo(- () =>- new Map(- serverAttachmentIds.flatMap((attachmentId, index) => {- const url = serverAttachmentUrls[index];- return url ? [[attachmentId, url] as const] : [];- }),- ),- [serverAttachmentIds, serverAttachmentUrls],- );- const displayServerMessages = useMemo<ReadonlyArray<ChatMessage>>(() => {- if (!serverMessages) return [];- return serverMessages.map((message) => {- if (!message.attachments || message.attachments.length === 0) {- return message;- }- return {- ...message,- attachments: message.attachments.map((attachment) => {- const previewUrl = serverAttachmentUrlById.get(attachment.id);- return previewUrl ? { ...attachment, previewUrl } : attachment;- }),- };- });- }, [serverAttachmentUrlById, serverMessages]);- useEffect(() => {- if (typeof Image === "undefined" || displayServerMessages.length === 0) {- return;- }-- const cleanups: Array<() => void> = [];- const userMessagesById = new Map<string, ChatMessage>(- displayServerMessages- .filter((message) => message.role === "user")- .map((message) => [String(message.id), message] as const),- );-- for (const [messageId, handoffPreviewUrls] of Object.entries(- attachmentPreviewHandoffByMessageId,- )) {- if (attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId]) {- continue;- }-- const serverMessage = userMessagesById.get(messageId);- if (!serverMessage?.attachments || serverMessage.attachments.length === 0) {- continue;- }-- const serverPreviewUrls = serverMessage.attachments.flatMap((attachment) =>- attachment.type === "image" && attachment.previewUrl ? [attachment.previewUrl] : [],- );- if (- serverPreviewUrls.length === 0 ||- serverPreviewUrls.length !== handoffPreviewUrls.length ||- serverPreviewUrls.some((previewUrl) => previewUrl.startsWith("blob:"))- ) {- continue;- }-- attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId] = true;-- let cancelled = false;- const imageInstances: HTMLImageElement[] = [];-- const preloadServerPreviews = Promise.all(- serverPreviewUrls.map(- (previewUrl) =>- new Promise<void>((resolve, reject) => {- const image = new Image();- imageInstances.push(image);- const handleLoad = () => resolve();- const handleError = () =>- reject(new Error(`Failed to load server preview for ${messageId}.`));- image.addEventListener("load", handleLoad, { once: true });- image.addEventListener("error", handleError, { once: true });- image.src = previewUrl;- }),- ),- );-- void preloadServerPreviews- .then(() => {- if (cancelled) {- return;- }- clearAttachmentPreviewHandoff(messageId as MessageId, handoffPreviewUrls);- })- .catch(() => {- if (!cancelled) {- delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];- }- });-- cleanups.push(() => {- cancelled = true;- delete attachmentPreviewPromotionInFlightByMessageIdRef.current[messageId];- for (const image of imageInstances) {- image.src = "";- }- });- }-- return () => {- for (const cleanup of cleanups) {- cleanup();- }- };- }, [attachmentPreviewHandoffByMessageId, clearAttachmentPreviewHandoff, displayServerMessages]);- const timelineMessages = useMemo(() => {- const messages = displayServerMessages;- const serverMessagesWithPreviewHandoff =- Object.keys(attachmentPreviewHandoffByMessageId).length === 0- ? messages- : // Spread only fires for the few messages that actually changed;- // unchanged ones early-return their original reference.- // In-place mutation would break React's immutable state contract.- messages.map((message) => {- if (- message.role !== "user" ||- !message.attachments ||- message.attachments.length === 0- ) {- return message;- }- const handoffPreviewUrls = attachmentPreviewHandoffByMessageId[message.id];- if (!handoffPreviewUrls || handoffPreviewUrls.length === 0) {- return message;- }-- let changed = false;- let imageIndex = 0;- const attachments = message.attachments.map((attachment) => {- if (attachment.type !== "image") {- return attachment;- }- const handoffPreviewUrl = handoffPreviewUrls[imageIndex];- imageIndex += 1;- if (!handoffPreviewUrl || attachment.previewUrl === handoffPreviewUrl) {- return attachment;- }- changed = true;- return {- ...attachment,- previewUrl: handoffPreviewUrl,- };- });-- return changed ? { ...message, attachments } : message;- });-- const localMessages = [- ...optimisticUserMessages,- ...feedbackSubmissions.flatMap((submission) =>- submission.status === "interrupted"- ? []- : [codexFeedbackMessage(submission), codexFeedbackMessage(submission, "assistant")],- ),- ];- if (localMessages.length === 0) {- return serverMessagesWithPreviewHandoff;- }- const serverIds = new Set(serverMessagesWithPreviewHandoff.map((message) => message.id));- const pendingMessages = localMessages.filter((message) => !serverIds.has(message.id));- if (pendingMessages.length === 0) {- return serverMessagesWithPreviewHandoff;- }- return [...serverMessagesWithPreviewHandoff, ...pendingMessages];- }, [- attachmentPreviewHandoffByMessageId,- displayServerMessages,- feedbackSubmissions,- optimisticUserMessages,- ]);- const timelineEntries = useMemo(- () =>- deriveTimelineEntries(- timelineMessages,- activeThread?.proposedPlans ?? [],- workLogEntries,- turnPlans,- ),- [activeThread?.proposedPlans, timelineMessages, turnPlans, workLogEntries],- );- const [dockedDraftHeroThreadKey, setDockedDraftHeroThreadKey] = useState<string | null>(null);- const draftHeroDockRequested =- activeThreadKey !== null && dockedDraftHeroThreadKey === activeThreadKey;- const isDraftHeroState = resolveDraftHeroState({- isLocalDraftThread,- hasTimelineEntries: timelineEntries.length > 0,- isWorking,- draftHeroDockRequested,- backgroundSubmissionPending,- });- const [- attachDraftHeroTransitionGroupRef,- attachDraftHeroComposerAnchorRef,- captureDraftHeroComposerRect,- ] = useDraftHeroLayoutTransition(isDraftHeroState);- const { turnDiffSummaries, inferredCheckpointTurnCountByTurnId } =- useTurnDiffSummaries(activeThread);- const turnDiffSummaryByAssistantMessageId = useMemo(() => {- const byMessageId = new Map<MessageId, TurnDiffSummary>();- for (const summary of turnDiffSummaries) {- if (!summary.assistantMessageId) continue;- byMessageId.set(summary.assistantMessageId, summary);- }- return byMessageId;- }, [turnDiffSummaries]);- const revertTurnCountByUserMessageId = useMemo(() => {- const byUserMessageId = new Map<MessageId, number>();- for (let index = 0; index < timelineEntries.length; index += 1) {- const entry = timelineEntries[index];- if (!entry || entry.kind !== "message" || entry.message.role !== "user") {- continue;- }-- for (let nextIndex = index + 1; nextIndex < timelineEntries.length; nextIndex += 1) {- const nextEntry = timelineEntries[nextIndex];- if (!nextEntry || nextEntry.kind !== "message") {- continue;- }- if (nextEntry.message.role === "user") {- break;- }- const summary = turnDiffSummaryByAssistantMessageId.get(nextEntry.message.id);- if (!summary) {- continue;- }- const turnCount =- summary.checkpointTurnCount ?? inferredCheckpointTurnCountByTurnId[summary.turnId];- if (typeof turnCount !== "number") {- break;- }- byUserMessageId.set(entry.message.id, Math.max(0, turnCount - 1));- break;- }- }-- return byUserMessageId;- }, [inferredCheckpointTurnCountByTurnId, timelineEntries, turnDiffSummaryByAssistantMessageId]);-- const gitCwd = activeProject- ? projectScriptCwd({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThread?.worktreePath ?? null,- })- : null;- const gitStatusCwd = activeThread?.worktreePath ?? gitCwd;- const gitStatusQuery = useEnvironmentQuery(- gitStatusCwd === null- ? null- : vcsEnvironment.status({- environmentId,- input: { cwd: gitStatusCwd },- }),- );- const keybindings = useAtomValue(primaryServerKeybindingsAtom);- const availableEditors = useAtomValue(primaryServerAvailableEditorsAtom);- // Prefer an instance-id match so a custom Codex instance (e.g.- // `codex_personal`) surfaces its own status/message in the banner rather- // than the default Codex's. Falls back to first-match-by-kind when no- // saved instance id is available or the instance no longer exists.- const selectedProviderInstanceId =- providerStatuses.find((status) => status.instanceId === selectedProviderByThreadId)- ?.instanceId ?? null;- const activeProviderInstanceId =- selectedProviderInstanceId ??- activeThread?.session?.providerInstanceId ??- activeThread?.modelSelection.instanceId ??- activeProject?.defaultModelSelection?.instanceId ??- null;- const compactionProviderAvailable = useMemo(- () =>- hasAvailableClaudeCompactionProvider({- providers: applyProviderInstanceSettings(- deriveProviderInstanceEntries(providerStatuses),- settings,- ),- instanceId: activeProviderInstanceId,- lockedInstanceId: lockedProvider- ? (activeThread?.session?.providerInstanceId ??- activeThread?.modelSelection.instanceId ??- null)- : null,- }),- [- activeProviderInstanceId,- activeThread?.modelSelection.instanceId,- activeThread?.session?.providerInstanceId,- lockedProvider,- providerStatuses,- settings,- ],- );- const activeProviderStatus = useMemo(() => {- if (activeProviderInstanceId) {- return (- providerStatuses.find((status) => status.instanceId === activeProviderInstanceId) ?? null- );- }- const defaultInstanceId = defaultInstanceIdForDriver(selectedProvider);- return providerStatuses.find((status) => status.instanceId === defaultInstanceId) ?? null;- }, [activeProviderInstanceId, providerStatuses, selectedProvider]);- const [resumeCompactionPermanentlyDismissed, setResumeCompactionPermanentlyDismissed] =- useLocalStorage(- `t3code:resume-compaction-dismissed:${environmentId}:${activeProviderInstanceId ?? "claudeAgent"}`,- false,- Schema.Boolean,- );- const nativeResumeCompactionDismissed = useMemo(- () => hasDismissedResumeCompaction(threadActivities),- [threadActivities],- );- useEffect(() => {- if (nativeResumeCompactionDismissed && !resumeCompactionPermanentlyDismissed) {- setResumeCompactionPermanentlyDismissed(true);- }- }, [- nativeResumeCompactionDismissed,- resumeCompactionPermanentlyDismissed,- setResumeCompactionPermanentlyDismissed,- ]);- const providerStatusBannerKey = getProviderStatusBannerKey(activeProviderStatus);- const [dismissedProviderStatusBannerKey, setDismissedProviderStatusBannerKey] = useState<- string | null- >(null);- useEffect(() => {- if (providerStatusBannerKey === null && dismissedProviderStatusBannerKey !== null) {- setDismissedProviderStatusBannerKey(null);- }- }, [dismissedProviderStatusBannerKey, providerStatusBannerKey]);- const visibleProviderStatus = shouldShowProviderStatusBanner(- activeProviderStatus,- dismissedProviderStatusBannerKey,- )- ? activeProviderStatus- : null;- const hasTimelineTopBanner = Boolean(visibleThreadError) || visibleProviderStatus !== null;- const activeProjectCwd = activeProject?.workspaceRoot ?? null;- const activeThreadWorktreePath = activeThread?.worktreePath ?? null;- const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;- const activeTerminalLaunchContext =- terminalUiLaunchContext?.threadId === activeThreadId ? terminalUiLaunchContext : null;- // Default true while loading to avoid toolbar flicker.- const isGitRepo = gitStatusQuery.data?.isRepo ?? true;- const showComposerContextStrip = shouldShowComposerContextStrip({- hasActiveProject: activeProject !== null,- isGitRepo,- showEnvironmentIndicator: showComposerEnvironmentIndicator,- });- const initialDiffPanelGitScope =- gitStatusQuery.data?.hasWorkingTreeChanges === true ? "unstaged" : "branch";- const diffPanelGitStatusResolutionKey = gitStatusQuery.data ? "resolved" : "pending";- const terminalShortcutLabelOptions = useMemo(- () => ({- context: {- terminalFocus: true,- terminalOpen: Boolean(terminalUiState.terminalOpen),- },- }),- [terminalUiState.terminalOpen],- );- const splitTerminalShortcutLabel = useMemo(- () => shortcutLabelForCommand(keybindings, "terminal.split", terminalShortcutLabelOptions),- [keybindings, terminalShortcutLabelOptions],- );- const splitTerminalVerticalShortcutLabel = useMemo(- () =>- shortcutLabelForCommand(keybindings, "terminal.splitVertical", terminalShortcutLabelOptions),- [keybindings, terminalShortcutLabelOptions],- );- const newTerminalShortcutLabel = useMemo(- () => shortcutLabelForCommand(keybindings, "terminal.new", terminalShortcutLabelOptions),- [keybindings, terminalShortcutLabelOptions],- );- const closeTerminalShortcutLabel = useMemo(- () => shortcutLabelForCommand(keybindings, "terminal.close", terminalShortcutLabelOptions),- [keybindings, terminalShortcutLabelOptions],- );- const onToggleDiff = useCallback(() => {- if (!isServerThread) {- return;- }- if (!diffOpen) {- onDiffPanelOpen?.();- }- if (activeThreadRef) {- useRightPanelStore.getState().toggle(activeThreadRef, "diff");- }- }, [activeThreadRef, diffOpen, isServerThread, onDiffPanelOpen]);-- const envLocked = Boolean(- activeThread &&- (activeThread.messages.length > 0 ||- (activeThread.session !== null && activeThread.session.status !== "stopped")),- );-- // Handle environment change for draft threads. When the user picks a- // different environment we update the draft context to point at the physical- // project in that environment while keeping the same logical project.- const onEnvironmentChange = useCallback(- (nextEnvironmentId: EnvironmentId) => {- if (envLocked || !draftId) return;- const target = logicalProjectEnvironments.find(- (env) => env.environmentId === nextEnvironmentId,- );- if (!target) return;- setDraftThreadContext(draftId, {- projectRef: scopeProjectRef(target.environmentId, target.projectId),- });- },- [draftId, envLocked, logicalProjectEnvironments, setDraftThreadContext],- );-- const activeTerminalGroup =- terminalUiState.terminalGroups.find(- (group) => group.id === terminalUiState.activeTerminalGroupId,- ) ??- terminalUiState.terminalGroups.find((group) =>- group.terminalIds.includes(terminalUiState.activeTerminalId),- ) ??- null;- const hasReachedSplitLimit =- (activeTerminalGroup?.terminalIds.length ?? 0) >= MAX_TERMINALS_PER_GROUP;- const setThreadError = useCallback(- (targetThreadId: ThreadId | null, error: string | null) => {- if (!targetThreadId) return;- const nextError = sanitizeThreadErrorMessage(error);- const nextEntry: LocalThreadErrorEntry = { message: nextError, at: Date.now() };- if (- shouldWriteThreadErrorToCurrentServerThread({- activeServerThread,- routeThreadRef,- targetThreadId,- })- ) {- setLocalServerErrorsByThreadKey((existing) => {- if ((existing[routeThreadKey]?.message ?? null) === nextError) {- return existing;- }- return {- ...existing,- [routeThreadKey]: nextEntry,- };- });- return;- }- const localDraftErrorKey = draftId ?? targetThreadId;- setLocalDraftErrorsByDraftId((existing) => {- if ((existing[localDraftErrorKey]?.message ?? null) === nextError) {- return existing;- }- return {- ...existing,- [localDraftErrorKey]: nextEntry,- };- });- },- [activeServerThread, draftId, routeThreadKey, routeThreadRef],- );-- const focusComposer = useCallback(() => {- composerRef.current?.focusAtEnd();- }, [composerRef]);- const scheduleComposerFocus = useCallback(() => {- window.requestAnimationFrame(() => {- focusComposer();- });- }, [focusComposer]);- const addTerminalContextToDraft = useCallback(- (selection: TerminalContextSelection) => {- composerRef.current?.addTerminalContext(selection);- },- [composerRef],- );- const setTerminalOpen = useCallback(- (open: boolean) => {- if (!activeThreadRef) return;- storeSetTerminalOpen(activeThreadRef, open);- },- [activeThreadRef, storeSetTerminalOpen],- );- const toggleTerminalVisibility = useCallback(() => {- if (!activeThreadRef) return;- const nextOpen = !terminalUiState.terminalOpen;- if (nextOpen && terminalUiState.terminalIds.length === 0) {- if (!activeThreadId || !activeProject) {- return;- }- const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;- if (!cwdForOpen) {- return;- }- const terminalId = nextTerminalId(allocatableActiveTerminalIds);- storeEnsureTerminal(activeThreadRef, terminalId, { open: true });- void openTerminal({- environmentId,- input: {- threadId: activeThreadId,- terminalId,- cwd: cwdForOpen,- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),- env: projectScriptRuntimeEnv({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThreadWorktreePath,- }),- },- });- return;- }- setTerminalOpen(nextOpen);- }, [- activeProject,- activeThreadId,- activeThreadRef,- activeThreadWorktreePath,- allocatableActiveTerminalIds,- environmentId,- gitCwd,- openTerminal,- setTerminalOpen,- storeEnsureTerminal,- terminalUiState.terminalIds.length,- terminalUiState.terminalOpen,- ]);- const splitTerminal = useCallback(- (direction: "horizontal" | "vertical" = "horizontal") => {- if (!activeThreadRef || hasReachedSplitLimit || !activeThreadId || !activeProject) {- return;- }- const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;- if (!cwdForOpen) {- return;- }- const terminalId = nextTerminalId(allocatableActiveTerminalIds);- if (direction === "vertical") {- storeSplitTerminalVertical(activeThreadRef, terminalId);- } else {- storeSplitTerminal(activeThreadRef, terminalId);- }- setTerminalFocusRequestId((value) => value + 1);- void openTerminal({- environmentId,- input: {- threadId: activeThreadId,- terminalId,- cwd: cwdForOpen,- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),- env: projectScriptRuntimeEnv({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThreadWorktreePath,- }),- },- });- },- [- activeProject,- activeThreadId,- allocatableActiveTerminalIds,- activeThreadRef,- openTerminal,- activeThreadWorktreePath,- environmentId,- gitCwd,- hasReachedSplitLimit,- storeSplitTerminal,- storeSplitTerminalVertical,- ],- );- const createNewTerminal = useCallback(() => {- if (!activeThreadRef || !activeThreadId || !activeProject) {- return;- }- const cwdForOpen = gitCwd ?? activeProject.workspaceRoot;- if (!cwdForOpen) {- return;- }- const terminalId = nextTerminalId(allocatableActiveTerminalIds);- storeNewTerminal(activeThreadRef, terminalId);- setTerminalFocusRequestId((value) => value + 1);- void openTerminal({- environmentId,- input: {- threadId: activeThreadId,- terminalId,- cwd: cwdForOpen,- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),- env: projectScriptRuntimeEnv({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThreadWorktreePath,- }),- },- });- }, [- activeProject,- activeThreadId,- allocatableActiveTerminalIds,- activeThreadRef,- openTerminal,- activeThreadWorktreePath,- environmentId,- gitCwd,- storeNewTerminal,- ]);- const closeTerminal = useCallback(- (terminalId: string) => {- if (!activeThreadId || !activeThreadRef) return;- const fallbackExitWrite = () =>- writeTerminal({- environmentId,- input: { threadId: activeThreadId, terminalId, data: "exit\n" },- });- void (async () => {- const closeResult = await closeTerminalMutation({- environmentId,- input: {- threadId: activeThreadId,- terminalId,- deleteHistory: true,- },- });- if (closeResult._tag === "Failure" && !isAtomCommandInterrupted(closeResult)) {- await fallbackExitWrite();- }- })();- storeCloseTerminal(activeThreadRef, terminalId);- setTerminalFocusRequestId((value) => value + 1);- },- [- activeThreadId,- activeThreadRef,- closeTerminalMutation,- environmentId,- storeCloseTerminal,- writeTerminal,- ],- );- const runProjectScript = useCallback(- async (- script: ProjectScript,- options?: {- cwd?: string;- env?: Record<string, string>;- worktreePath?: string | null;- preferNewTerminal?: boolean;- rememberAsLastInvoked?: boolean;- },- ) => {- if (!activeThreadId || !activeProject || !activeThread) return;- if (options?.rememberAsLastInvoked !== false) {- setLastInvokedScriptByProjectId((current) => {- if (current[activeProject.id] === script.id) return current;- return { ...current, [activeProject.id]: script.id };- });- }- const targetCwd = options?.cwd ?? gitCwd ?? activeProject.workspaceRoot;- const baseTerminalId =- terminalUiState.activeTerminalId || activeKnownTerminalIds[0] || DEFAULT_THREAD_TERMINAL_ID;- const isBaseTerminalBusy = runningTerminalIds.includes(baseTerminalId);- const wantsNewTerminal = Boolean(options?.preferNewTerminal) || isBaseTerminalBusy;- const shouldCreateNewTerminal = wantsNewTerminal;- const targetWorktreePath = options?.worktreePath ?? activeThread.worktreePath ?? null;-- setTerminalUiLaunchContext({- threadId: activeThreadId,- cwd: targetCwd,- worktreePath: targetWorktreePath,- });- setTerminalOpen(true);- if (!activeThreadRef) {- return;- }- setTerminalFocusRequestId((value) => value + 1);-- const runtimeEnv = projectScriptRuntimeEnv({- project: {- cwd: activeProject.workspaceRoot,- },- worktreePath: targetWorktreePath,- ...(options?.env ? { extraEnv: options.env } : {}),- });- const targetTerminalId = shouldCreateNewTerminal- ? nextTerminalId(allocatableActiveTerminalIds)- : baseTerminalId;- const openTerminalInput: TerminalOpenInput = shouldCreateNewTerminal- ? {- threadId: activeThreadId,- terminalId: targetTerminalId,- cwd: targetCwd,- ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),- env: runtimeEnv,- cols: SCRIPT_TERMINAL_COLS,- rows: SCRIPT_TERMINAL_ROWS,- }- : {- threadId: activeThreadId,- terminalId: targetTerminalId,- cwd: targetCwd,- ...(targetWorktreePath !== null ? { worktreePath: targetWorktreePath } : {}),- env: runtimeEnv,- };-- if (shouldCreateNewTerminal) {- storeNewTerminal(activeThreadRef, targetTerminalId);- } else {- storeSetActiveTerminal(activeThreadRef, targetTerminalId);- }-- const openResult = await openTerminal({ environmentId, input: openTerminalInput });- if (openResult._tag === "Failure") {- if (!isAtomCommandInterrupted(openResult)) {- const error = squashAtomCommandFailure(openResult);- setThreadError(- activeThreadId,- error instanceof Error ? error.message : `Failed to run script "${script.name}".`,- );- }- return;- }-- const writeResult = await writeTerminal({- environmentId,- input: {- threadId: activeThreadId,- terminalId: targetTerminalId,- data: `${script.command}\r`,- },- });- if (writeResult._tag === "Failure" && !isAtomCommandInterrupted(writeResult)) {- const error = squashAtomCommandFailure(writeResult);- setThreadError(- activeThreadId,- error instanceof Error ? error.message : `Failed to run script "${script.name}".`,- );- }- },- [- activeProject,- activeThread,- activeThreadId,- activeThreadRef,- gitCwd,- setTerminalOpen,- setThreadError,- storeNewTerminal,- storeSetActiveTerminal,- setLastInvokedScriptByProjectId,- environmentId,- openTerminal,- activeKnownTerminalIds,- allocatableActiveTerminalIds,- runningTerminalIds,- terminalUiState.activeTerminalId,- writeTerminal,- ],- );-- const persistProjectScripts = useCallback(- async (input: {- projectId: ProjectId;- projectCwd: string;- previousScripts: ReadonlyArray<ProjectScript>;- nextScripts: ReadonlyArray<ProjectScript>;- keybinding?: string | null;- keybindingCommand: KeybindingCommand;- }): Promise<AtomCommandResult<void, unknown>> => {- const updateResult = mapAtomCommandResult(- await updateProject({- environmentId,- input: {- projectId: input.projectId,- scripts: input.nextScripts,- },- }),- () => undefined,- );- if (updateResult._tag === "Failure") {- return updateResult;- }-- const keybindingRule = decodeProjectScriptKeybindingRule({- keybinding: input.keybinding,- command: input.keybindingCommand,- });-- if (isElectron && keybindingRule) {- return mapAtomCommandResult(- await upsertKeybinding({- environmentId,- input: keybindingRule,- }),- () => undefined,- );- }- return updateResult;- },- [environmentId, updateProject, upsertKeybinding],- );- const saveProjectScript = useCallback(- async (input: NewProjectScriptInput): Promise<AtomCommandResult<void, unknown>> => {- if (!activeProject) {- return AsyncResult.success(undefined);- }- const nextId = nextProjectScriptId(- input.name,- activeProject.scripts.map((script) => script.id),- );- const nextScript = buildProjectScript(nextId, input);- const nextScripts = input.runOnWorktreeCreate- ? [- ...activeProject.scripts.map((script) =>- script.runOnWorktreeCreate ? { ...script, runOnWorktreeCreate: false } : script,- ),- nextScript,- ]- : [...activeProject.scripts, nextScript];-- return persistProjectScripts({- projectId: activeProject.id,- projectCwd: activeProject.workspaceRoot,- previousScripts: activeProject.scripts,- nextScripts,- keybinding: input.keybinding,- keybindingCommand: commandForProjectScript(nextId),- });- },- [activeProject, persistProjectScripts],- );- const updateProjectScript = useCallback(- async (- scriptId: string,- input: NewProjectScriptInput,- ): Promise<AtomCommandResult<void, unknown>> => {- if (!activeProject) {- return AsyncResult.success(undefined);- }- const existingScript = activeProject.scripts.find((script) => script.id === scriptId);- if (!existingScript) {- return AsyncResult.failure(Cause.fail(new Error("Script not found.")));- }-- const updatedScript = buildProjectScript(existingScript.id, input);- const nextScripts = activeProject.scripts.map((script) =>- script.id === scriptId- ? updatedScript- : input.runOnWorktreeCreate- ? { ...script, runOnWorktreeCreate: false }- : script,- );-- return persistProjectScripts({- projectId: activeProject.id,- projectCwd: activeProject.workspaceRoot,- previousScripts: activeProject.scripts,- nextScripts,- keybinding: input.keybinding,- keybindingCommand: commandForProjectScript(scriptId),- });- },- [activeProject, persistProjectScripts],- );- const deleteProjectScript = useCallback(- async (scriptId: string): Promise<AtomCommandResult<void, unknown>> => {- if (!activeProject) {- return AsyncResult.success(undefined);- }- const nextScripts = activeProject.scripts.filter((script) => script.id !== scriptId);-- const deletedName = activeProject.scripts.find((s) => s.id === scriptId)?.name;-- const result = await persistProjectScripts({- projectId: activeProject.id,- projectCwd: activeProject.workspaceRoot,- previousScripts: activeProject.scripts,- nextScripts,- keybinding: null,- keybindingCommand: commandForProjectScript(scriptId),- });- if (result._tag === "Success") {- toastManager.add({- type: "success",- title: `Deleted action "${deletedName ?? "Unknown"}"`,- });- } else if (!isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Could not delete action",- description: error instanceof Error ? error.message : "An unexpected error occurred.",- }),- );- }- return result;- },- [activeProject, persistProjectScripts],- );-- const handleRuntimeModeChange = useCallback(- (mode: RuntimeMode) => {- if (mode === runtimeMode) return;- setComposerDraftRuntimeMode(composerDraftTarget, mode);- if (isLocalDraftThread) {- setDraftThreadContext(composerDraftTarget, { runtimeMode: mode });- }- scheduleComposerFocus();- },- [- isLocalDraftThread,- runtimeMode,- scheduleComposerFocus,- composerDraftTarget,- setComposerDraftRuntimeMode,- setDraftThreadContext,- ],- );-- const handleInteractionModeChange = useCallback(- (mode: ProviderInteractionMode) => {- if (mode === interactionMode) return;- setComposerDraftInteractionMode(composerDraftTarget, mode);- if (isLocalDraftThread) {- setDraftThreadContext(composerDraftTarget, { interactionMode: mode });- }- scheduleComposerFocus();- },- [- interactionMode,- isLocalDraftThread,- scheduleComposerFocus,- composerDraftTarget,- setComposerDraftInteractionMode,- setDraftThreadContext,- ],- );- const toggleInteractionMode = useCallback(() => {- handleInteractionModeChange(interactionMode === "plan" ? "default" : "plan");- }, [handleInteractionModeChange, interactionMode]);- const createBrowserSurface = useCallback(() => {- if (!activeThreadRef) return;- void addBrowserSurface({ threadRef: activeThreadRef, openPreview });- }, [activeThreadRef, openPreview]);- const addDiffSurface = useCallback(() => {- if (!activeThreadRef || !isServerThread || !isGitRepo) return;- useRightPanelStore.getState().open(activeThreadRef, "diff");- onDiffPanelOpen?.();- }, [activeThreadRef, isGitRepo, isServerThread, onDiffPanelOpen]);- const addFilesSurface = useCallback(() => {- if (!activeThreadRef || !activeProject) return;- useRightPanelStore.getState().open(activeThreadRef, "files");- }, [activeProject, activeThreadRef]);- const addAgentsSurface = useCallback(() => {- if (!activeThreadRef) return;- useRightPanelStore.getState().open(activeThreadRef, "agents");- }, [activeThreadRef]);- const openFileSurface = useCallback(- (relativePath: string) => {- if (!activeThreadRef || !activeProject) return;- useRightPanelStore.getState().openFile(activeThreadRef, relativePath);- },- [activeProject, activeThreadRef],- );- // The thread's own change request, placed against the project it belongs to. Without a- // project there is nothing to resolve it against, so the caller falls back to the browser.- const linkedThreadPullRequest = activeThread?.linkedPullRequest ?? null;- const activeProjectRepository = activeProject?.repositoryIdentity?.displayName ?? null;- const threadRepository = linkedThreadPullRequest?.repository ?? activeProjectRepository;- const openThreadPullRequest = useCallback(- (number: number) => {- if (!supportsPullRequests || !activeThreadRef) {- return;- }- const projectId = linkedThreadPullRequest?.projectId ?? activeProject?.id;- const repository = linkedThreadPullRequest?.repository ?? activeProjectRepository;- if (projectId === undefined || repository === null) return;- useRightPanelStore.getState().openPullRequest(activeThreadRef, {- projectId,- repository,- number,- });- },- [- activeProject,- activeProjectRepository,- activeThreadRef,- linkedThreadPullRequest,- supportsPullRequests,- ],- );- const openProjectPullRequest = useCallback(- (number: number) => {- if (- !supportsPullRequests ||- !activeThreadRef ||- !activeProject ||- activeProjectRepository === null- ) {- return;- }- useRightPanelStore.getState().openPullRequest(activeThreadRef, {- projectId: activeProject.id,- repository: activeProjectRepository,- number,- });- },- [activeProject, activeProjectRepository, activeThreadRef, supportsPullRequests],- );- const togglePreviewPanel = useCallback(() => {- if (!activeThreadRef || !isPreviewSupportedInRuntime()) return;- if (previewPanelOpen) {- useRightPanelStore.getState().close(activeThreadRef);- return;- }- const activeTabId = activePreviewState.activeTabId;- if (activeTabId) {- useRightPanelStore.getState().openBrowser(activeThreadRef, activeTabId);- } else {- createBrowserSurface();- }- }, [activePreviewState.activeTabId, activeThreadRef, createBrowserSurface, previewPanelOpen]);- const closePreviewPanel = useCallback(() => {- if (activeThreadRef) {- setMaximizedRightPanelThreadKey(null);- useRightPanelStore.getState().close(activeThreadRef);- }- }, [activeThreadRef]);- const addTerminalSurface = useCallback(() => {- if (!activeThreadRef || !activeThreadId || !activeProject) return;- const cwd = gitCwd ?? activeProject.workspaceRoot;- const terminalId = nextTerminalId(allocatableActiveTerminalIds);- useRightPanelStore.getState().openTerminal(activeThreadRef, terminalId);- setTerminalFocusRequestId((value) => value + 1);- void openTerminal({- environmentId: activeThreadRef.environmentId,- input: {- threadId: activeThreadId,- terminalId,- cwd,- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),- env: projectScriptRuntimeEnv({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThreadWorktreePath,- }),- },- });- }, [- activeProject,- activeThreadId,- activeThreadRef,- activeThreadWorktreePath,- allocatableActiveTerminalIds,- gitCwd,- openTerminal,- ]);- const splitPanelTerminal = useCallback(- (direction: "horizontal" | "vertical" = "horizontal") => {- if (- !activeThreadRef ||- !activeThreadId ||- !activeProject ||- activeRightPanelSurface?.kind !== "terminal" ||- activeRightPanelSurface.terminalIds.length >= MAX_TERMINALS_PER_GROUP- ) {- return;- }- const terminalId = nextTerminalId(allocatableActiveTerminalIds);- const cwd = gitCwd ?? activeProject.workspaceRoot;- useRightPanelStore- .getState()- .splitTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId, direction);- setTerminalFocusRequestId((value) => value + 1);- void openTerminal({- environmentId: activeThreadRef.environmentId,- input: {- threadId: activeThreadId,- terminalId,- cwd,- ...(activeThreadWorktreePath != null ? { worktreePath: activeThreadWorktreePath } : {}),- env: projectScriptRuntimeEnv({- project: { cwd: activeProject.workspaceRoot },- worktreePath: activeThreadWorktreePath,- }),- },- });- },- [- activeProject,- activeRightPanelSurface,- activeThreadId,- activeThreadRef,- activeThreadWorktreePath,- allocatableActiveTerminalIds,- gitCwd,- openTerminal,- ],- );- const splitPanelTerminalVertical = useCallback(() => {- splitPanelTerminal("vertical");- }, [splitPanelTerminal]);- const activatePanelTerminal = useCallback(- (terminalId: string) => {- if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return;- useRightPanelStore- .getState()- .activateTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);- setTerminalFocusRequestId((value) => value + 1);- },- [activeRightPanelSurface, activeThreadRef],- );- const closePanelTerminal = useCallback(- (terminalId: string) => {- if (!activeThreadRef || activeRightPanelSurface?.kind !== "terminal") return;- void closeTerminalMutation({- environmentId: activeThreadRef.environmentId,- input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },- });- storeCloseTerminal(activeThreadRef, terminalId);- useRightPanelStore- .getState()- .closeTerminal(activeThreadRef, activeRightPanelSurface.id, terminalId);- setTerminalFocusRequestId((value) => value + 1);- },- [activeRightPanelSurface, activeThreadRef, closeTerminalMutation, storeCloseTerminal],- );- const requestCloseTerminal = useCallback(- (terminalId: string) => {- const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);- void confirmTerminalClose([label]).then((confirmed) => {- if (confirmed) closeTerminal(terminalId);- });- },- [activeTerminalLabelsById, closeTerminal],- );- const requestClosePanelTerminal = useCallback(- (terminalId: string) => {- const label = activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId);- void confirmTerminalClose([label]).then((confirmed) => {- if (confirmed) closePanelTerminal(terminalId);- });- },- [activeTerminalLabelsById, closePanelTerminal],- );- const activateRightPanelSurface = useCallback(- (surface: RightPanelSurface) => {- if (!activeThreadRef) return;- useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id);- if (surface.kind === "preview" && surface.resourceId) {- setActivePreviewTab(activeThreadRef, surface.resourceId);- }- if (surface.kind === "terminal") {- setTerminalFocusRequestId((value) => value + 1);- }- if (surface.kind === "diff" && !diffOpen) {- onDiffPanelOpen?.();- }- },- [activeThreadRef, diffOpen, onDiffPanelOpen],- );- const toggleRightPanel = useCallback(() => {- if (!activeThreadRef) return;- if (rightPanelOpen) {- closePreviewPanel();- return;- }- useRightPanelStore.getState().toggleVisibility(activeThreadRef);- }, [activeThreadRef, closePreviewPanel, rightPanelOpen]);- const toggleRightPanelMaximized = useCallback(() => {- if (!canMaximizeRightPanel) return;- setMaximizedRightPanelThreadKey((threadKey) =>- threadKey === routeThreadKey ? null : routeThreadKey,- );- }, [canMaximizeRightPanel, routeThreadKey]);- const cleanupRightPanelSurfaces = useCallback(- (surfaces: readonly RightPanelSurface[]) => {- if (!activeThreadRef) return;- for (const surface of surfaces) {- if (surface.kind === "preview" && surface.resourceId) {- void closePreviewSession({- closePreview,- snapshot: activePreviewState.sessions[surface.resourceId] ?? null,- tabId: surface.resourceId,- threadRef: activeThreadRef,- });- }- if (surface.kind === "terminal") {- for (const terminalId of surface.terminalIds) {- storeCloseTerminal(activeThreadRef, terminalId);- void closeTerminalMutation({- environmentId: activeThreadRef.environmentId,- input: { threadId: activeThreadRef.threadId, terminalId, deleteHistory: true },- });- }- }- }- },- [- activeThreadRef,- activePreviewState.sessions,- closePreview,- closeTerminalMutation,- storeCloseTerminal,- ],- );- const syncActivePreviewSurface = useCallback(() => {- if (!activeThreadRef) return;- const nextActiveSurface = selectActiveRightPanelSurface(- useRightPanelStore.getState().byThreadKey,- activeThreadRef,- );- if (nextActiveSurface?.kind === "preview" && nextActiveSurface.resourceId) {- setActivePreviewTab(activeThreadRef, nextActiveSurface.resourceId);- }- }, [activeThreadRef]);- const closeRightPanelSurface = useCallback(- (surface: RightPanelSurface) => {- if (!activeThreadRef) return;- const finishClose = () => {- cleanupRightPanelSurfaces([surface]);- useRightPanelStore.getState().closeSurface(activeThreadRef, surface.id);- syncActivePreviewSurface();- };- if (surface.kind !== "terminal") {- finishClose();- return;- }- const activeLabel =- activeTerminalLabelsById.get(surface.activeTerminalId) ??- getTerminalLabel(surface.activeTerminalId);- const otherLabels = surface.terminalIds- .filter((terminalId) => terminalId !== surface.activeTerminalId)- .map(- (terminalId) => activeTerminalLabelsById.get(terminalId) ?? getTerminalLabel(terminalId),- );- void confirmTerminalClose([activeLabel, ...otherLabels]).then((confirmed) => {- if (confirmed) finishClose();- });- },- [- activeThreadRef,- activeTerminalLabelsById,- cleanupRightPanelSurfaces,- syncActivePreviewSurface,- ],- );- const closeOtherRightPanelSurfaces = useCallback(- (surface: RightPanelSurface) => {- if (!activeThreadRef) return;- const surfaces = rightPanelState.surfaces.filter((entry) => entry.id !== surface.id);- cleanupRightPanelSurfaces(surfaces);- useRightPanelStore.getState().closeOtherSurfaces(activeThreadRef, surface.id);- syncActivePreviewSurface();- },- [- activeThreadRef,- cleanupRightPanelSurfaces,- rightPanelState.surfaces,- syncActivePreviewSurface,- ],- );- const closeRightPanelSurfacesToRight = useCallback(- (surface: RightPanelSurface) => {- if (!activeThreadRef) return;- const surfaceIndex = rightPanelState.surfaces.findIndex((entry) => entry.id === surface.id);- if (surfaceIndex < 0) return;- const surfaces = rightPanelState.surfaces.slice(surfaceIndex + 1);- cleanupRightPanelSurfaces(surfaces);- useRightPanelStore.getState().closeSurfacesToRight(activeThreadRef, surface.id);- syncActivePreviewSurface();- },- [- activeThreadRef,- cleanupRightPanelSurfaces,- rightPanelState.surfaces,- syncActivePreviewSurface,- ],- );- const closeAllRightPanelSurfaces = useCallback(() => {- if (!activeThreadRef) return;- cleanupRightPanelSurfaces(rightPanelState.surfaces);- useRightPanelStore.getState().closeAllSurfaces(activeThreadRef);- }, [activeThreadRef, cleanupRightPanelSurfaces, rightPanelState.surfaces]);- const copyRightPanelFilePath = useCallback((relativePath: string) => {- if (typeof window === "undefined" || !navigator.clipboard?.writeText) {- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to copy path",- description: "Clipboard API unavailable.",- }),- );- return;- }-- void navigator.clipboard.writeText(relativePath).then(- () => {- toastManager.add({- type: "success",- title: "Path copied",- description: relativePath,- });- },- (error) => {- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to copy path",- description: error instanceof Error ? error.message : "An error occurred.",- }),- );- },- );- }, []);- useEffect(- () =>- subscribePreviewAction((action) => {- if (action === "toggle-panel") togglePreviewPanel();- }),- [togglePreviewPanel],- );- const persistThreadSettingsForNextTurn = useCallback(- async (input: {- threadId: ThreadId;- createdAt: string;- modelSelection?: ModelSelection;- branch?: string;- runtimeMode: RuntimeMode;- interactionMode: ProviderInteractionMode;- }): Promise<AtomCommandResult<void, unknown>> => {- if (!serverThread) {- return AsyncResult.success(undefined);- }-- let result: AtomCommandResult<void, unknown> = AsyncResult.success(undefined);- const metadataUpdate = resolveThreadMetadataUpdateForNextTurn({- currentModelSelection: serverThread.modelSelection,- ...(input.modelSelection ? { nextModelSelection: input.modelSelection } : {}),- currentBranch: serverThread.branch,- ...(input.branch ? { nextBranch: input.branch } : {}),- });- if (metadataUpdate) {- result = mapAtomCommandResult(- await updateThreadMetadata({- environmentId,- input: {- threadId: input.threadId,- ...metadataUpdate,- },- }),- () => undefined,- );- if (result._tag === "Failure") {- return result;- }- }-- if (input.runtimeMode !== serverThread.runtimeMode) {- result = mapAtomCommandResult(- await setThreadRuntimeMode({- environmentId,- input: {- threadId: input.threadId,- runtimeMode: input.runtimeMode,- createdAt: input.createdAt,- },- }),- () => undefined,- );- if (result._tag === "Failure") {- return result;- }- }-- if (input.interactionMode !== serverThread.interactionMode) {- result = mapAtomCommandResult(- await setThreadInteractionMode({- environmentId,- input: {- threadId: input.threadId,- interactionMode: input.interactionMode,- createdAt: input.createdAt,- },- }),- () => undefined,- );- }- return result;- },- [- environmentId,- serverThread,- setThreadInteractionMode,- setThreadRuntimeMode,- updateThreadMetadata,- ],- );-- // Debounce *showing* the scroll-to-bottom pill so it doesn't flash during- // thread switches. LegendList fires scroll events with isAtEnd=false while- // initialScrollAtEnd is settling; hiding is always immediate.- const showScrollDebouncer = useRef(- new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }),- );- const timelineScrollModeRef = useRef<TimelineScrollMode>("following-end");- // State mirror of the follow mode refs. LegendList's maintainScrollAtEnd- // re-pins on its own (independent of the refs), so the timeline needs a- // render-visible flag to switch it off once the user scrolls away.- const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true);- const pendingTimelineAnchorRef = useRef<MessageId | null>(null);- const positionedTimelineAnchorRef = useRef<MessageId | null>(null);- const settledTimelineAnchorRef = useRef<MessageId | null>(null);- const activeTimelineAnchorIndexRef = useRef<number | null>(null);- const anchorUserScrollGenerationRef = useRef(0);- const liveFollowUserScrollGenerationRef = useRef<number | null>(0);- // Manual navigation stops live-follow without removing anchored end space.- // Collapsing that space during a gesture clamps the viewport back to the end.- const cancelTimelineLiveFollowForUserNavigation = useCallback(() => {- anchorUserScrollGenerationRef.current += 1;- timelineScrollModeRef.current = "free-scrolling";- liveFollowUserScrollGenerationRef.current = null;- setTimelineLiveFollowEnabled(false);- pendingTimelineAnchorRef.current = null;- positionedTimelineAnchorRef.current = null;- settledTimelineAnchorRef.current = null;- activeTimelineAnchorIndexRef.current = null;- }, []);- const cancelTimelineLiveFollowForUserNavigationRef = useRef(- cancelTimelineLiveFollowForUserNavigation,- );- useEffect(() => {- cancelTimelineLiveFollowForUserNavigationRef.current =- cancelTimelineLiveFollowForUserNavigation;- }, [cancelTimelineLiveFollowForUserNavigation]);- const getActiveTimelineTurnMetrics = useCallback(- (list?: LegendListRef | null) => {- const resolvedList = list ?? legendListRef.current;- const anchorIndex = activeTimelineAnchorIndexRef.current;- const state = resolvedList?.getState();- if (!resolvedList || !state || anchorIndex === null) {- return null;- }-- return getAnchoredTurnMetrics({- state,- anchorIndex,- composerOverlayHeight,- anchorOffset: CHAT_LIST_ANCHOR_OFFSET,- });- },- [composerOverlayHeight],- );- const timelineRealContentOverflowsViewport = useCallback(- (list?: LegendListRef | null) => {- const resolvedList = list ?? legendListRef.current;- const state = resolvedList?.getState();- if (!resolvedList || !state || state.data.length === 0) {- return false;- }-- const lastRowIndex = state.data.length - 1;- const lastRowTop = state.positionAtIndex(lastRowIndex);- const lastRowHeight = state.sizeAtIndex(lastRowIndex);- if (- typeof lastRowTop !== "number" ||- typeof lastRowHeight !== "number" ||- !Number.isFinite(lastRowTop) ||- !Number.isFinite(lastRowHeight)- ) {- return false;- }-- const realContentBottom = lastRowTop + Math.max(1, lastRowHeight);- const visibleScrollLength = Math.max(- 0,- (state.scrollLength ?? 0) - composerOverlayHeight - CHAT_LIST_ANCHOR_OFFSET,- );- return realContentBottom > visibleScrollLength;- },- [composerOverlayHeight],- );- // Live-follow stays active after send/thread-open until an actual list scroll- // gesture opts out.- const scrollToEnd = useCallback((animated = false) => {- isAtEndRef.current = true;- timelineScrollModeRef.current = "following-end";- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;- setTimelineLiveFollowEnabled(true);- pendingTimelineAnchorRef.current = null;- positionedTimelineAnchorRef.current = null;- settledTimelineAnchorRef.current = null;- activeTimelineAnchorIndexRef.current = null;- showScrollDebouncer.current.cancel();- setShowScrollToBottom(false);- setTimelineAnchor(releaseChatTimelineAnchor);- requestAnimationFrame(() => {- void legendListRef.current?.scrollToEnd?.({ animated });- });- }, []);- useLayoutEffect(() => {- if (timelineScrollModeRef.current !== "anchoring-new-turn") {- return;- }-- if (- shouldReleaseTimelineAnchorForToolActivity({- anchorMessageId: timelineAnchorMessageId,- liveFollowEnabled: timelineLiveFollowEnabled,- runningTurnId: activeRunningTurnId,- timelineEntries,- })- ) {- scrollToEnd();- }- }, [- activeRunningTurnId,- scrollToEnd,- timelineAnchorMessageId,- timelineEntries,- timelineLiveFollowEnabled,- ]);- useEffect(() => {- let removeListeners: (() => void) | null = null;- let frame: number | null = null;- const attach = (remainingAttempts: number) => {- frame = requestAnimationFrame(() => {- frame = null;- const scrollNode = legendListRef.current?.getScrollableNode();- if (!scrollNode) {- // The list may not have mounted on the first frame after a thread- // switch — without a retry the opt-out listeners never attach and- // live-follow becomes impossible to escape for the whole thread.- if (remainingAttempts > 0) {- attach(remainingAttempts - 1);- }- return;- }- const handleManualNavigation = () => {- cancelTimelineLiveFollowForUserNavigationRef.current();- };- // The gestures below must only break follow when they can actually- // move the viewport away from the live edge. Follow now gates- // LegendList's maintainScrollAtEnd, so a spurious break while pinned- // at the end produces no scroll event, never re-arms, and streaming- // silently stops following. Underflowing content can't scroll at all,- // so nothing there should break follow.- const contentScrollsUp = () => timelineRealContentOverflowsViewport();- // The follow re-arm band, not the strict flag: streaming growth makes- // isAtEnd flicker false for a frame before the follow scroll catches- // up, and a gesture landing in that window while still pinned would- // otherwise break follow with no scroll event left to re-arm it.- const viewportIsAwayFromEnd = () =>- resolveTimelineIsAtEnd(legendListRef.current?.getState(), composerOverlayHeight) ===- false;- // Only an upward wheel is a navigation intent; wheeling down while- // following either does nothing (at the end) or moves toward it.- const handleWheel = (event: WheelEvent) => {- if (event.deltaY < 0 && contentScrollsUp()) {- handleManualNavigation();- }- };- // Touch direction isn't observable here (touchmove fires on any- // finger motion, scrolling or not), so break only once the drag has- // actually carried the viewport out of the end band — an upward flick- // gets there within its first few events and later touchmoves break.- const handleTouchMove = () => {- if (viewportIsAwayFromEnd()) {- handleManualNavigation();- }- };- // Scrollbar drags produce no wheel/touch events; they are the only- // pointerdowns whose target is the scroll node itself rather than a- // message row. Content clicks break follow only away from the end- // (reading or selecting up there must hold position); clicking near- // the live edge keeps following.- const handlePointerDown = (event: PointerEvent) => {- if (event.target === scrollNode) {- if (contentScrollsUp()) {- handleManualNavigation();- }- return;- }- if (viewportIsAwayFromEnd()) {- handleManualNavigation();- }- };- // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and- // pointer events entirely; without this the timeline yanks back to- // the end on the next stream chunk.- const handleKeyDown = (event: KeyboardEvent) => {- switch (event.key) {- case "PageUp":- case "Home":- case "ArrowUp":- if (contentScrollsUp()) {- handleManualNavigation();- }- break;- default:- break;- }- };- scrollNode.addEventListener("wheel", handleWheel, {- passive: true,- });- scrollNode.addEventListener("touchmove", handleTouchMove, {- passive: true,- });- scrollNode.addEventListener("pointerdown", handlePointerDown, {- passive: true,- });- scrollNode.addEventListener("keydown", handleKeyDown);- removeListeners = () => {- scrollNode.removeEventListener("wheel", handleWheel);- scrollNode.removeEventListener("touchmove", handleTouchMove);- scrollNode.removeEventListener("pointerdown", handlePointerDown);- scrollNode.removeEventListener("keydown", handleKeyDown);- };- });- };- attach(12);-- return () => {- if (frame !== null) {- cancelAnimationFrame(frame);- }- removeListeners?.();- };- }, [activeThread?.id, composerOverlayHeight, timelineRealContentOverflowsViewport]);-- const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => {- // Anchored-end space can be remeasured when the turn completes. Once the- // user has scrolled away (or returned to ordinary end-following), that- // remeasurement must not restart the send-time anchor positioning.- if (timelineScrollModeRef.current !== "anchoring-new-turn") {- return;- }- if (pendingTimelineAnchorRef.current === messageId) {- pendingTimelineAnchorRef.current = null;- }- activeTimelineAnchorIndexRef.current = anchorIndex;- if (positionedTimelineAnchorRef.current === messageId) {- return;- }- positionedTimelineAnchorRef.current = messageId;- settledTimelineAnchorRef.current = null;- const positionAnchor = (remainingAttempts: number) => {- requestAnimationFrame(() => {- if (positionedTimelineAnchorRef.current !== messageId) {- return;- }- const list = legendListRef.current;- if (!list) {- if (remainingAttempts > 0) {- positionAnchor(remainingAttempts - 1);- }- return;- }- void list- .scrollToIndex({- index: anchorIndex,- animated: true,- viewPosition: 0,- viewOffset: CHAT_LIST_ANCHOR_OFFSET,- })- .then(() => {- if (positionedTimelineAnchorRef.current !== messageId) {- return;- }- settledTimelineAnchorRef.current = messageId;- });- });- };- requestAnimationFrame(() => positionAnchor(12));- }, []);-- const onIsAtEndChange = useCallback((isAtEnd: boolean) => {- if (- !isAtEnd &&- liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current- ) {- showScrollDebouncer.current.cancel();- setShowScrollToBottom(false);- return;- }- if (isAtEndRef.current === isAtEnd) return;- isAtEndRef.current = isAtEnd;- if (isAtEnd) {- timelineScrollModeRef.current = "following-end";- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;- setTimelineLiveFollowEnabled(true);- // Reachable only once manual navigation has already broken follow, so- // the anchored turn framing is over: the user scrolled back to the live- // edge and expects the stream to stick to it again, exactly like the- // scroll-to-bottom pill.- setTimelineAnchor(releaseChatTimelineAnchor);- showScrollDebouncer.current.cancel();- setShowScrollToBottom(false);- } else {- timelineScrollModeRef.current = "free-scrolling";- liveFollowUserScrollGenerationRef.current = null;- showScrollDebouncer.current.maybeExecute();- }- }, []);-- // Anchored end space intentionally disables LegendList's normal end-follow so- // the sent message can stay near the top. T3 only owns streaming adjustments- // during that mode; LegendList owns ordinary end-follow everywhere else.- useEffect(() => {- if (!activeThread?.id) {- return;- }- if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {- return;- }- if (timelineScrollModeRef.current !== "anchoring-new-turn") {- return;- }-- let secondFrame: number | null = null;- const frame = requestAnimationFrame(() => {- secondFrame = requestAnimationFrame(() => {- if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) {- return;- }- if (pendingTimelineAnchorRef.current !== null) {- return;- }- if (- positionedTimelineAnchorRef.current !== null &&- settledTimelineAnchorRef.current !== positionedTimelineAnchorRef.current- ) {- return;- }- const list = legendListRef.current;- if (!list) {- return;- }-- const metrics = getActiveTimelineTurnMetrics(list);- if (!metrics || metrics.scrollDeltaToRevealEnd <= 1) {- return;- }-- const nextOffset = list.getState().scroll + metrics.scrollDeltaToRevealEnd;- void list.scrollToOffset({ offset: nextOffset, animated: false });- });- });-- return () => {- cancelAnimationFrame(frame);- if (secondFrame !== null) {- cancelAnimationFrame(secondFrame);- }- };- }, [activeThread?.id, timelineEntries, getActiveTimelineTurnMetrics]);-- useEffect(() => {- setPullRequestDialogState(null);- isAtEndRef.current = true;- timelineScrollModeRef.current = "following-end";- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;- setTimelineLiveFollowEnabled(true);- pendingTimelineAnchorRef.current = null;- positionedTimelineAnchorRef.current = null;- settledTimelineAnchorRef.current = null;- activeTimelineAnchorIndexRef.current = null;- showScrollDebouncer.current.cancel();- setShowScrollToBottom(false);- // activeThreadRef resets transitively with the active thread.- }, [activeThread?.id]);-- useEffect(() => {- setIsRevertingCheckpoint(false);- }, [activeThread?.id]);-- useEffect(() => {- if (!activeThread?.id || terminalUiState.terminalOpen) return;- const frame = window.requestAnimationFrame(() => {- focusComposer();- });- return () => {- window.cancelAnimationFrame(frame);- };- }, [activeThread?.id, focusComposer, terminalUiState.terminalOpen]);-- useEffect(() => {- if (!activeThread?.id) return;- if (activeThread.messages.length === 0) {- return;- }- const serverIds = new Set(activeThread.messages.map((message) => message.id));- const removedMessages = optimisticUserMessages.filter((message) => serverIds.has(message.id));- if (removedMessages.length === 0) {- return;- }- const timer = window.setTimeout(() => {- setOptimisticUserMessages((existing) =>- existing.filter((message) => !serverIds.has(message.id)),- );- }, 0);- for (const removedMessage of removedMessages) {- const previewUrls = collectUserMessageBlobPreviewUrls(removedMessage);- if (previewUrls.length > 0) {- handoffAttachmentPreviews(removedMessage.id, previewUrls);- continue;- }- revokeUserMessagePreviewUrls(removedMessage);- }- return () => {- window.clearTimeout(timer);- };- }, [activeThread?.id, activeThread?.messages, handoffAttachmentPreviews, optimisticUserMessages]);-- useEffect(() => {- setOptimisticUserMessages((existing) => {- for (const message of existing) {- revokeUserMessagePreviewUrls(message);- }- return [];- });- resetLocalDispatch();- setExpandedImage(null);- }, [draftId, resetLocalDispatch, threadId]);-- const closeExpandedImage = useCallback(() => {- setExpandedImage(null);- }, []);-- const activeWorktreePath = activeThread?.worktreePath ?? null;- const derivedEnvMode: DraftThreadEnvMode = resolveEffectiveEnvMode({- activeWorktreePath,- hasServerThread: isServerThread,- draftThreadEnvMode: isLocalDraftThread ? draftThread?.envMode : undefined,- });- const canOverrideServerThreadEnvMode = Boolean(- isServerThread &&- activeThread &&- activeThread.messages.length === 0 &&- activeThread.worktreePath === null &&- !envLocked,- );- const envMode: DraftThreadEnvMode = canOverrideServerThreadEnvMode- ? (pendingServerThreadEnvMode ?? draftThread?.envMode ?? derivedEnvMode)- : derivedEnvMode;- const activeThreadBranch =- canOverrideServerThreadEnvMode && pendingServerThreadBranch !== undefined- ? pendingServerThreadBranch- : (activeThread?.branch ?? null);- const startFromOrigin = isLocalDraftThread- ? (draftThread?.startFromOrigin ?? false)- : canOverrideServerThreadEnvMode- ? (pendingServerThreadStartFromOriginByThreadId[activeThread?.id ?? ""] ??- primaryServerSettings.newWorktreesStartFromOrigin)- : false;- const sendEnvMode = resolveSendEnvMode({- requestedEnvMode: envMode,- isGitRepo,- });- const localCheckoutBranchMismatch = useMemo(- () =>- isServerThread- ? resolveLocalCheckoutBranchMismatch({- effectiveEnvMode: envMode,- activeWorktreePath,- activeThreadBranch,- currentGitBranch: gitStatusQuery.data?.refName ?? null,- })- : null,- [activeThreadBranch, activeWorktreePath, envMode, gitStatusQuery.data?.refName, isServerThread],- );- // Settled state of the open thread, resolved exactly like the sidebar- // partition (same shell, same capability gate, same PR auto-settle input)- // so the banner and the sidebar row never disagree.- const activeThreadShell = useThreadShell(isServerThread ? activeThreadRef : null);- const activeComposerTasksProgress =- activeLatestTurn !== null && !latestTurnSettled- ? (activeThreadShell?.planProgress ?? null)- : null;- const activeComposerTaskSteps =- activeComposerTasksProgress && activePlan && activePlan.turnId === activeLatestTurn?.turnId- ? activePlan.steps- : null;- const autoSettleAfterDays = useClientSettings((settings) => settings.sidebarAutoSettleAfterDays);- const autoSettleOnMerge = useClientSettings((settings) => settings.sidebarAutoSettleOnMerge);- const linkedPullRequestStatus = useLinkedThreadPullRequest(- activeThreadRef?.environmentId ?? null,- linkedThreadPullRequest,- );- const activeThreadPr = resolveDisplayedThreadPr({- threadBranch: activeThread?.branch ?? null,- gitStatus: gitStatusQuery.data ?? null,- snapshot: activeThreadKey ? changeRequestSnapshotByKey.get(activeThreadKey) : undefined,- retainTerminalOnBranchMismatch: activeThread?.worktreePath === null,- linkedPullRequest: linkedThreadPullRequest,- linkedPullRequestStatus,- });- // The right panel offers the thread's own change request, so it can only offer it once the- // branch has one; until then the picker says so rather than opening an empty panel.- const addPullRequestSurface = useCallback(() => {- if (activeThreadPr === null) return;- openThreadPullRequest(activeThreadPr.number);- }, [activeThreadPr, openThreadPullRequest]);- const pullRequestSurfaceAvailable =- supportsPullRequests && activeThreadPr !== null && threadRepository !== null;- // Primitive slice of the displayed PR for the settle-rule memos below:- // resolveDisplayedThreadPr returns a fresh object every render, so memoize- // on the fields the rules read instead of the object identity.- const activeThreadPrState = activeThreadPr?.state ?? null;- const activeThreadPrUpdatedAt = activeThreadPr?.updatedAt ?? null;- const activeThreadChangeRequest = useMemo(- () =>- activeThreadPrState === null- ? null- : { state: activeThreadPrState, updatedAt: activeThreadPrUpdatedAt },- [activeThreadPrState, activeThreadPrUpdatedAt],- );- const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true;- const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true;- const nowMinute = useNowMinute();- const snoozeNow = new Date().toISOString();- const activeThreadSnoozed =- activeThreadShell !== null &&- supportsSnooze &&- effectiveSnoozed(activeThreadShell, { now: snoozeNow });- const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0);- void snoozeWakeTick;- const activeThreadWokeAt =- activeThreadShell !== null && supportsSnooze- ? threadWokeAt(activeThreadShell, { now: snoozeNow })- : null;- useEffect(() => {- if (!activeThreadSnoozed) return;- const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? "");- if (!Number.isFinite(wakeAtMs)) return;- const id = window.setTimeout(- () => bumpSnoozeWakeTick((tick) => tick + 1),- Math.min(Math.max(0, wakeAtMs - Date.now()) + 50, 2_147_483_647),- );- return () => window.clearTimeout(id);- }, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]);- const acknowledgeActiveThreadWoke = useCallback(() => {- if (activeThreadRef === null || activeThreadWokeAt === null) return;- markThreadVisited(scopedThreadKey(activeThreadRef), activeThreadWokeAt);- }, [activeThreadRef, activeThreadWokeAt, markThreadVisited]);- // Mirror of the sidebar's Woke pill for the open thread. It uses the same- // visit comparison and change request settle rule.- const activeThreadLastVisitedAt = useUiStateStore((store) =>- activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey],- );- const activeThreadWokeVisible = useMemo(() => {- if (activeThreadWokeAt === null) return false;- if (- changeRequestAutoSettles(activeThreadChangeRequest, {- autoSettleOnMerge,- thread: activeThreadShell,- })- ) {- return false;- }- const wokeAtMs = Date.parse(activeThreadWokeAt);- if (Number.isNaN(wokeAtMs)) return false;- // Having the thread open counts as a visit at completedAt (the effect- // above stamps it); folding that floor in here keeps a completion-- // triggered wake from flashing a banner for one frame before the stamp- // lands. An unparseable stored visit counts as never-visited: corrupt- // local data must not eat the wake signal.- const storedVisitMs = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN;- const completedAtMs = activeLatestTurn?.completedAt- ? Date.parse(activeLatestTurn.completedAt)- : NaN;- const lastVisitedMs = Math.max(- Number.isNaN(storedVisitMs) ? -Infinity : storedVisitMs,- Number.isNaN(completedAtMs) ? -Infinity : completedAtMs,- );- return lastVisitedMs < wokeAtMs;- }, [- activeLatestTurn?.completedAt,- activeThreadLastVisitedAt,- activeThreadChangeRequest,- activeThreadShell,- activeThreadWokeAt,- autoSettleOnMerge,- ]);- const activeThreadSettled = useMemo(() => {- if (activeThreadShell === null || !supportsSettlement) return false;- return effectiveSettled(activeThreadShell, {- now: `${nowMinute}:00.000Z`,- autoSettleAfterDays,- autoSettleOnMerge,- changeRequest: activeThreadChangeRequest,- });- }, [- activeThreadChangeRequest,- activeThreadShell,- autoSettleAfterDays,- autoSettleOnMerge,- changeRequestSnapshotByKey,- nowMinute,- supportsSettlement,- ]);- const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {- reportFailure: false,- });- // Keyed by thread, not a boolean: the pending state must follow the thread- // it belongs to across navigation, and a request resolving for thread A- // must never clear (or re-enable) thread B's button.- const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null);- const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey;- const handleUnsettleActiveThread = useCallback(async () => {- if (!activeThreadRef) return;- const threadKey = scopedThreadKey(activeThreadRef);- setUnsettlingThreadKey(threadKey);- try {- const result = await unsettleThreadMutation({- environmentId: activeThreadRef.environmentId,- input: { threadId: activeThreadRef.threadId, reason: "user" },- });- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to un-settle thread",- description: error instanceof Error ? error.message : "An error occurred.",- }),- );- }- } finally {- setUnsettlingThreadKey((current) => (current === threadKey ? null : current));- }- }, [activeThreadRef, unsettleThreadMutation]);- const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {- reportFailure: false,- });- const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null);- const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey;- const handleUnsnoozeActiveThread = useCallback(async () => {- if (!activeThreadRef) return;- const threadKey = scopedThreadKey(activeThreadRef);- setUnsnoozingThreadKey(threadKey);- try {- const result = await unsnoozeThreadMutation({- environmentId: activeThreadRef.environmentId,- input: { threadId: activeThreadRef.threadId, reason: "user" },- });- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to wake thread",- description: error instanceof Error ? error.message : "An error occurred.",- }),- );- }- } finally {- setUnsnoozingThreadKey((current) => (current === threadKey ? null : current));- }- }, [activeThreadRef, unsnoozeThreadMutation]);- const [isRestoringThreadBranch, setIsRestoringThreadBranch] = useState(false);- const [branchRestoreConfirmOpen, setBranchRestoreConfirmOpen] = useState(false);- // Once revealed for a given mismatch, the banner stays mounted until the- // mismatch changes or resolves, so clearing the draft doesn't flicker it.- const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null);- // Dismissal lives in a module-level set (survives remounts); this tick just- // forces a re-render so the banner leaves immediately.- const [, setBranchMismatchDismissTick] = useState(0);- const activeBranchMismatchKey = branchMismatchKey(- activeThread?.id ?? null,- localCheckoutBranchMismatch,- );- const showBranchMismatchBanner = shouldShowBranchMismatchBanner({- hasMismatch: localCheckoutBranchMismatch !== null,- isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey),- composerHasContent: composerHasUnsentContent,- wasShownForCurrentMismatch:- revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey,- });- useEffect(() => {- setRevealedBranchMismatchKey((revealed) => {- if (showBranchMismatchBanner) {- return activeBranchMismatchKey;- }- // Hysteresis is scoped to an uninterrupted mismatch: reset when the- // mismatch resolves or changes so a recurrence re-gates on intent.- return revealed !== null && revealed !== activeBranchMismatchKey ? null : revealed;- });- }, [activeBranchMismatchKey, showBranchMismatchBanner]);- const handleSwitchCheckoutToThread = useCallback(async () => {- if (- !activeProjectCwd ||- !activeThread ||- !localCheckoutBranchMismatch ||- isRestoringThreadBranch- ) {- return;- }- setIsRestoringThreadBranch(true);- const checkoutResult = await switchGitRef({- environmentId,- input: {- cwd: activeProjectCwd,- refName: localCheckoutBranchMismatch.threadBranch,- },- });- if (checkoutResult._tag === "Failure") {- setIsRestoringThreadBranch(false);- if (!isAtomCommandInterrupted(checkoutResult)) {- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to switch checkout",- description: chatActionErrorMessage(squashAtomCommandFailure(checkoutResult)),- }),- );- }- return;- }-- const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch;- if (nextBranch !== activeThread.branch) {- const updateResult = await updateThreadMetadata({- environmentId,- input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null },- });- if (updateResult._tag === "Failure") {- setIsRestoringThreadBranch(false);- if (!isAtomCommandInterrupted(updateResult)) {- toastManager.add(- stackedThreadToast({- type: "error",- title: "Checkout switched, but the thread could not be updated",- description: chatActionErrorMessage(squashAtomCommandFailure(updateResult)),- }),- );- }- gitStatusQuery.refresh();- return;- }- }- gitStatusQuery.refresh();- setIsRestoringThreadBranch(false);- scheduleComposerFocus();- }, [- activeProjectCwd,- activeThread,- environmentId,- gitStatusQuery,- isRestoringThreadBranch,- localCheckoutBranchMismatch,- scheduleComposerFocus,- switchGitRef,- updateThreadMetadata,- ]);- // Background work (subagent fleets, workflow runs, watch loops) can outlive- // the turn; once it settles, the composer stop button is gone, so this- // banner is the only visible stop affordance. Stop routes through the- // stop-everything interrupt: it kills every live background task before- // interrupting, and works by session, so no active turn is needed.- const activeBackgroundLiveness =- !isWorking && activeThread ? (activeThreadShell?.backgroundLiveness ?? null) : null;- const [isStoppingBackgroundWork, setIsStoppingBackgroundWork] = useState(false);- useEffect(() => {- // "Stopping..." holds until the liveness clears; the interrupt command- // returning only means the request was accepted.- if (activeBackgroundLiveness === null) {- setIsStoppingBackgroundWork(false);- }- }, [activeBackgroundLiveness]);- useEffect(() => {- // Per-thread state: switching threads while A's stop is pending must not- // disable B's Stop button (review finding).- setIsStoppingBackgroundWork(false);- }, [activeThreadId]);- const handleStopBackgroundWork = useCallback(async () => {- if (!activeThread) return;- setIsStoppingBackgroundWork(true);- const result = await interruptThreadTurn({- environmentId,- input: buildThreadTurnInterruptInput(activeThread),- });- if (result._tag === "Failure") {- // Every failure clears the pending state — an interrupted command- // never reached the server, so liveness would hold "Stopping..."- // forever. Only real failures toast.- setIsStoppingBackgroundWork(false);- if (!isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- setThreadError(- activeThread.id,- error instanceof Error ? error.message : "Failed to stop background work.",- );- }- }- }, [activeThread, environmentId, interruptThreadTurn, setThreadError]);- const backgroundLivenessBannerItem = useMemo<ComposerBannerStackItem | null>(() => {- if (activeBackgroundLiveness === null || !activeThread) {- return null;- }- const working = activeBackgroundLiveness === "working";- const liveCount = agentPanelModel.liveCount;- return {- id: `background-liveness:${activeThread.id}`,- variant: "default",- icon: (- <span- className={cn("size-1.5 rounded-full bg-foreground", working && "animate-status-pulse")}- aria-hidden="true"- />- ),- title: working- ? liveCount > 0- ? `${liveCount} ${liveCount === 1 ? "agent" : "agents"} working`- : "Background work"- : "Monitoring",- actions: (- <Button- size="xs"- variant="ghost"- disabled={isStoppingBackgroundWork}- onClick={() => void handleStopBackgroundWork()}- >- {isStoppingBackgroundWork ? "Stopping..." : "Stop"}- </Button>- ),- };- }, [- activeBackgroundLiveness,- activeThread,- agentPanelModel.liveCount,- handleStopBackgroundWork,- isStoppingBackgroundWork,- ]);- // A woken thread announces itself in the open view, not just the sidebar- // pill. Dismissing marks the wake as seen (same acknowledgment as the- // pill); sending a message clears it as a side effect of the send path.- const wokeThreadBannerItem = useMemo<ComposerBannerStackItem | null>(() => {- if (!activeThreadWokeVisible) {- return null;- }- return {- id: `thread-woke:${activeThread?.id ?? "unknown"}`,- variant: "info",- icon: <AlarmClockIcon />,- title: "This thread woke from snooze",- description: "Dismiss to clear the Woke indicator, or send a message to keep going.",- dismissLabel: "Dismiss Woke notification",- onDismiss: acknowledgeActiveThreadWoke,- };- }, [acknowledgeActiveThreadWoke, activeThread?.id, activeThreadWokeVisible]);- // The stack renders items[0] front-most and tucks the rest behind hover, so- // ordering is priority: urgent system banners (error/warning variants plus- // calm-styled live states flagged `urgent`, like update progress), then- // background liveness — its Stop button is the only stop affordance for- // settled turns, so a passive "update available" notice must not cover it —- // then calm system banners, the woke and branch-mismatch notices, and the- // informational parked-thread banner last — it must never cover another.- const parkedThreadBannerItem = useMemo<ComposerBannerStackItem | null>(() => {- if (!activeThreadSnoozed && !activeThreadSettled) {- return null;- }- const isSnoozed = activeThreadSnoozed;- return {- id: `thread-${isSnoozed ? "snoozed" : "settled"}:${activeThread?.id ?? "unknown"}`,- variant: "info",- icon: isSnoozed ? <AlarmClockIcon /> : <CheckCircle2Icon />,- title: `This thread is ${isSnoozed ? "snoozed" : "settled"}`,- description: isSnoozed- ? "Sending a message wakes it and moves it back to Active in the sidebar."- : "Sending a message moves it back to Active in the sidebar.",- actions: (- <Button- size="xs"- variant="outline"- disabled={isSnoozed ? isUnsnoozing : isUnsettling}- onClick={() =>- void (isSnoozed ? handleUnsnoozeActiveThread() : handleUnsettleActiveThread())- }- >- {isSnoozed- ? isUnsnoozing- ? "Waking..."- : "Wake now"- : isUnsettling- ? "Un-settling..."- : "Un-settle"}- </Button>- ),- };- }, [- activeThread?.id,- activeThreadSettled,- activeThreadSnoozed,- handleUnsnoozeActiveThread,- handleUnsettleActiveThread,- isUnsnoozing,- isUnsettling,- ]);- // Session-scoped dismissals, one key per (thread, snapshot). A set rather- // than a single slot so dismissing the banner on one thread does not- // resurface it on another thread dismissed earlier.- const [dismissedResumeCompactionKeys, setDismissedResumeCompactionKeys] = useState<- ReadonlySet<string>- >(new Set());- const resumeCompactionKey =- activeThread && activeContextWindow- ? `${activeThread.id}:${activeContextWindow.updatedAt}`- : null;- const compactDisabled =- !activeThread ||- !activeProject ||- !isServerThread ||- selectedProvider !== "claudeAgent" ||- !compactionProviderAvailable ||- isWorking ||- threadDetailLoading ||- isPreparingWorktree ||- activeEnvironmentUnavailable ||- feedbackUploading ||- pendingApprovals.length > 0 ||- pendingUserInputs.length > 0 ||- showPlanFollowUpPrompt ||- composerHasUnsentContent;- const compactDisabledReason = compactDisabled- ? composerHasUnsentContent- ? "Send or clear your draft before compacting"- : !activeProject- ? "Choose a project before compacting"- : !compactionProviderAvailable- ? "Enable a Claude provider before compacting"- : "Compacting is unavailable right now"- : null;- const resumeCompactionBannerItem = useMemo<ComposerBannerStackItem | null>(() => {- if (- !activeThread ||- !activeContextWindow ||- resumeCompactionKey === null ||- dismissedResumeCompactionKeys.has(resumeCompactionKey) ||- resumeCompactionPermanentlyDismissed ||- nativeResumeCompactionDismissed ||- pendingUserInputs.length > 0 ||- phase === "running" ||- !shouldOfferResumeCompaction({- provider: selectedProvider,- usedTokens: activeContextWindow.usedTokens,- updatedAt: activeContextWindow.updatedAt,- now: `${nowMinute}:00.000Z`,- })- ) {- return null;- }-- const dismiss = () =>- setDismissedResumeCompactionKeys((keys) => new Set(keys).add(resumeCompactionKey));- const compactAction = (- <Button- size="xs"- variant="outline"- disabled={compactDisabled}- onClick={() => {- if (compactDisabled) return;- composerRef.current?.compactContext();- }}- >- Compact- </Button>- );- return {- id: `resume-compaction:${resumeCompactionKey}`,- variant: "info",- icon: <Minimize2Icon />,- title: "Resume with less context",- description: `${formatContextWindowTokens(activeContextWindow.usedTokens)} tokens from an older session`,- actions: compactDisabledReason ? (- <Tooltip>- <TooltipTrigger render={<span className="inline-flex">{compactAction}</span>} />- <TooltipPopup side="top">{compactDisabledReason}</TooltipPopup>- </Tooltip>- ) : (- compactAction- ),- dismissLabel: "Keep full history",- onDismiss: dismiss,- };- }, [- activeContextWindow,- activeThread,- compactDisabled,- compactDisabledReason,- composerRef,- dismissedResumeCompactionKeys,- nativeResumeCompactionDismissed,- nowMinute,- pendingUserInputs.length,- phase,- resumeCompactionKey,- resumeCompactionPermanentlyDismissed,- selectedProvider,- ]);- const handleRestoreThreadBranch = useCallback(() => {- if (gitStatusQuery.data?.hasWorkingTreeChanges) {- setBranchRestoreConfirmOpen(true);- return;- }- void handleSwitchCheckoutToThread();- }, [gitStatusQuery.data?.hasWorkingTreeChanges, handleSwitchCheckoutToThread]);- const composerBannerItems = useMemo<ComposerBannerStackItem[]>(() => {- const isUrgentSystemItem = (item: ComposerBannerStackItem) =>- item.urgent === true || item.variant === "error" || item.variant === "warning";- const urgentSystemItems = systemComposerBannerItems.filter(isUrgentSystemItem);- const calmSystemItems = systemComposerBannerItems.filter((item) => !isUrgentSystemItem(item));- const backgroundLivenessItems =- backgroundLivenessBannerItem === null ? [] : [backgroundLivenessBannerItem];- const resumeCompactionItems =- resumeCompactionBannerItem === null ? [] : [resumeCompactionBannerItem];- const wokeThreadItems = wokeThreadBannerItem === null ? [] : [wokeThreadBannerItem];- const parkedThreadItems = parkedThreadBannerItem === null ? [] : [parkedThreadBannerItem];- if (!localCheckoutBranchMismatch || !showBranchMismatchBanner || !activeBranchMismatchKey) {- return [- ...urgentSystemItems,- ...backgroundLivenessItems,- ...calmSystemItems,- ...resumeCompactionItems,- ...wokeThreadItems,- ...parkedThreadItems,- ];- }- return [- ...urgentSystemItems,- ...backgroundLivenessItems,- ...calmSystemItems,- ...resumeCompactionItems,- ...wokeThreadItems,- {- id: `branch-mismatch:${activeBranchMismatchKey}`,- variant: "info",- icon: <GitBranchIcon />,- title: (- <span className="flex min-w-0 items-baseline gap-1.5">- <span className="shrink-0 font-normal text-muted-foreground">Branch changed — was</span>- <Tooltip>- <TooltipTrigger- render={- <code className="min-w-0 truncate font-medium text-foreground">- {localCheckoutBranchMismatch.threadBranch}- </code>- }- />- <TooltipPopup side="top" className="max-w-80">- This thread last ran on {localCheckoutBranchMismatch.threadBranch}. Sending will- continue on {localCheckoutBranchMismatch.currentBranch}.- </TooltipPopup>- </Tooltip>- </span>- ),- className: "dark:shadow-none",- actions: (- <Button- size="xs"- variant="ghost"- disabled={isRestoringThreadBranch}- onClick={handleRestoreThreadBranch}- >- {isRestoringThreadBranch ? "Restoring..." : "Restore branch"}- </Button>- ),- dismissLabel: "Dismiss branch change notice",- onDismiss: () => {- dismissBranchMismatchForSession(activeBranchMismatchKey);- setBranchMismatchDismissTick((tick) => tick + 1);- },- },- ...parkedThreadItems,- ];- }, [- activeBranchMismatchKey,- backgroundLivenessBannerItem,- handleRestoreThreadBranch,- isRestoringThreadBranch,- localCheckoutBranchMismatch,- parkedThreadBannerItem,- resumeCompactionBannerItem,- showBranchMismatchBanner,- systemComposerBannerItems,- wokeThreadBannerItem,- ]);- useEffect(() => {- setPendingServerThreadEnvMode(null);- setPendingServerThreadBranch(undefined);- }, [activeThread?.id]);-- useEffect(() => {- if (canOverrideServerThreadEnvMode) {- return;- }- setPendingServerThreadEnvMode(null);- setPendingServerThreadBranch(undefined);- }, [canOverrideServerThreadEnvMode]);-- useEffect(() => {- if (!activeThreadId) {- setTerminalUiLaunchContext(null);- return;- }- setTerminalUiLaunchContext((current) => {- if (!current) return current;- if (current.threadId === activeThreadId) return current;- return null;- });- }, [activeThreadId]);-- useEffect(() => {- if (!activeThreadId || !activeProjectCwd) {- return;- }- setTerminalUiLaunchContext((current) => {- if (!current || current.threadId !== activeThreadId) {- return current;- }- const settledCwd = projectScriptCwd({- project: { cwd: activeProjectCwd },- worktreePath: activeThreadWorktreePath,- });- if (- settledCwd === current.cwd &&- (activeThreadWorktreePath ?? null) === current.worktreePath- ) {- return null;- }- return current;- });- }, [activeProjectCwd, activeThreadId, activeThreadWorktreePath]);-- useEffect(() => {- if (terminalUiState.terminalOpen) {- return;- }- setTerminalUiLaunchContext((current) =>- current?.threadId === activeThreadId ? null : current,- );- }, [activeThreadId, terminalUiState.terminalOpen]);-- useEffect(() => {- if (!activeThreadKey) return;- const previous = terminalUiOpenByThreadRef.current[activeThreadKey] ?? false;- const current = Boolean(terminalUiState.terminalOpen);-- if (!previous && current) {- terminalUiOpenByThreadRef.current[activeThreadKey] = current;- setTerminalFocusRequestId((value) => value + 1);- return;- } else if (previous && !current) {- terminalUiOpenByThreadRef.current[activeThreadKey] = current;- const frame = window.requestAnimationFrame(() => {- focusComposer();- });- return () => {- window.cancelAnimationFrame(frame);- };- }-- terminalUiOpenByThreadRef.current[activeThreadKey] = current;- }, [activeThreadKey, focusComposer, terminalUiState.terminalOpen]);-- useEffect(() => {- const handler = (event: globalThis.KeyboardEvent) => {- if (preventRepeatedTerminalCloseShortcut(event, keybindings)) {- event.stopPropagation();- return;- }- // While a close confirmation is open, terminal focus has moved to the- // dialog, so a deliberate second close shortcut would otherwise fall- // through to the native window/tab close accelerator.- if (isTerminalCloseConfirmPending() && preventTerminalCloseShortcut(event, keybindings)) {- event.stopPropagation();- return;- }- if (!activeThreadId || isCommandPaletteOpen()) {- return;- }- const terminalFocusOwner = getTerminalFocusOwner();- if (event.defaultPrevented && terminalFocusOwner === null) {- return;- }- const shortcutContext = {- terminalFocus: terminalFocusOwner !== null,- terminalOpen: Boolean(terminalUiState.terminalOpen),- modelPickerOpen: composerRef.current?.isModelPickerOpen() ?? false,- };-- if (- !shortcutContext.terminalFocus &&- !shortcutContext.modelPickerOpen &&- shouldTypeToFocusComposer(event)- ) {- if (composerRef.current?.insertTextAtEnd(event.key)) {- event.preventDefault();- event.stopPropagation();- return;- }- }-- const command = resolveShortcutCommand(event, keybindings, {- context: shortcutContext,- });- if (!command) return;-- if (command === "thread.settle") {- event.preventDefault();- event.stopPropagation();- if (!isServerThread || !activeThreadRef || !supportsSettlement) return;- if (activeThreadSettled) {- void handleUnsettleActiveThread();- return;- }-- void settleThread(activeThreadRef).then((result) => {- if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return;- const error = squashAtomCommandFailure(result);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to settle thread",- description: error instanceof Error ? error.message : "An error occurred.",- }),- );- });- return;- }-- if (command === "terminal.toggle") {- event.preventDefault();- event.stopPropagation();- toggleTerminalVisibility();- return;- }-- if (command === "rightPanel.toggle") {- event.preventDefault();- event.stopPropagation();- toggleRightPanel();- return;- }-- if (command === "rightPanel.toggleMaximized") {- event.preventDefault();- event.stopPropagation();- toggleRightPanelMaximized();- return;- }-- if (command === "terminal.split") {- event.preventDefault();- event.stopPropagation();- if (terminalFocusOwner === "right-panel") {- splitPanelTerminal();- return;- }- if (!terminalUiState.terminalOpen) {- setTerminalOpen(true);- }- splitTerminal();- return;- }-- if (command === "terminal.splitVertical") {- event.preventDefault();- event.stopPropagation();- if (terminalFocusOwner === "right-panel") {- splitPanelTerminal("vertical");- return;- }- if (!terminalUiState.terminalOpen) {- setTerminalOpen(true);- }- splitTerminal("vertical");- return;- }-- if (command === "terminal.close") {- event.preventDefault();- event.stopPropagation();- if (terminalFocusOwner === "right-panel" && activeRightPanelSurface?.kind === "terminal") {- requestClosePanelTerminal(activeRightPanelSurface.activeTerminalId);- return;- }- if (!terminalUiState.terminalOpen) return;- requestCloseTerminal(terminalUiState.activeTerminalId);- return;- }-- if (command === "terminal.new") {- event.preventDefault();- event.stopPropagation();- if (terminalFocusOwner === "right-panel") {- addTerminalSurface();- return;- }- if (!terminalUiState.terminalOpen) {- setTerminalOpen(true);- }- createNewTerminal();- return;- }-- if (command === "diff.toggle") {- event.preventDefault();- event.stopPropagation();- onToggleDiff();- return;- }-- if (command === "modelPicker.toggle") {- event.preventDefault();- event.stopPropagation();- composerRef.current?.toggleModelPicker();- return;- }-- const scriptId = projectScriptIdFromCommand(command);- if (!scriptId || !activeProject) return;- const script = activeProject.scripts.find((entry) => entry.id === scriptId);- if (!script) return;- event.preventDefault();- event.stopPropagation();- void runProjectScript(script);- };- window.addEventListener("keydown", handler, true);- return () => window.removeEventListener("keydown", handler, true);- }, [- activeProject,- activeRightPanelSurface,- addTerminalSurface,- activeThreadRef,- activeThreadSettled,- terminalUiState.terminalOpen,- terminalUiState.activeTerminalId,- activeThreadId,- requestCloseTerminal,- requestClosePanelTerminal,- createNewTerminal,- setTerminalOpen,- runProjectScript,- splitTerminal,- splitPanelTerminal,- keybindings,- handleUnsettleActiveThread,- isServerThread,- onToggleDiff,- settleThread,- supportsSettlement,- toggleRightPanel,- toggleRightPanelMaximized,- toggleTerminalVisibility,- composerRef,- ]);-- const onRevertToTurnCount = useCallback(- async (turnCount: number) => {- const localApi = readLocalApi();- if (!localApi || !activeThread || isRevertingCheckpoint) return;-- if (activeEnvironmentUnavailable && activeEnvironmentUnavailableLabel) {- setThreadError(- activeThread.id,- `Reconnect ${activeEnvironmentUnavailableLabel} before reverting checkpoints.`,- );- return;- }- if (phase === "running" || isSendBusy || isConnecting) {- setThreadError(activeThread.id, "Interrupt the current turn before reverting checkpoints.");- return;- }- const confirmed = await localApi.dialogs.confirm(- [- `Revert this thread to checkpoint ${turnCount}?`,- "This will discard newer messages and turn diffs in this thread.",- "This action cannot be undone.",- ].join("\n"),- { variant: "destructive" },- );- if (!confirmed) {- return;- }-- setIsRevertingCheckpoint(true);- setThreadError(activeThread.id, null);- const result = await revertThreadCheckpoint({- environmentId,- input: {- threadId: activeThread.id,- turnCount,- },- });- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- setThreadError(- activeThread.id,- error instanceof Error ? error.message : "Failed to revert thread state.",- );- }- setIsRevertingCheckpoint(false);- },- [- activeThread,- activeEnvironmentUnavailable,- activeEnvironmentUnavailableLabel,- environmentId,- isConnecting,- isRevertingCheckpoint,- isSendBusy,- phase,- revertThreadCheckpoint,- setThreadError,- ],- );-- const onSend = async (- e?: { preventDefault: () => void },- submissionIntent: ComposerSubmissionIntent = "foreground",- directAnnotation?: {- annotation: PreviewAnnotationPayload;- image: ComposerImageAttachment | null;- },- ) => {- e?.preventDefault();- const notifyDirectAnnotationAttached = () => {- if (!directAnnotation) return;- toastManager.add(- stackedThreadToast({- type: "info",- title: "Annotation attached to draft",- description: "Sending is unavailable right now. Finish the current action, then send.",- }),- );- };- if (- !activeThread ||- isSendBusy ||- isConnecting ||- threadDetailLoading ||- sendInFlightRef.current ||- feedbackUploadsInFlightRef.current.has(routeThreadKey)- ) {- notifyDirectAnnotationAttached();- return;- }- if (activeEnvironmentUnavailable) {- toastManager.add(- stackedThreadToast({- type: "warning",- title: "Not connected: message not sent",- description: "Reconnecting to the environment. Try again once it is connected.",- }),- );- return;- }- if (activePendingProgress) {- if (directAnnotation) {- notifyDirectAnnotationAttached();- return;- }- onAdvanceActivePendingUserInput();- return;- }- const sendCtx = composerRef.current?.getSendContext();- if (!sendCtx?.providerAvailable) {- notifyDirectAnnotationAttached();- return;- }- const {- images: sendContextImages,- terminalContexts: composerTerminalContexts,- elementContexts: composerElementContexts,- previewAnnotations: sendContextPreviewAnnotations,- reviewComments: composerReviewComments,- selectedProvider: ctxSelectedProvider,- selectedModel: ctxSelectedModel,- selectedProviderModels: ctxSelectedProviderModels,- selectedPromptEffort: ctxSelectedPromptEffort,- selectedModelSelection: ctxSelectedModelSelection,- } = sendCtx;- const composerImages =- directAnnotation?.image &&- !sendContextImages.some((image) => image.id === directAnnotation.image?.id)- ? [...sendContextImages, directAnnotation.image]- : sendContextImages;- const composerPreviewAnnotations =- directAnnotation &&- !sendContextPreviewAnnotations.some(- (annotation) => annotation.id === directAnnotation.annotation.id,- )- ? [- ...sendContextPreviewAnnotations,- {- ...directAnnotation.annotation,- screenshot: directAnnotation.annotation.screenshot- ? { ...directAnnotation.annotation.screenshot, dataUrl: "" }- : null,- },- ]- : sendContextPreviewAnnotations;- const promptForSend = promptRef.current;- const {- trimmedPrompt: trimmed,- sendableTerminalContexts: sendableComposerTerminalContexts,- expiredTerminalContextCount,- hasSendableContent,- } = deriveComposerSendState({- prompt: promptForSend,- imageCount: composerImages.length,- terminalContexts: composerTerminalContexts,- elementContextCount:- composerElementContexts.length +- composerPreviewAnnotations.length +- composerReviewComments.length,- });- const feedbackCommand =- ctxSelectedProvider === "codex" &&- composerImages.length === 0 &&- sendableComposerTerminalContexts.length === 0 &&- composerElementContexts.length === 0 &&- composerPreviewAnnotations.length === 0 &&- composerReviewComments.length === 0- ? parseCodexFeedbackCommand(trimmed)- : null;- if (feedbackCommand) {- if (!isServerThread || activeThread.session === null) {- toastManager.add(- stackedThreadToast({- type: "warning",- title: "Start a Codex thread first",- description: "Send a message before you submit feedback.",- }),- );- return;- }- feedbackUploadsInFlightRef.current.add(routeThreadKey);- const result = await submitCodexFeedback({- submission: {- id: newMessageId(),- command: trimmed,- createdAt: new Date().toISOString(),- },- clearDraft: () => {- promptRef.current = "";- clearComposerDraftContent(composerDraftTarget);- composerRef.current?.resetCursorState();- scrollToEnd();- },- onUpdate: (submission) => {- setFeedbackSubmissionsByThreadKey((current) => {- const existing = current[routeThreadKey] ?? [];- const found = existing.some((entry) => entry.id === submission.id);- return {- ...current,- [routeThreadKey]: found- ? existing.map((entry) => (entry.id === submission.id ? submission : entry))- : [...existing, submission],- };- });- },- upload: () =>- uploadThreadFeedback({- environmentId,- input: {- threadId: activeThread.id,- ...feedbackCommand,- },- }),- }).finally(() => {- feedbackUploadsInFlightRef.current.delete(routeThreadKey);- });- if (result._tag === "Failure") {- if (!isAtomCommandInterrupted(result)) {- toastManager.add(- stackedThreadToast({- type: "error",- title: "Could not send feedback to OpenAI",- description: chatActionErrorMessage(squashAtomCommandFailure(result)),- }),- );- }- return;- }- const feedbackId = result.value.feedbackId;- toastManager.add(- stackedThreadToast({- type: "success",- title: "Feedback sent to OpenAI",- description: `Thread ID: ${feedbackId}`,- timeout: 0,- actionProps: {- children: "Copy ID",- onClick: () => {- void writeTextToClipboard(feedbackId, "Codex feedback thread ID").catch(- (error: unknown) => {- toastManager.add(- stackedThreadToast({- type: "error",- title: "Could not copy thread ID",- description: chatActionErrorMessage(error),- }),- );- },- );- },- },- }),- );- return;- }- if (!directAnnotation && showPlanFollowUpPrompt && activeProposedPlan) {- const followUp = resolvePlanFollowUpSubmission({- draftText: trimmed,- planMarkdown: activeProposedPlan.planMarkdown,- });- const outgoingFollowUpText = formatOutgoingPrompt({- provider: ctxSelectedProvider,- model: ctxSelectedModel,- models: ctxSelectedProviderModels,- effort: ctxSelectedPromptEffort,- text: followUp.text.trim(),- });- if (composerRef.current?.validateProviderInput(outgoingFollowUpText) === false) {- return;- }- promptRef.current = "";- clearComposerDraftContent(composerDraftTarget);- composerRef.current?.resetCursorState();- await onSubmitPlanFollowUp({- text: followUp.text,- interactionMode: followUp.interactionMode,- });- return;- }- // Legacy plan mode: /plan and /default only act when the beta flag is on;- // otherwise they send as plain text like any other message.- const standaloneSlashCommand =- settings.planModeEnabled &&- composerImages.length === 0 &&- sendableComposerTerminalContexts.length === 0 &&- composerElementContexts.length === 0 &&- composerPreviewAnnotations.length === 0 &&- composerReviewComments.length === 0- ? parseStandaloneComposerSlashCommand(trimmed)- : null;- if (standaloneSlashCommand) {- handleInteractionModeChange(standaloneSlashCommand);- promptRef.current = "";- clearComposerDraftContent(composerDraftTarget);- composerRef.current?.resetCursorState();- return;- }- if (!hasSendableContent) {- if (expiredTerminalContextCount > 0) {- const toastCopy = buildExpiredTerminalContextToastCopy(- expiredTerminalContextCount,- "empty",- );- toastManager.add(- stackedThreadToast({- type: "warning",- title: toastCopy.title,- description: toastCopy.description,- }),- );- }- return;- }- if (!activeProject) {- toastManager.add(- stackedThreadToast({- type: "warning",- title: "Choose a project first",- description: "This draft no longer points to an available project.",- }),- );- return;- }- const threadIdForSend = activeThread.id;- const isFirstMessage = !isServerThread || activeThread.messages.length === 0;- const baseBranchForWorktree =- isFirstMessage && sendEnvMode === "worktree" && !activeThread.worktreePath- ? activeThreadBranch- : null;-- // In worktree mode, require an explicit base branch so we don't silently- // fall back to local execution when branch selection is missing.- const shouldCreateWorktree =- isFirstMessage && sendEnvMode === "worktree" && !activeThread.worktreePath;- if (shouldCreateWorktree && !activeThreadBranch) {- setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode.");- return;- }-- const composerImagesSnapshot = [...composerImages];- const composerTerminalContextsSnapshot = [...sendableComposerTerminalContexts];- const composerElementContextsSnapshot = [...composerElementContexts];- const composerPreviewAnnotationsSnapshot = [...composerPreviewAnnotations];- const composerReviewCommentsSnapshot: ReviewCommentContext[] = [...composerReviewComments];- const messageTextWithContexts = appendElementContextsToPrompt(- appendTerminalContextsToPrompt(promptForSend, composerTerminalContextsSnapshot),- composerElementContextsSnapshot,- );- const messageTextWithPreviewAnnotations = composerPreviewAnnotationsSnapshot.reduce(- (text, annotation) => appendPreviewAnnotationPrompt(text, annotation),- messageTextWithContexts,- );- const messageTextForSend = appendReviewCommentsToPrompt(- messageTextWithPreviewAnnotations,- composerReviewCommentsSnapshot,- );- const outgoingMessageText = formatOutgoingPrompt({- provider: ctxSelectedProvider,- model: ctxSelectedModel,- models: ctxSelectedProviderModels,- effort: ctxSelectedPromptEffort,- text: messageTextForSend || IMAGE_ONLY_BOOTSTRAP_PROMPT,- });- if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) {- return;- }-- sendInFlightRef.current = true;- if (supportsAttachmentUploads && composerImagesSnapshot.length > 0) {- for (const image of composerImagesSnapshot) {- startAttachmentUpload({ environmentId, image });- }- await awaitAttachmentUploads(composerImagesSnapshot.map((image) => image.id));- if (getUploadedAttachments({ environmentId, images: composerImagesSnapshot }) === null) {- sendInFlightRef.current = false;- setThreadError(threadIdForSend, "Retry or remove failed image uploads before sending.");- return;- }- }-- const resolvedSubmissionIntent =- submissionIntent === "background" && isLocalDraftThread ? "background" : "foreground";- if (- shouldDockDraftHeroForSubmission({- isDraftHeroState,- activeThreadKey,- submissionIntent: resolvedSubmissionIntent,- }) &&- activeThreadKey- ) {- let resolveDockStarted: (() => void) | undefined;- const dockStarted = new Promise<void>((resolve) => {- resolveDockStarted = resolve;- });- const dockTransition = runMobileComposerTransition(() => {- flushSync(() => {- captureDraftHeroComposerRect();- setDockedDraftHeroThreadKey(activeThreadKey);- });- resolveDockStarted?.();- });- void dockTransition.catch(() => resolveDockStarted?.());- await dockStarted;- }- beginLocalDispatch({- preparingWorktree: Boolean(baseBranchForWorktree),- submissionIntent: resolvedSubmissionIntent,- });-- const messageIdForSend = newMessageId();- const messageCreatedAt = new Date().toISOString();- const turnAttachmentsPromise = Promise.all(- composerImagesSnapshot.map(async (image) => {- if (supportsAttachmentUploads) {- const uploaded = getUploadedAttachments({ environmentId, images: [image] })?.[0];- if (!uploaded) {- throw new Error(`Image '${image.name}' did not finish uploading.`);- }- return uploaded;- }- return {- type: "image" as const,- name: image.name,- mimeType: image.mimeType,- sizeBytes: image.sizeBytes,- dataUrl: await readFileAsDataUrl(image.file),- };- }),- );- const optimisticAttachments = composerImagesSnapshot.map((image) => ({- type: "image" as const,- id: image.id,- name: image.name,- mimeType: image.mimeType,- sizeBytes: image.sizeBytes,- previewUrl: image.previewUrl,- }));- const shouldAnchorFirstMessage =- activeThread.latestTurn === null &&- !timelineMessages.some((message) => message.role === "user");- if (shouldAnchorFirstMessage) {- isAtEndRef.current = true;- timelineScrollModeRef.current = "anchoring-new-turn";- liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current;- setTimelineLiveFollowEnabled(true);- pendingTimelineAnchorRef.current = messageIdForSend;- activeTimelineAnchorIndexRef.current = null;- showScrollDebouncer.current.cancel();- setShowScrollToBottom(false);- setTimelineAnchor({- threadKey: scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),- messageId: messageIdForSend,- });- } else {- scrollToEnd();- }- setOptimisticUserMessages((existing) => [- ...existing,- {- id: messageIdForSend,- role: "user",- text: outgoingMessageText,- ...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),- turnId: null,- createdAt: messageCreatedAt,- updatedAt: messageCreatedAt,- streaming: false,- },- ]);- setThreadError(threadIdForSend, null);- if (expiredTerminalContextCount > 0) {- const toastCopy = buildExpiredTerminalContextToastCopy(- expiredTerminalContextCount,- "omitted",- );- toastManager.add(- stackedThreadToast({- type: "warning",- title: toastCopy.title,- description: toastCopy.description,- }),- );- }- promptRef.current = "";- clearComposerDraftContent(composerDraftTarget);- composerRef.current?.resetCursorState();-- let firstComposerImageName: string | null = null;- if (composerImagesSnapshot.length > 0) {- const firstComposerImage = composerImagesSnapshot[0];- if (firstComposerImage) {- firstComposerImageName = firstComposerImage.name;- }- }- let titleSeed = trimmed;- if (!titleSeed) {- if (firstComposerImageName) {- titleSeed = `Image: ${firstComposerImageName}`;- } else if (composerTerminalContextsSnapshot.length > 0) {- titleSeed = formatTerminalContextLabel(composerTerminalContextsSnapshot[0]!);- } else if (composerElementContextsSnapshot.length > 0) {- titleSeed = formatElementContextLabel(composerElementContextsSnapshot[0]!);- } else {- titleSeed = "New thread";- }- }- const title = truncate(titleSeed);- const threadCreateModelSelection = createModelSelection(- ctxSelectedModelSelection.instanceId,- ctxSelectedModel || activeProject.defaultModelSelection?.model || DEFAULT_MODEL,- ctxSelectedModelSelection.options,- );-- let failure: AtomCommandResult<unknown, unknown> | null = null;- // Auto-title from first message- if (isFirstMessage && isServerThread) {- const titleResult = await updateThreadMetadata({- environmentId,- input: {- threadId: threadIdForSend,- title,- },- });- if (titleResult._tag === "Failure") {- failure = titleResult;- }- }-- if (failure === null && isServerThread) {- const settingsResult = await persistThreadSettingsForNextTurn({- threadId: threadIdForSend,- createdAt: messageCreatedAt,- ...(ctxSelectedModel ? { modelSelection: ctxSelectedModelSelection } : {}),- ...(localCheckoutBranchMismatch- ? { branch: localCheckoutBranchMismatch.currentBranch }- : {}),- runtimeMode,- interactionMode,- });- if (settingsResult._tag === "Failure") {- failure = settingsResult;- }- }-- const turnAttachmentsResult = await settlePromise(() => turnAttachmentsPromise);- if (failure === null && turnAttachmentsResult._tag === "Failure") {- failure = turnAttachmentsResult;- }-- let turnStartSucceeded = false;- if (failure === null && turnAttachmentsResult._tag === "Success") {- const bootstrap =- isLocalDraftThread || baseBranchForWorktree- ? {- ...(isLocalDraftThread- ? {- createThread: {- projectId: activeProject.id,- title,- modelSelection: threadCreateModelSelection,- runtimeMode,- interactionMode,- branch: activeThreadBranch,- worktreePath: activeThread.worktreePath,- createdAt: activeThread.createdAt,- },- }- : {}),- ...(baseBranchForWorktree- ? {- prepareWorktree: {- projectCwd: activeProject.workspaceRoot,- baseBranch: baseBranchForWorktree,- branch: buildTemporaryWorktreeBranchName(randomHex),- ...(startFromOrigin ? { startFromOrigin: true } : {}),- },- runSetupScript: true,- }- : {}),- }- : undefined;- beginLocalDispatch({ preparingWorktree: false });- const backgroundThreadRef =- resolvedSubmissionIntent === "background"- ? scopeThreadRef(activeThread.environmentId, threadIdForSend)- : null;- if (backgroundThreadRef) {- beginBackgroundDraftSubmissionByRef(backgroundThreadRef);- }- const startResult = await startThreadTurn({- environmentId,- input: {- threadId: threadIdForSend,- message: {- messageId: messageIdForSend,- role: "user",- text: outgoingMessageText,- attachments: turnAttachmentsResult.value,- },- modelSelection: ctxSelectedModelSelection,- titleSeed: title,- runtimeMode,- interactionMode,- ...(bootstrap ? { bootstrap } : {}),- createdAt: messageCreatedAt,- },- });- if (startResult._tag === "Failure") {- if (backgroundThreadRef) {- clearBackgroundDraftSubmissionByRef(backgroundThreadRef);- }- failure = startResult;- } else {- turnStartSucceeded = true;- if (supportsAttachmentUploads) {- releaseAttachmentUploads(composerImagesSnapshot);- }- acknowledgeActiveThreadWoke();- if (backgroundThreadRef) {- markPromotedDraftThreadByRef(backgroundThreadRef);- try {- const nextDraft = await handleNewThread(- scopeProjectRef(activeProject.environmentId, activeProject.id),- resolveBackgroundDraftWorkspaceOptions({- envMode: sendEnvMode,- branch: activeThreadBranch,- startFromOrigin,- }),- );- if (nextDraft) {- finalizePromotedDraftThreadByRef(backgroundThreadRef);- toastManager.add(- stackedThreadToast({- type: "success",- title: "Started in background",- timeout: 5_000,- actionProps: {- children: "Open",- onClick: () => {- void navigate({- to: "/$environmentId/$threadId",- params: buildThreadRouteParams(backgroundThreadRef),- });- },- },- }),- );- } else {- clearBackgroundDraftSubmissionByRef(backgroundThreadRef);- }- } catch (error) {- clearBackgroundDraftSubmissionByRef(backgroundThreadRef);- resetLocalDispatch();- toastManager.add(- stackedThreadToast({- type: "warning",- title: "Task started in the background",- description:- error instanceof Error- ? `Could not open a fresh composer: ${error.message}`- : "Could not open a fresh composer.",- }),- );- }- }- }- }-- if (failure !== null) {- if (- promptRef.current.length === 0 &&- composerImagesRef.current.length === 0 &&- composerTerminalContextsRef.current.length === 0 &&- composerElementContextsRef.current.length === 0 &&- (useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.previewAnnotations- .length ?? 0) === 0 &&- (useComposerDraftStore.getState().getComposerDraft(composerDraftTarget)?.reviewComments- .length ?? 0) === 0- ) {- setOptimisticUserMessages((existing) => {- const removed = existing.filter((message) => message.id === messageIdForSend);- for (const message of removed) {- revokeUserMessagePreviewUrls(message);- }- const next = existing.filter((message) => message.id !== messageIdForSend);- return next.length === existing.length ? existing : next;- });- promptRef.current = promptForSend;- const retryComposerImages = composerImagesSnapshot.map(cloneComposerImageForRetry);- composerImagesRef.current = retryComposerImages;- composerTerminalContextsRef.current = composerTerminalContextsSnapshot;- composerElementContextsRef.current = composerElementContextsSnapshot;- setComposerDraftPrompt(composerDraftTarget, promptForSend);- addComposerDraftImages(composerDraftTarget, retryComposerImages);- setComposerDraftTerminalContexts(composerDraftTarget, composerTerminalContextsSnapshot);- setComposerDraftElementContexts(composerDraftTarget, composerElementContextsSnapshot);- setComposerDraftPreviewAnnotations(composerDraftTarget, composerPreviewAnnotationsSnapshot);- setComposerDraftReviewComments(composerDraftTarget, composerReviewCommentsSnapshot);- composerRef.current?.resetCursorState({- cursor: collapseExpandedComposerCursor(promptForSend, promptForSend.length),- prompt: promptForSend,- detectTrigger: true,- });- }- if (!isAtomCommandInterrupted(failure)) {- const error = squashAtomCommandFailure(failure);- if (isLocalDraftThread && draftId && wasBootstrapThreadDeleted(error)) {- const failedDraftSession = getDraftSession(draftId);- if (failedDraftSession?.threadId === threadIdForSend) {- setLogicalProjectDraftThreadId(- failedDraftSession.logicalProjectKey,- scopeProjectRef(failedDraftSession.environmentId, failedDraftSession.projectId),- draftId,- {- threadId: newThreadId(),- createdAt: new Date().toISOString(),- },- );- }- }- setThreadError(- threadIdForSend,- error instanceof Error ? error.message : "Failed to send message.",- );- }- }- sendInFlightRef.current = false;- if (!turnStartSucceeded) {- setDockedDraftHeroThreadKey((currentThreadKey) =>- currentThreadKey === activeThreadKey ? null : currentThreadKey,- );- resetLocalDispatch();- }- };-- const onInterrupt = async () => {- if (!activeThread) return;- const result = await interruptThreadTurn({- environmentId,- input: buildThreadTurnInterruptInput(activeThread),- });- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- setThreadError(- activeThread.id,- error instanceof Error ? error.message : "Failed to interrupt the current turn.",- );- }- };-- const onRespondToApproval = useCallback(- async (requestId: ApprovalRequestId, decision: ProviderApprovalDecision) => {- if (!activeThreadId) return;-- setRespondingRequestIds((existing) =>- existing.includes(requestId) ? existing : [...existing, requestId],- );- const result = await respondToThreadApproval({- environmentId,- input: {- threadId: activeThreadId,- requestId,- decision,- },- });- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- setThreadError(- activeThreadId,- error instanceof Error ? error.message : "Failed to submit approval decision.",- );- }- setRespondingRequestIds((existing) => existing.filter((id) => id !== requestId));- return result;- },- [activeThreadId, environmentId, respondToThreadApproval, setThreadError],- );-- const onRespondToUserInput = useCallback(- async (requestId: ApprovalRequestId, answers: Record<string, unknown>) => {- if (!activeThreadId) return;-- setRespondingUserInputRequestIds((existing) =>- existing.includes(requestId) ? existing : [...existing, requestId],- );- const result = await respondToThreadUserInput({- environmentId,- input: {- threadId: activeThreadId,- requestId,- answers,- },- });- if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {- const error = squashAtomCommandFailure(result);- setThreadError(- activeThreadId,- error instanceof Error ? error.message : "Failed to submit user input.",- );- }- setRespondingUserInputRequestIds((existing) => existing.filter((id) => id !== requestId));- return result;- },- [activeThreadId, environmentId, respondToThreadUserInput, setThreadError],- );-- const setActivePendingUserInputQuestionIndex = useCallback(- (nextQuestionIndex: number) => {- if (!activePendingUserInput) {- return;- }- setPendingUserInputQuestionIndexByRequestId((existing) => ({- ...existing,- [activePendingUserInput.requestId]: nextQuestionIndex,- }));- },- [activePendingUserInput],- );-- const onSelectActivePendingUserInputOption = useCallback(- (questionId: string, optionLabel: string) => {- if (!activePendingUserInput) {- return;- }- setPendingUserInputAnswersByRequestId((existing) => {- const question =- (activePendingProgress?.activeQuestion?.id === questionId- ? activePendingProgress.activeQuestion- : undefined) ??- activePendingUserInput.questions.find((entry) => entry.id === questionId);- if (!question) {- return existing;- }-- return {- ...existing,- [activePendingUserInput.requestId]: {- ...existing[activePendingUserInput.requestId],- [questionId]: togglePendingUserInputOptionSelection(- question,- existing[activePendingUserInput.requestId]?.[questionId],- optionLabel,- ),- },- };- });- promptRef.current = "";- composerRef.current?.resetCursorState({ cursor: 0 });- },- [activePendingProgress?.activeQuestion, activePendingUserInput, composerRef],- );-- const onChangeActivePendingUserInputCustomAnswer = useCallback(- (- questionId: string,- value: string,- nextCursor: number,- expandedCursor: number,- _cursorAdjacentToMention: boolean,- ) => {- if (!activePendingUserInput) {- return;- }- promptRef.current = value;- setPendingUserInputAnswersByRequestId((existing) => ({- ...existing,- [activePendingUserInput.requestId]: {- ...existing[activePendingUserInput.requestId],- [questionId]: setPendingUserInputCustomAnswer(- existing[activePendingUserInput.requestId]?.[questionId],- value,- ),- },- }));- const snapshot = composerRef.current?.readSnapshot();- if (- snapshot?.value !== value ||- snapshot.cursor !== nextCursor ||- snapshot.expandedCursor !== expandedCursor- ) {- composerRef.current?.focusAt(nextCursor);- }- },- [activePendingUserInput, composerRef],- );-- const onAdvanceActivePendingUserInput = useCallback(() => {- if (!activePendingUserInput || !activePendingProgress) {- return;- }- if (activePendingProgress.isLastQuestion) {- if (activePendingResolvedAnswers) {- void onRespondToUserInput(activePendingUserInput.requestId, activePendingResolvedAnswers);- }- return;- }- setActivePendingUserInputQuestionIndex(activePendingProgress.questionIndex + 1);- }, [- activePendingProgress,- activePendingResolvedAnswers,- activePendingUserInput,- onRespondToUserInput,- setActivePendingUserInputQuestionIndex,- ]);-- const onPreviousActivePendingUserInputQuestion = useCallback(() => {- if (!activePendingProgress) {- return;- }- setActivePendingUserInputQuestionIndex(Math.max(activePendingProgress.questionIndex - 1, 0));- }, [activePendingProgress, setActivePendingUserInputQuestionIndex]);-- const onSubmitPlanFollowUp = useCallback(- async ({- text,- interactionMode: nextInteractionMode,- }: {- text: string;- interactionMode: "default" | "plan";- }) => {- if (- !activeThread ||- !isServerThread ||- isSendBusy ||- isConnecting ||- sendInFlightRef.current- ) {- return;- }-- const trimmed = text.trim();- if (!trimmed) {- return;- }-- const sendCtx = composerRef.current?.getSendContext();- if (!sendCtx?.providerAvailable) {- return;- }- const {- selectedProvider: ctxSelectedProvider,- selectedModel: ctxSelectedModel,- selectedProviderModels: ctxSelectedProviderModels,- selectedPromptEffort: ctxSelectedPromptEffort,- selectedModelSelection: ctxSelectedModelSelection,- } = sendCtx;-- const threadIdForSend = activeThread.id;- const messageIdForSend = newMessageId();- const messageCreatedAt = new Date().toISOString();- const outgoingMessageText = formatOutgoingPrompt({- provider: ctxSelectedProvider,- model: ctxSelectedModel,- models: ctxSelectedProviderModels,- effort: ctxSelectedPromptEffort,- text: trimmed,- });-- sendInFlightRef.current = true;- beginLocalDispatch({ preparingWorktree: false });- setThreadError(threadIdForSend, null);-- scrollToEnd();-- setOptimisticUserMessages((existing) => [- ...existing,- {- id: messageIdForSend,- role: "user",- text: outgoingMessageText,- turnId: null,- createdAt: messageCreatedAt,- updatedAt: messageCreatedAt,- streaming: false,- },- ]);-- const settingsResult = await persistThreadSettingsForNextTurn({- threadId: threadIdForSend,- createdAt: messageCreatedAt,- modelSelection: ctxSelectedModelSelection,- ...(localCheckoutBranchMismatch- ? { branch: localCheckoutBranchMismatch.currentBranch }- : {}),- runtimeMode,- interactionMode: nextInteractionMode,- });- let failure: AtomCommandResult<unknown, unknown> | null =- settingsResult._tag === "Failure" ? settingsResult : null;-- if (failure === null) {- // Keep the mode toggle and plan-follow-up banner in sync immediately- // while the same-thread implementation turn is starting.- setComposerDraftInteractionMode(- scopeThreadRef(activeThread.environmentId, threadIdForSend),- nextInteractionMode,- );-- const startResult = await startThreadTurn({- environmentId,- input: {- threadId: threadIdForSend,- message: {- messageId: messageIdForSend,- role: "user",- text: outgoingMessageText,- attachments: [],- },- modelSelection: ctxSelectedModelSelection,- titleSeed: activeThread.title,- runtimeMode,- interactionMode: nextInteractionMode,- ...(nextInteractionMode === "default" && activeProposedPlan- ? {- sourceProposedPlan: {- threadId: activeThread.id,- planId: activeProposedPlan.id,- },- }- : {}),- createdAt: messageCreatedAt,- },- });- failure = startResult._tag === "Failure" ? startResult : null;- }-- if (failure === null) {- acknowledgeActiveThreadWoke();- sendInFlightRef.current = false;- return;- }-- setOptimisticUserMessages((existing) =>- existing.filter((message) => message.id !== messageIdForSend),- );- if (!isAtomCommandInterrupted(failure)) {- const error = squashAtomCommandFailure(failure);- setThreadError(- threadIdForSend,- error instanceof Error ? error.message : "Failed to send plan follow-up.",- );- }- sendInFlightRef.current = false;- resetLocalDispatch();- },- [- activeThread,- activeProposedPlan,- acknowledgeActiveThreadWoke,- beginLocalDispatch,- isConnecting,- isSendBusy,- isServerThread,- localCheckoutBranchMismatch,- persistThreadSettingsForNextTurn,- resetLocalDispatch,- runtimeMode,- scrollToEnd,- setComposerDraftInteractionMode,- setThreadError,- startThreadTurn,- environmentId,- composerRef,- ],- );-- const onImplementPlanInNewThread = useCallback(async () => {- if (- !activeThread ||- !activeProject ||- !activeProposedPlan ||- !isServerThread ||- isSendBusy ||- isConnecting ||- activeEnvironmentUnavailable ||- sendInFlightRef.current- ) {- return;- }-- const sendCtx = composerRef.current?.getSendContext();- if (!sendCtx?.providerAvailable) {- return;- }- const {- selectedProvider: ctxSelectedProvider,- selectedModel: ctxSelectedModel,- selectedProviderModels: ctxSelectedProviderModels,- selectedPromptEffort: ctxSelectedPromptEffort,- selectedModelSelection: ctxSelectedModelSelection,- } = sendCtx;-- const createdAt = new Date().toISOString();- const nextThreadId = newThreadId();- const planMarkdown = activeProposedPlan.planMarkdown;- const implementationPrompt = buildPlanImplementationPrompt(planMarkdown);- const outgoingImplementationPrompt = formatOutgoingPrompt({- provider: ctxSelectedProvider,- model: ctxSelectedModel,- models: ctxSelectedProviderModels,- effort: ctxSelectedPromptEffort,- text: implementationPrompt,- });- if (composerRef.current?.validateProviderInput(outgoingImplementationPrompt) === false) {- return;- }- const nextThreadTitle = truncate(buildPlanImplementationThreadTitle(planMarkdown));- const nextThreadModelSelection: ModelSelection = ctxSelectedModelSelection;-- sendInFlightRef.current = true;- beginLocalDispatch({ preparingWorktree: false });- const finish = () => {- sendInFlightRef.current = false;- resetLocalDispatch();- };-- const createResult = await createThread({- environmentId,- input: {- threadId: nextThreadId,- projectId: activeProject.id,- title: nextThreadTitle,- modelSelection: nextThreadModelSelection,- runtimeMode,- interactionMode: "default",- branch: activeThreadBranch,- worktreePath: activeThread.worktreePath,- createdAt,- },- });- let failure: AtomCommandResult<unknown, unknown> | null =- createResult._tag === "Failure" ? createResult : null;-- if (failure === null) {- const startResult = await startThreadTurn({- environmentId,- input: {- threadId: nextThreadId,- message: {- messageId: newMessageId(),- role: "user",- text: outgoingImplementationPrompt,- attachments: [],- },- modelSelection: ctxSelectedModelSelection,- titleSeed: nextThreadTitle,- runtimeMode,- interactionMode: "default",- sourceProposedPlan: {- threadId: activeThread.id,- planId: activeProposedPlan.id,- },- createdAt,- },- });- failure = startResult._tag === "Failure" ? startResult : null;- }-- if (failure === null) {- const startedResult = await settlePromise(() =>- waitForStartedServerThread(scopeThreadRef(activeThread.environmentId, nextThreadId)),- );- failure = startedResult._tag === "Failure" ? startedResult : null;- }-- if (failure === null) {- const navigateResult = await settlePromise(() =>- navigate({- to: "/$environmentId/$threadId",- params: {- environmentId: activeThread.environmentId,- threadId: nextThreadId,- },- }),- );- failure = navigateResult._tag === "Failure" ? navigateResult : null;- }-- if (failure !== null) {- const cleanupResult = await deleteThread({- environmentId,- input: {- threadId: nextThreadId,- },- });- if (cleanupResult._tag === "Failure" && !isAtomCommandInterrupted(cleanupResult)) {- console.warn(- "Failed to clean up implementation thread after start failure.",- squashAtomCommandFailure(cleanupResult),- );- }- if (!isAtomCommandInterrupted(failure)) {- const error = squashAtomCommandFailure(failure);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Could not start implementation thread",- description:- error instanceof Error- ? error.message- : "An error occurred while creating the new thread.",- }),- );- }- }- finish();- }, [- activeProject,- activeProposedPlan,- activeThreadBranch,- activeThread,- beginLocalDispatch,- activeEnvironmentUnavailable,- createThread,- deleteThread,- isConnecting,- isSendBusy,- isServerThread,- navigate,- resetLocalDispatch,- runtimeMode,- startThreadTurn,- environmentId,- composerRef,- ]);-- const getModelDisabledReason = useCallback(- (instanceId: ProviderInstanceId, model: string): string | null => {- if (!activeThread) {- return null;- }- const reason = getStartedThreadModelChangeBlockReason({- providers: providerStatuses,- hasStartedSession: activeThread.session !== null,- currentModelSelection: activeThread.modelSelection,- currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null,- nextModelSelection: { instanceId, model },- });- return reason ? `${reason.description} Start a new thread to use this model.` : null;- },- [activeThread, providerStatuses],- );-- const onProviderModelSelect = useCallback(- (instanceId: ProviderInstanceId, model: string) => {- if (!activeThread) return;- // Look up the configured instance so model normalization and custom- // model lookup stay scoped to that exact instance. Unknown instance ids- // are rejected by returning early; the server remains authoritative too.- const entry = providerStatuses.find((snapshot) => snapshot.instanceId === instanceId);- const resolvedDriverKind = entry?.driver ?? null;- if (- lockedProvider !== null &&- resolvedDriverKind !== null &&- resolvedDriverKind !== lockedProvider- ) {- scheduleComposerFocus();- return;- }- if (lockedProvider !== null && activeThread.session?.providerInstanceId) {- const currentEntry = providerStatuses.find(- (snapshot) => snapshot.instanceId === activeThread.session?.providerInstanceId,- );- if (- currentEntry?.continuation?.groupKey &&- entry?.continuation?.groupKey &&- currentEntry.continuation.groupKey !== entry.continuation.groupKey- ) {- scheduleComposerFocus();- return;- }- }- const resolvedModel = resolveAppModelSelectionForInstance(- instanceId,- settings,- providerStatuses,- model,- );- if (!resolvedModel) {- scheduleComposerFocus();- return;- }- const nextModelSelection: ModelSelection = {- instanceId,- model: resolvedModel,- };- const modelChangeBlockReason = getStartedThreadModelChangeBlockReason({- providers: providerStatuses,- hasStartedSession: activeThread.session !== null,- currentModelSelection: activeThread.modelSelection,- currentProviderInstanceId: activeThread.session?.providerInstanceId ?? null,- nextModelSelection,- });- if (modelChangeBlockReason) {- toastManager.add({- type: "warning",- title: modelChangeBlockReason.title,- description: modelChangeBlockReason.description,- });- scheduleComposerFocus();- return;- }- setComposerDraftModelSelection(- scopeThreadRef(activeThread.environmentId, activeThread.id),- nextModelSelection,- );- setStickyComposerModelSelection(nextModelSelection);- scheduleComposerFocus();- },- [- activeThread,- lockedProvider,- scheduleComposerFocus,- setComposerDraftModelSelection,- setStickyComposerModelSelection,- providerStatuses,- settings,- ],- );- const onEnvModeChange = useCallback(- (mode: DraftThreadEnvMode) => {- if (canOverrideServerThreadEnvMode) {- setPendingServerThreadEnvMode(mode);- scheduleComposerFocus();- return;- }- if (isLocalDraftThread) {- setDraftThreadContext(composerDraftTarget, {- envMode: mode,- startFromOrigin: resolveNewDraftStartFromOrigin({- envMode: mode,- newWorktreesStartFromOrigin: primaryServerSettings.newWorktreesStartFromOrigin,- }),- ...(mode === "worktree" && draftThread?.worktreePath ? { worktreePath: null } : {}),- });- }- scheduleComposerFocus();- },- [- canOverrideServerThreadEnvMode,- composerDraftTarget,- draftThread?.worktreePath,- isLocalDraftThread,- primaryServerSettings.newWorktreesStartFromOrigin,- setPendingServerThreadEnvMode,- scheduleComposerFocus,- setDraftThreadContext,- ],- );-- const onStartFromOriginChange = (nextStartFromOrigin: boolean) => {- if (canOverrideServerThreadEnvMode && activeThread) {- setPendingServerThreadStartFromOriginByThreadId((current) =>- current[activeThread.id] === nextStartFromOrigin- ? current- : { ...current, [activeThread.id]: nextStartFromOrigin },- );- return;- }- if (isLocalDraftThread) {- setDraftThreadContext(composerDraftTarget, {- startFromOrigin: nextStartFromOrigin,- });- }- };-- const onExpandTimelineImage = useCallback((preview: ExpandedImagePreview) => {- setExpandedImage(preview);- }, []);- const onOpenTurnDiff = useCallback(- (turnId: TurnId, filePath?: string) => {- if (!isServerThread || !activeThreadRef) return;- useDiffPanelStore.getState().selectTurn(activeThreadRef, turnId, filePath);- useRightPanelStore.getState().open(activeThreadRef, "diff");- onDiffPanelOpen?.();- },- [activeThreadRef, isServerThread, onDiffPanelOpen],- );- // Both the Map and the revert handler are read from refs at call-time so- // the callback reference is fully stable and never busts context identity.- const revertTurnCountRef = useRef(revertTurnCountByUserMessageId);- revertTurnCountRef.current = revertTurnCountByUserMessageId;- const onRevertToTurnCountRef = useRef(onRevertToTurnCount);- onRevertToTurnCountRef.current = onRevertToTurnCount;- const onRevertUserMessage = useCallback((messageId: MessageId) => {- const targetTurnCount = revertTurnCountRef.current.get(messageId);- if (typeof targetTurnCount !== "number") {- return;- }- void onRevertToTurnCountRef.current(targetTurnCount);- }, []);-- // Empty state: no active thread- if (!activeThread) {- return <NoActiveThreadState />;- }-- const panelToggleControls = (- <PanelLayoutControls- terminalAvailable={activeProject !== null}- terminalOpen={terminalUiState.terminalOpen}- terminalShortcutLabel={shortcutLabelForCommand(keybindings, "terminal.toggle")}- rightPanelAvailable={activeProject !== null}- rightPanelOpen={rightPanelOpen}- rightPanelShortcutLabel={shortcutLabelForCommand(keybindings, "rightPanel.toggle")}- // Suppressed while the Agents surface is visible: the roster itself is- // on screen, so the toggle badge would be pointing at nothing.- liveAgentCount={- rightPanelOpen && activeRightPanelSurface?.kind === "agents" ? 0 : agentPanelModel.liveCount- }- onToggleTerminal={toggleTerminalVisibility}- onToggleRightPanel={toggleRightPanel}- />- );- const panelLayoutControls = (- <div- className={cn(- // One inset in both states: the controls move between containers when- // the right panel opens, and a different right offset made them jump- // sideways on every toggle.- "absolute top-[var(--workspace-controls-top)] right-[var(--workspace-controls-right)] z-50 mr-px flex h-[var(--workspace-topbar-height)] items-center gap-1 [-webkit-app-region:no-drag]",- )}- data-workspace-titlebar-controls- >- {rightPanelOpen && !shouldUseRightPanelSheet ? (- <RightPanelMaximizeControl- maximized={rightPanelMaximized}- onToggle={toggleRightPanelMaximized}- />- ) : null}- {panelToggleControls}- </div>- );- const rightPanelContent = activeThreadRef ? (- activeRightPanelSurface?.kind === "preview" ? (- <Suspense fallback={null}>- <PreviewPanel- mode="embedded"- threadRef={activeThreadRef}- tabId={activeRightPanelSurface.resourceId}- configuredUrls={configuredPreviewUrls}- visible- onSendAnnotation={(annotation, image) => {- void onSend(undefined, "foreground", { annotation, image });- }}- />- </Suspense>- ) : activeRightPanelSurface?.kind === "terminal" ? (- <PersistentThreadTerminalPanel- threadRef={activeThreadRef}- surface={activeRightPanelSurface}- launchContext={activeTerminalLaunchContext ?? null}- focusRequestId={terminalFocusRequestId}- keybindings={keybindings}- onAddTerminalContext={addTerminalContextToDraft}- onSplitTerminal={splitPanelTerminal}- onSplitTerminalVertical={splitPanelTerminalVertical}- onNewTerminal={addTerminalSurface}- onActiveTerminalChange={activatePanelTerminal}- onCloseTerminal={closePanelTerminal}- splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}- splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}- newShortcutLabel={newTerminalShortcutLabel ?? undefined}- closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}- />- ) : activeRightPanelSurface?.kind === "diff" ? (- <Suspense fallback={null}>- <DiffPanel- key={`${activeThreadKey}:${diffPanelGitStatusResolutionKey}`}- mode="embedded"- composerDraftTarget={composerDraftTarget}- initialGitScope={initialDiffPanelGitScope}- />- </Suspense>- ) : activeRightPanelSurface?.kind === "pull-request" && !pullRequestsCapabilityKnown ? (- <PullRequestDetailGhost />- ) : activeRightPanelSurface?.kind === "pull-request" && !supportsPullRequests ? (- <PullRequestsUnavailableState- title="Pull requests unavailable"- error="Update this environment's T3 Code server to browse pull requests."- />- ) : activeRightPanelSurface?.kind === "pull-request" ? (- // No onClose: the surface tab's own X owns closing here, and a second X in the header- // would be the same action twice. The thread context also drops the checkout button, so it- // is only right for the thread's own pull request, whose branch is already under the- // reader's feet. A link the agent wrote can open any other one here, and that one has to be- // checkable out like it is anywhere else.- <PullRequestDetailPanel- key={`${activeRightPanelSurface.repository}#${activeRightPanelSurface.number}`}- environmentId={activeThread.environmentId}- reference={{- projectId: activeRightPanelSurface.projectId as ProjectId,- repository: activeRightPanelSurface.repository,- number: activeRightPanelSurface.number,- }}- context={- isThreadOwnPullRequest(- {- projectId: linkedThreadPullRequest?.projectId ?? activeProject?.id ?? null,- repository: threadRepository,- number: activeThreadPr?.number ?? null,- },- {- projectId: activeRightPanelSurface.projectId,- repository: activeRightPanelSurface.repository,- number: activeRightPanelSurface.number,- },- )- ? "thread"- : "page"- }- composerDraftTarget={composerDraftTarget}- onStateChange={handlePullRequestTabStatusChange}- />- ) : activeRightPanelSurface?.kind === "agents" ? (- <AgentsPanel- model={agentPanelModel}- environmentId={activeThreadRef?.environmentId ?? null}- threadId={activeThreadRef?.threadId ?? null}- />- ) : (activeRightPanelSurface?.kind === "files" || activeRightPanelSurface?.kind === "file") &&- activeProject &&- activeWorkspaceRoot ? (- <Suspense fallback={null}>- <FilePreviewPanel- key={`${activeProject.environmentId}:${activeWorkspaceRoot}`}- environmentId={activeProject.environmentId}- cwd={activeWorkspaceRoot}- projectName={activeProject.title}- threadRef={activeThreadRef}- composerDraftTarget={composerDraftTarget}- keybindings={keybindings}- availableEditors={availableEditors}- relativePath={- activeRightPanelSurface.kind === "file" ? activeRightPanelSurface.relativePath : null- }- revealLine={activeFileSurface?.revealLine ?? null}- revealRequestId={activeFileSurface?.revealRequestId ?? 0}- onOpenFile={openFileSurface}- onPendingChange={handleFilePendingChange}- />- </Suspense>- ) : null- ) : null;-- const workspaceFileDropHandlers = makeWorkspaceFileDropHandlers({- setDragActive: setIsWorkspaceFileDragActive,- addFiles: (files) => composerRef.current?.addDroppedFiles(files),- });- const externalComposerDrawerAttached =- composerBannerItems.length > 0 || Boolean(threadSyncPhase && !activeEnvironmentUnavailable);-- return (- <div className="relative flex min-h-0 min-w-0 flex-1 overflow-hidden bg-background">- {rightPanelOpen && !shouldUseRightPanelSheet ? panelLayoutControls : null}- <div- className={cn(- "flex min-h-0 min-w-0 flex-col overflow-x-hidden",- rightPanelMaximized ? "w-0 flex-none" : "flex-1",- )}- data-chat-column-maximized-away={rightPanelMaximized ? "true" : "false"}- >- {/* Top bar */}- <WorkspacePageHeader- data-chat-header- electron={isElectron}- reserveNativeControls={reserveTitleBarControlInset && !inlineRightPanelOwnsTitleBar}- className="relative bg-background"- >- {!rightPanelOpen ? panelLayoutControls : null}- <ChatHeader- {...(!supportsPullRequests || activeProjectRepository === null- ? {}- : { onOpenPullRequest: openProjectPullRequest })}- activeThreadEnvironmentId={activeThread.environmentId}- activeThreadId={activeThread.id}- {...(routeKind === "draft" && draftId ? { draftId } : {})}- activeThreadTitle={activeThread.title}- isServerThread={isServerThread}- changeRequest={activeThreadChangeRequest}- activeProjectName={activeProject?.title}- activeProjectCwd={activeProject?.workspaceRoot ?? null}- activeProjectFaviconPath={activeProject?.faviconPath ?? null}- openInCwd={gitCwd}- activeProjectScripts={activeProject?.scripts}- preferredScriptId={- activeProject ? (lastInvokedScriptByProjectId[activeProject.id] ?? null) : null- }- keybindings={keybindings}- availableEditors={availableEditors}- rightPanelOpen={rightPanelOpen}- gitCwd={gitCwd}- onNewThreadInProject={handleNewThreadInActiveProject}- onRunProjectScript={runProjectScript}- onAddProjectScript={saveProjectScript}- onUpdateProjectScript={updateProjectScript}- onDeleteProjectScript={deleteProjectScript}- />- </WorkspacePageHeader>-- <ThreadErrorBanner- error={visibleThreadError}- onDismiss={() => {- setThreadError(activeThread.id, null);- dismissThreadErrorBannerForSession(threadErrorBannerKey);- setThreadErrorBannerDismissTick((tick) => tick + 1);- }}- />- {/* Main content area with optional plan sidebar */}- <div className="flex min-h-0 min-w-0 flex-1">- {/* Chat column */}- <div- className="relative flex min-h-0 min-w-0 flex-1 flex-col"- data-chat-workspace-drop-target="true"- onDragEnter={workspaceFileDropHandlers.onDragEnter}- onDragOver={workspaceFileDropHandlers.onDragOver}- onDragLeave={workspaceFileDropHandlers.onDragLeave}- onDrop={workspaceFileDropHandlers.onDrop}- >- {isWorkspaceFileDragActive ? (- <div- className="pointer-events-none absolute inset-2 z-40 flex items-center justify-center rounded-2xl border-2 border-dashed border-primary/60 bg-primary/[0.035]"- data-chat-workspace-drop-overlay="true"- >- <div- role="status"- className="flex items-center gap-2 rounded-full border border-primary/25 bg-background/95 px-4 py-2.5 text-sm font-medium text-foreground shadow-lg"- >- <PaperclipIcon className="size-4 text-primary" aria-hidden="true" />- Drop files to attach- </div>- </div>- ) : null}- {/* Provider status overlays the timeline without changing its content height. */}- <div className="pointer-events-none absolute inset-x-0 top-0 z-20">- <ProviderStatusBanner- status={visibleProviderStatus}- onDismiss={() => setDismissedProviderStatusBannerKey(providerStatusBannerKey)}- />- </div>- {/* Messages Wrapper */}- <div className="relative flex min-h-0 flex-1 flex-col">- {/* Messages — LegendList handles virtualization and scrolling internally */}- <MessagesTimeline- agentPanelModel={agentPanelModel}- onOpenAgents={addAgentsSurface}- key={activeThread.id}- isWorking={isWorking}- workingStepLabel={workingStepLabel}- activeTurnStartedAt={activeWorkStartedAt}- listRef={legendListRef}- timelineEntries={timelineEntries}- latestTurn={activeLatestTurn}- runningTurnId={activeRunningTurnId}- turnDiffSummaryByAssistantMessageId={turnDiffSummaryByAssistantMessageId}- activeThreadEnvironmentId={activeThread.environmentId}- routeThreadKey={routeThreadKey}- onOpenTurnDiff={onOpenTurnDiff}- revertTurnCountByUserMessageId={revertTurnCountByUserMessageId}- onRevertUserMessage={onRevertUserMessage}- isRevertingCheckpoint={isRevertingCheckpoint}- onImageExpand={onExpandTimelineImage}- markdownCwd={gitCwd ?? undefined}- resolvedTheme={resolvedTheme}- timestampFormat={timestampFormat}- workspaceRoot={activeWorkspaceRoot}- skills={activeProviderStatus?.skills ?? EMPTY_PROVIDER_SKILLS}- anchorMessageId={timelineAnchorMessageId}- onAnchorReady={onTimelineAnchorReady}- contentInsetEndAdjustment={composerOverlayHeight}- liveFollowEnabled={timelineLiveFollowEnabled}- onIsAtEndChange={onIsAtEndChange}- onManualNavigation={cancelTimelineLiveFollowForUserNavigation}- hideEmptyPlaceholder={isDraftHeroState || threadDetailLoading}- topFadeEnabled={!hasTimelineTopBanner}- loadEarlier={loadEarlierTurns}- />-- {/* scroll to end pill — shown when user has scrolled away from the live edge */}- {showScrollToBottom && (- <div- className="pointer-events-none absolute left-1/2 z-30 flex -translate-x-1/2 justify-center py-1.5"- style={{ bottom: composerOverlayHeight + 4 }}- >- <Button- aria-label="Scroll to end"- onClick={() => scrollToEnd(true)}- className="pointer-events-auto gap-1.5 rounded-full px-3 text-muted-foreground hover:text-foreground"- size="xs"- variant="glass"- >- <ChevronDownIcon className="size-3.5" />- Scroll to end- </Button>- </div>- )}- </div>-- {/* Input bar — centered hero while a draft has no messages, docked at the bottom otherwise */}- <div- ref={setComposerOverlayElement}- data-chat-composer-overlay="true"- className={- isDraftHeroState- ? "pointer-events-none absolute inset-0 z-20 flex items-center"- : "pointer-events-none absolute inset-x-0 bottom-0 z-20 pt-1.5 sm:pt-2"- }- >- <div- ref={attachDraftHeroTransitionGroupRef}- className="w-full ps-[calc(env(safe-area-inset-left)+0.75rem)] pe-[calc(env(safe-area-inset-right)+0.75rem)] sm:ps-[calc(env(safe-area-inset-left)+1.25rem)] sm:pe-[calc(env(safe-area-inset-right)+1.25rem)]"- >- <div className="pointer-events-auto relative z-10">- {isDraftHeroState ? (- <div className="absolute inset-x-0 bottom-full z-0">- <div- className="pb-8"- style={- forceExpandedMobileComposer- ? {- viewTransitionName: MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,- }- : undefined- }- >- <DraftHeroHeadline- activeProjectRef={activeProjectRef}- activeProjectTitle={activeProject?.title ?? null}- />- </div>- <ComposerBannerStack className="relative z-0" items={composerBannerItems} />- </div>- ) : (- <ComposerBannerStack className="relative z-0" items={composerBannerItems} />- )}- {threadSyncPhase && !activeEnvironmentUnavailable ? (- <ThreadSyncStatusPill phase={threadSyncPhase} />- ) : null}- <div- className="relative"- style={- forceExpandedMobileComposer- ? { viewTransitionName: MOBILE_COMPOSER_VIEW_TRANSITION_NAME }- : undefined- }- >- <div- className={cn(- "chat-composer-glass-shell relative mx-auto w-full max-w-3xl",- externalComposerDrawerAttached && "chat-composer-glass-shell-attached",- showComposerContextStrip && "chat-composer-glass-shell-with-context",- )}- >- <div className="chat-composer-glass-host relative z-10 w-full rounded-[22px]">- <div ref={attachDraftHeroComposerAnchorRef} className="relative z-10">- <ChatComposer- composerRef={composerRef}- composerDraftTarget={composerDraftTarget}- environmentId={environmentId}- attachmentUploadsCapabilityKnown={attachmentUploadsCapabilityKnown}- supportsAttachmentUploads={supportsAttachmentUploads}- routeKind={routeKind}- routeThreadRef={routeThreadRef}- draftId={draftId}- activeThreadId={activeThreadId}- activeThreadEnvironmentId={activeThread?.environmentId}- activeThread={activeThread}- isServerThread={isServerThread}- isLocalDraftThread={isLocalDraftThread}- forceExpandedOnMobile={forceExpandedMobileComposer && isDraftHeroState}- projectSelectionRequired={isLocalDraftThread && activeProject === null}- phase={phase}- isConnecting={isConnecting}- isSendBusy={isSendBusy}- sendDisabledReason={- feedbackUploading- ? "Sending feedback"- : threadDetailLoading- ? "Messages loading"- : null- }- isPreparingWorktree={isPreparingWorktree}- externalDrawerAttached={externalComposerDrawerAttached}- environmentUnavailable={activeEnvironmentUnavailableState}- activePendingApproval={activePendingApproval}- pendingApprovals={pendingApprovals}- pendingUserInputs={pendingUserInputs}- activePendingProgress={activePendingProgress}- activePendingResolvedAnswers={activePendingResolvedAnswers}- activePendingIsResponding={activePendingIsResponding}- activePendingDraftAnswers={activePendingDraftAnswers}- activePendingQuestionIndex={activePendingQuestionIndex}- respondingRequestIds={respondingRequestIds}- showPlanFollowUpPrompt={showPlanFollowUpPrompt}- activeProposedPlan={activeProposedPlan}- activeTasksProgress={activeComposerTasksProgress}- activeTaskSteps={activeComposerTaskSteps}- runtimeMode={runtimeMode}- interactionMode={interactionMode}- lockedProvider={lockedProvider}- providerStatuses={providerStatuses as ServerProvider[]}- activeProjectDefaultModelSelection={- activeProject?.defaultModelSelection- }- activeThreadModelSelection={activeThread?.modelSelection}- activeContextWindow={activeContextWindow}- compactDisabled={compactDisabled}- compactDisabledReason={compactDisabledReason}- resolvedTheme={resolvedTheme}- settings={settings}- keybindings={keybindings}- terminalOpen={Boolean(terminalUiState.terminalOpen)}- gitCwd={gitCwd}- promptRef={promptRef}- composerImagesRef={composerImagesRef}- composerTerminalContextsRef={composerTerminalContextsRef}- composerElementContextsRef={composerElementContextsRef}- onSend={onSend}- onInterrupt={onInterrupt}- onImplementPlanInNewThread={onImplementPlanInNewThread}- onRespondToApproval={onRespondToApproval}- onSelectActivePendingUserInputOption={- onSelectActivePendingUserInputOption- }- onAdvanceActivePendingUserInput={onAdvanceActivePendingUserInput}- onPreviousActivePendingUserInputQuestion={- onPreviousActivePendingUserInputQuestion- }- onChangeActivePendingUserInputCustomAnswer={- onChangeActivePendingUserInputCustomAnswer- }- onProviderModelSelect={onProviderModelSelect}- getModelDisabledReason={getModelDisabledReason}- toggleInteractionMode={toggleInteractionMode}- handleRuntimeModeChange={handleRuntimeModeChange}- handleInteractionModeChange={handleInteractionModeChange}- focusComposer={focusComposer}- scheduleComposerFocus={scheduleComposerFocus}- setThreadError={setThreadError}- onExpandImage={onExpandTimelineImage}- />- </div>- </div>- <div className="min-h-0">- <div- data-terminal-open={terminalUiState.terminalOpen ? "true" : undefined}- className="relative z-0"- >- {showComposerContextStrip && (- <div className="pointer-events-auto">- <BranchToolbar- environmentId={activeThread.environmentId}- threadId={activeThread.id}- showGitControls={isGitRepo}- {...(routeKind === "draft" && draftId ? { draftId } : {})}- onEnvModeChange={onEnvModeChange}- startFromOrigin={startFromOrigin}- onStartFromOriginChange={onStartFromOriginChange}- {...(canOverrideServerThreadEnvMode- ? { effectiveEnvModeOverride: envMode }- : {})}- {...(canOverrideServerThreadEnvMode- ? {- activeThreadBranchOverride: activeThreadBranch,- onActiveThreadBranchOverrideChange:- setPendingServerThreadBranch,- }- : {})}- envLocked={envLocked}- onComposerFocusRequest={scheduleComposerFocus}- {...(canCheckoutPullRequestIntoThread- ? { onCheckoutPullRequestRequest: openPullRequestDialog }- : {})}- {...(hasMultipleEnvironments ? { onEnvironmentChange } : {})}- availableEnvironments={logicalProjectEnvironments}- />- </div>- )}- </div>- </div>- </div>- <div- aria-hidden- className="h-[calc(env(safe-area-inset-bottom)+1rem)] sm:h-[calc(env(safe-area-inset-bottom)+1.25rem)]"- />- </div>- </div>- </div>- </div>-- {activeThreadRef && activePreviewMiniPlayer ? (- <ThreadPreviewMiniPlayer- key={`${activeThreadKey}:${activePreviewMiniPlayer.tabId}`}- threadRef={activeThreadRef}- tabId={activePreviewMiniPlayer.tabId}- bottomInset={isDraftHeroState ? 0 : composerOverlayHeight}- />- ) : null}-- <AlertDialog open={branchRestoreConfirmOpen} onOpenChange={setBranchRestoreConfirmOpen}>- <AlertDialogPopup>- <AlertDialogHeader>- <AlertDialogTitle>- Switch to{" "}- <code className="font-medium">- {localCheckoutBranchMismatch?.threadBranch ?? ""}- </code>- ?- </AlertDialogTitle>- <AlertDialogDescription>- You have uncommitted changes. They'll carry over to the other branch, or block- the switch if they conflict.- </AlertDialogDescription>- </AlertDialogHeader>- <AlertDialogFooter>- <AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>- <Button- variant="default"- onClick={() => {- setBranchRestoreConfirmOpen(false);- void handleSwitchCheckoutToThread();- }}- >- Switch branch- </Button>- </AlertDialogFooter>- </AlertDialogPopup>- </AlertDialog>-- {pullRequestDialogState ? (- <PullRequestThreadDialog- key={pullRequestDialogState.key}- open- environmentId={activeThread.environmentId}- threadId={activeThread.id}- cwd={activeProject?.workspaceRoot ?? null}- initialReference={pullRequestDialogState.initialReference}- onOpenChange={(open) => {- if (!open) {- closePullRequestDialog();- }- }}- onPrepared={handlePreparedPullRequestThread}- />- ) : null}- </div>- {/* end chat column */}- </div>- {/* end horizontal flex container */}-- {mountedTerminalThreadRefs.map(({ key: mountedThreadKey, threadRef: mountedThreadRef }) => (- <PersistentThreadTerminalDrawer- key={mountedThreadKey}- threadRef={mountedThreadRef}- threadId={mountedThreadRef.threadId}- visible={mountedThreadKey === activeThreadKey && terminalUiState.terminalOpen}- launchContext={- mountedThreadKey === activeThreadKey ? (activeTerminalLaunchContext ?? null) : null- }- focusRequestId={mountedThreadKey === activeThreadKey ? terminalFocusRequestId : 0}- splitShortcutLabel={splitTerminalShortcutLabel ?? undefined}- splitVerticalShortcutLabel={splitTerminalVerticalShortcutLabel ?? undefined}- newShortcutLabel={newTerminalShortcutLabel ?? undefined}- closeShortcutLabel={closeTerminalShortcutLabel ?? undefined}- keybindings={keybindings}- onAddTerminalContext={addTerminalContextToDraft}- />- ))}- </div>-- {!shouldUseRightPanelSheet && rightPanelOpen && activeThreadRef ? (- <RightPanelTabs- mode="inline"- maximized={rightPanelMaximized}- surfaces={rightPanelState.surfaces}- activeSurfaceId={activeRightPanelSurface?.id ?? null}- pendingSurfaceIds={pendingFileSurfaceIds}- previewSessions={activePreviewState.sessions}- desktopByTabId={activePreviewState.desktopByTabId}- previewRuntimeTabId={resolvePreviewRuntimeTabId}- terminalLabelsById={activeTerminalLabelsById}- onActivate={activateRightPanelSurface}- onCloseSurface={closeRightPanelSurface}- onCloseOtherSurfaces={closeOtherRightPanelSurfaces}- onCloseSurfacesToRight={closeRightPanelSurfacesToRight}- onCloseAllSurfaces={closeAllRightPanelSurfaces}- onCopyFilePath={copyRightPanelFilePath}- onAddBrowser={createBrowserSurface}- onAddTerminal={addTerminalSurface}- onAddDiff={addDiffSurface}- onAddFiles={addFilesSurface}- onAddPullRequest={addPullRequestSurface}- onAddAgents={addAgentsSurface}- browserAvailable={isPreviewSupportedInRuntime()}- terminalAvailable={activeProject !== null}- diffAvailable={isServerThread && isGitRepo}- filesAvailable={activeProject !== null}- pullRequestAvailable={pullRequestSurfaceAvailable}- agentsAvailable- pullRequestStatuses={pullRequestTabStatuses}- liveAgentCount={agentPanelModel.liveCount}- >- {rightPanelContent}- </RightPanelTabs>- ) : null}- {shouldUseRightPanelSheet && rightPanelOpen && activeThreadRef ? (- <RightPanelSheet open onClose={closePreviewPanel}>- <RightPanelTabs- mode="sheet"- // Same effective inset as the closed-state titlebar controls- // (pr-3 in the tab bar plus this pixel equals the absolute- // right inset plus mr-px), so the cluster does not creep when- // the sheet opens.- layoutControls={<div className="mr-px flex items-center">{panelToggleControls}</div>}- surfaces={rightPanelState.surfaces}- activeSurfaceId={activeRightPanelSurface?.id ?? null}- pendingSurfaceIds={pendingFileSurfaceIds}- previewSessions={activePreviewState.sessions}- desktopByTabId={activePreviewState.desktopByTabId}- previewRuntimeTabId={resolvePreviewRuntimeTabId}- terminalLabelsById={activeTerminalLabelsById}- onActivate={activateRightPanelSurface}- onCloseSurface={closeRightPanelSurface}- onCloseOtherSurfaces={closeOtherRightPanelSurfaces}- onCloseSurfacesToRight={closeRightPanelSurfacesToRight}- onCloseAllSurfaces={closeAllRightPanelSurfaces}- onCopyFilePath={copyRightPanelFilePath}- onAddBrowser={createBrowserSurface}- onAddTerminal={addTerminalSurface}- onAddDiff={addDiffSurface}- onAddFiles={addFilesSurface}- onAddPullRequest={addPullRequestSurface}- onAddAgents={addAgentsSurface}- browserAvailable={isPreviewSupportedInRuntime()}- terminalAvailable={activeProject !== null}- diffAvailable={isServerThread && isGitRepo}- filesAvailable={activeProject !== null}- pullRequestAvailable={pullRequestSurfaceAvailable}- agentsAvailable- pullRequestStatuses={pullRequestTabStatuses}- liveAgentCount={agentPanelModel.liveCount}- >- {rightPanelContent}- </RightPanelTabs>- </RightPanelSheet>- ) : null}-- {expandedImage && (- <ExpandedImageDialog- key={`${expandedImage.images[expandedImage.index]?.src ?? "image"}:${expandedImage.index}`}- preview={expandedImage}- onClose={closeExpandedImage}- />- )}- </div>- );-}--export default function ChatView(props: ChatViewProps) {- return (- <DiffWorkerPoolProvider>- <ChatViewContent {...props} />- </DiffWorkerPoolProvider>- );-}diff --git a/apps/web/src/components/CommandPalette.logic.test.ts b/apps/web/src/components/CommandPalette.logic.test.tsindex d521c1193..ea2c06a5a 100644--- a/apps/web/src/components/CommandPalette.logic.test.ts+++ b/apps/web/src/components/CommandPalette.logic.test.ts@@ -4,6 +4,7 @@ import type { Thread } from "../types";import {browseInputEndPaddingClass,buildBrowseGroups,+ buildModelPickerCommandPaletteAction,buildThreadActionItems,enumerateCommandPaletteItems,filterPinnedBrowseEntries,@@ -112,6 +113,55 @@ describe("reduceCommandPaletteUiState", () => {});});+describe("buildModelPickerCommandPaletteAction", () => {+ it("closes the command palette and schedules the shared handle opener", async () => {+ const events: string[] = [];+ const openModelPicker = vi.fn(() => events.push("open-model-picker"));+ let scheduled: (() => void) | null = null;+ const action = buildModelPickerCommandPaletteAction({+ composerHandle: { openModelPicker },+ closePalette: () => events.push("close-command-palette"),+ scheduleAfterClose: (open) => {+ events.push("schedule-model-picker");+ scheduled = open;+ },+ icon: null,+ });++ expect(action).toMatchObject({+ value: "action:change-model",+ title: "Change model",+ disabled: false,+ keepOpen: true,+ shortcutCommand: "modelPicker.toggle",+ });+ await action.run();+ expect(events).toEqual(["close-command-palette", "schedule-model-picker"]);+ expect(openModelPicker).not.toHaveBeenCalled();++ expect(scheduled).not.toBeNull();+ scheduled!();+ expect(openModelPicker).toHaveBeenCalledOnce();+ expect(events).toEqual(["close-command-palette", "schedule-model-picker", "open-model-picker"]);+ });++ it("disables the action when no composer handle exists", async () => {+ const closePalette = vi.fn();+ const scheduleAfterClose = vi.fn();+ const action = buildModelPickerCommandPaletteAction({+ composerHandle: null,+ closePalette,+ scheduleAfterClose,+ icon: null,+ });++ expect(action.disabled).toBe(true);+ await action.run();+ expect(closePalette).not.toHaveBeenCalled();+ expect(scheduleAfterClose).not.toHaveBeenCalled();+ });+});+describe("enumerateCommandPaletteItems", () => {it("assigns positional jump shortcuts to the first nine displayed items", () => {const items = Array.from({ length: 10 }, (_, index) => ({diff --git a/apps/web/src/components/CommandPalette.logic.ts b/apps/web/src/components/CommandPalette.logic.tsindex 688a8a8ea..b240c4b68 100644--- a/apps/web/src/components/CommandPalette.logic.ts+++ b/apps/web/src/components/CommandPalette.logic.ts@@ -118,6 +118,29 @@ export interface CommandPaletteGroup {readonly items: ReadonlyArray<CommandPaletteActionItem | CommandPaletteSubmenuItem>;}+export function buildModelPickerCommandPaletteAction(input: {+ readonly composerHandle: { readonly openModelPicker: () => void } | null;+ readonly closePalette: () => void;+ readonly scheduleAfterClose: (openModelPicker: () => void) => void;+ readonly icon: ReactNode;+}): CommandPaletteActionItem {+ return {+ kind: "action",+ value: "action:change-model",+ searchTerms: ["change model", "model", "provider", "reasoning"],+ title: "Change model",+ icon: input.icon,+ disabled: input.composerHandle === null,+ keepOpen: true,+ shortcutCommand: "modelPicker.toggle",+ run: async () => {+ if (input.composerHandle === null) return;+ input.closePalette();+ input.scheduleAfterClose(input.composerHandle.openModelPicker);+ },+ };+}+export interface CommandPaletteView {readonly addonIcon: ReactNode;readonly groups: ReadonlyArray<CommandPaletteGroup>;diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsxindex c5ec3f095..e026c7e60 100644--- a/apps/web/src/components/CommandPalette.tsx+++ b/apps/web/src/components/CommandPalette.tsx@@ -1,6 +1,5 @@"use client";-import { scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime/environment";import {canCreateProjectInEnvironment,getCloneDestinationBrowsePath,@@ -10,7 +9,6 @@ import {normalizePastedCloneUrl,} from "@t3tools/client-runtime/operations/projects";import { connectionStatusText } from "@t3tools/client-runtime/connection";-import { threadSearchMatchKey } from "@t3tools/client-runtime/state/thread-search";import {canPreloadBrowsePath,createBrowseNavigationCoordinator,@@ -19,7 +17,6 @@ import {} from "@t3tools/client-runtime/state/filesystem";import {isAtomCommandInterrupted,- settlePromise,squashAtomCommandFailure,} from "@t3tools/client-runtime/state/runtime";import {@@ -36,13 +33,15 @@ import { useNavigate, useParams } from "@tanstack/react-router";import * as Option from "effect/Option";import {ArrowLeftIcon,+ BotIcon,+ ChartNoAxesColumnIcon,CornerLeftUpIcon,FileSearchIcon,FolderIcon,FolderPlusIcon,LinkIcon,- MessageSquareIcon,PaletteIcon,+ PuzzleIcon,ServerIcon,SettingsIcon,SquarePenIcon,@@ -78,7 +77,7 @@ import { useAtomQueryRunner } from "../state/use-atom-query-runner";import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";import { useProjects, useThreadShells } from "../state/entities";import { useThreadSearch } from "../state/queries";-import { resolveThreadActionProjectRef, startNewThreadFromContext } from "../lib/chatThreadActions";+import { resolveThreadActionProjectRef } from "../lib/chatThreadActions";import {appendBrowsePathSegment,ensureBrowseDirectoryPath,@@ -94,7 +93,6 @@ import { onOpenCommandPalette } from "../commandPaletteBus";import { isPreviewFocused } from "../lib/previewFocus";import { isTerminalFocused } from "../lib/terminalFocus";import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";-import { getLatestThreadForProject, sortThreads } from "../lib/threadSort";import {cn,getLocalFileManagerName,@@ -103,7 +101,7 @@ import {newProjectId,} from "../lib/utils";import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";-import { buildThreadRouteParams, resolveThreadRouteTarget } from "../threadRoutes";+import { resolveThreadRouteTarget } from "../threadRoutes";import {applyWslEnvironmentConfiguration,parseWslUncPath,@@ -114,6 +112,7 @@ import {ADDON_ICON_CLASS,browseInputEndPaddingClass,buildBrowseGroups,+ buildModelPickerCommandPaletteAction,buildProjectActionItems,buildRootGroups,buildThreadActionItems,@@ -140,18 +139,12 @@ import { ProjectFavicon } from "./ProjectFavicon";import { ProjectFilePicker } from "./files/ProjectFilePicker";import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";import { toggleThemeEditorForTheme } from "./settings/themeEditorStore";-import {- COMMAND_PALETTE_META_ICON_CLASS,- CommandPaletteMetaDot,- ThreadCommandSubtitle,-} from "./ThreadCommandSubtitle";-import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";+import { openSettings } from "~/settingsDialogStore";+import { openPlugins } from "~/pluginsDialogStore";+import { openUsage } from "~/usageDialogStore";+import { COMMAND_PALETTE_META_ICON_CLASS, CommandPaletteMetaDot } from "./ThreadCommandSubtitle";import { primaryServerKeybindingsAtom, primaryServerProvidersAtom } from "../state/server";-import {- deriveProviderInstanceEntries,- resolveDefaultProviderModelSelection,- type ProviderInstanceEntry,-} from "../providerInstances";+import { resolveDefaultProviderModelSelection } from "../providerInstances";import { resolveShortcutCommand, threadJumpIndexFromCommand } from "../keybindings";import { CommandDialog, CommandDialogPopup, CommandFooterAction } from "./ui/command";import { Button } from "./ui/button";@@ -563,6 +556,7 @@ function OpenCommandPaletteDialog(props: {readonly clearOpenIntent: () => void;}) {const navigate = useNavigate();+ const composerHandleRef = useComposerHandleContext();const { clearOpenIntent, openIntent, openOverlayMode, setOpen } = props;const [query, setQuery] = useState("");const deferredQuery = useDeferredValue(query);@@ -593,18 +587,6 @@ function OpenCommandPaletteDialog(props: {const keybindings = useAtomValue(primaryServerKeybindingsAtom);const { theme, themeHalves, resolvedTheme } = useTheme();const providers = useAtomValue(primaryServerProvidersAtom);- const providerEntryByEnvironmentAndInstanceId = useMemo(() => {- const map = new Map<string, ProviderInstanceEntry>();- for (const environment of environments) {- const environmentProviders =- environment.serverConfig?.providers ??- (environment.environmentId === primaryEnvironmentId ? providers : []);- for (const entry of deriveProviderInstanceEntries(environmentProviders)) {- map.set(`${environment.environmentId}:${entry.instanceId}`, entry);- }- }- return map;- }, [environments, primaryEnvironmentId, providers]);const [viewStack, setViewStack] = useState<CommandPaletteView[]>([]);const currentView = viewStack.at(-1) ?? null;const environmentIds = useMemo(@@ -616,17 +598,6 @@ function OpenCommandPaletteDialog(props: {);const threadSearchQuery = currentView === null && !isActionsOnly ? deferredQuery : "";const threadSearch = useThreadSearch(environmentIds, threadSearchQuery);- const threadContentMatchByKey = useMemo(- () =>- new Map(- threadSearch.matches.flatMap((match) =>- match.source === "user" || match.source === "assistant"- ? [[threadSearchMatchKey(match), match] as const]- : [],- ),- ),- [threadSearch.matches],- );const [browseGeneration, setBrowseGeneration] = useState(0);const browseNavigationRef = useRef<ReturnType<typeof createBrowseNavigationCoordinator> | null>(null,@@ -868,16 +839,6 @@ function OpenCommandPaletteDialog(props: {new Map<ProjectId, string>(projects.map((project) => [project.id, project.workspaceRoot])),[projects],);- const projectFaviconPathById = useMemo(- () => new Map(projects.map((project) => [project.id, project.faviconPath ?? null] as const)),- [projects],- );- const projectTitleById = useMemo(- () => new Map<ProjectId, string>(projects.map((project) => [project.id, project.title])),- [projects],- );-- const activeThreadId = activeThread?.id;const currentProjectEnvironmentId =activeThread?.environmentId ?? activeDraftThread?.environmentId ?? null;const currentProjectId = activeThread?.projectId ?? activeDraftThread?.projectId ?? null;@@ -960,48 +921,10 @@ function OpenCommandPaletteDialog(props: {);const openProjectFromSearch = useMemo(- () => async (project: (typeof projects)[number]) => {- const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);- const groupedProjectKeys = group- ? new Set(- group.memberProjectRefs.map(- (projectRef) => `${projectRef.environmentId}:${projectRef.projectId}`,- ),- )- : null;- const latestThread = groupedProjectKeys- ? (sortThreads(- threads.filter(- (thread) =>- thread.archivedAt === null &&- groupedProjectKeys.has(`${thread.environmentId}:${thread.projectId}`),- ),- clientSettings.sidebarThreadSortOrder,- )[0] ?? null)- : getLatestThreadForProject(- threads.filter((thread) => thread.environmentId === project.environmentId),- project.id,- clientSettings.sidebarThreadSortOrder,- );- if (latestThread) {- await navigate({- to: "/$environmentId/$threadId",- params: buildThreadRouteParams(- scopeThreadRef(latestThread.environmentId, latestThread.id),- ),- });- return;- }-- await handleNewThread(scopeProjectRef(project.environmentId, project.id));+ () => async (_project: (typeof projects)[number]) => {+ await navigate({ to: "/" });},- [- clientSettings.sidebarThreadSortOrder,- handleNewThread,- navigate,- projectGroupByTargetKey,- threads,- ],+ [navigate],);const projectSearchItems = useMemo(@@ -1055,100 +978,15 @@ function OpenCommandPaletteDialog(props: {);},icon: projectFavicon,- runProject: async (project) => {- const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`);- const contextualRefBelongsToGroup =- contextualProjectRef !== null &&- group?.memberProjectRefs.some(- (projectRef) =>- projectRef.environmentId === contextualProjectRef.environmentId &&- projectRef.projectId === contextualProjectRef.projectId,- );- await handleNewThread(- contextualRefBelongsToGroup- ? contextualProjectRef- : scopeProjectRef(project.environmentId, project.id),- );+ runProject: async () => {+ await navigate({ to: "/" });},}),),- [- contextualProjectRef,- handleNewThread,- pickerProjects,- projectEnvironmentLocationById,- projectGroupByTargetKey,- ],+ [navigate, pickerProjects, projectEnvironmentLocationById, projectGroupByTargetKey],);- const allThreadItems = useMemo(- () =>- buildThreadActionItems({- threads,- ...(activeThreadId ? { activeThreadId } : {}),- projectTitleById,- sortOrder: clientSettings.sidebarThreadSortOrder,- icon: <MessageSquareIcon className={ITEM_ICON_CLASS} />,- renderLeadingContent: (thread) => <ThreadRowLeadingStatus thread={thread} />,- renderTrailingContent: (thread) => <ThreadRowTrailingStatus thread={thread} />,- renderDescription: (thread, { projectTitle }) => {- const modelInstanceId =- thread.session?.providerInstanceId ?? thread.modelSelection.instanceId;- const providerEntry =- providerEntryByEnvironmentAndInstanceId.get(- `${thread.environmentId}:${modelInstanceId}`,- ) ?? null;- return (- <ThreadCommandSubtitle- environmentId={thread.environmentId}- projectCwd={projectCwdById.get(thread.projectId) ?? null}- projectFaviconPath={projectFaviconPathById.get(thread.projectId) ?? null}- projectTitle={projectTitle ?? null}- branch={thread.branch}- worktreePath={thread.worktreePath}- isCurrent={thread.id === activeThreadId}- driverKind={providerEntry?.driverKind ?? null}- providerDisplayName={- thread.session?.providerName ?? providerEntry?.displayName ?? modelInstanceId- }- />- );- },- getContentMatch: (thread) => {- const match = threadContentMatchByKey.get(- threadSearchMatchKey({- environmentId: thread.environmentId,- threadId: thread.id,- }),- );- return match && (match.source === "user" || match.source === "assistant")- ? {- source: match.source,- snippet: match.snippet,- query: threadSearchQuery,- }- : undefined;- },- runThread: async (thread) => {- await navigate({- to: "/$environmentId/$threadId",- params: buildThreadRouteParams(scopeThreadRef(thread.environmentId, thread.id)),- });- },- }),- [- activeThreadId,- clientSettings.sidebarThreadSortOrder,- navigate,- projectCwdById,- projectFaviconPathById,- projectTitleById,- providerEntryByEnvironmentAndInstanceId,- threadContentMatchByKey,- threadSearchQuery,- threads,- ],- );+ const allThreadItems: ReturnType<typeof buildThreadActionItems> = [];const recentThreadItems = allThreadItems.slice(0, RECENT_THREAD_LIMIT);const pushPaletteView = useCallback(@@ -1243,8 +1081,8 @@ function OpenCommandPaletteDialog(props: {const openSourceControlSettings = useCallback(() => {setOpen(false);- void navigate({ to: "/settings/source-control" });- }, [navigate, setOpen]);+ openSettings("source-control");+ }, [setOpen]);const buildAddProjectSourceGroups = useCallback((@@ -1486,44 +1324,16 @@ function OpenCommandPaletteDialog(props: {const actionItems: Array<CommandPaletteActionItem | CommandPaletteSubmenuItem> = [];- if (projects.length > 0) {- const activeProjectTitle =- projectPickerEntries.find((entry) => entry.isPreferred)?.group.displayName ??- (currentProjectId ? (projectTitleById.get(currentProjectId) ?? null) : null);-- if (activeProjectTitle) {- actionItems.push({- kind: "action",- value: "action:new-thread",- searchTerms: ["new thread", "chat", "create", "draft"],- title: (- <>- New thread in <span className="font-semibold">{activeProjectTitle}</span>- </>- ),- icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,- shortcutCommand: "chat.new",- run: async () => {- await startNewThreadFromContext({- activeDraftThread,- activeThread: activeThread ?? undefined,- defaultProjectRef,- handleNewThread,- });- },- });- }-- actionItems.push({- kind: "submenu",- value: "action:new-thread-in",- searchTerms: ["new thread", "project", "pick", "choose", "select"],- title: "New thread in...",- icon: <SquarePenIcon className={ITEM_ICON_CLASS} />,- addonIcon: <SquarePenIcon className={ADDON_ICON_CLASS} />,- groups: [{ value: "projects", label: "Projects", items: projectThreadItems }],- });- }+ actionItems.push(+ buildModelPickerCommandPaletteAction({+ composerHandle: composerHandleRef?.current ?? null,+ closePalette: () => setOpen(false),+ scheduleAfterClose: (openModelPicker) => {+ window.requestAnimationFrame(openModelPicker);+ },+ icon: <BotIcon className={ITEM_ICON_CLASS} />,+ }),+ );actionItems.push({kind: "action",@@ -1612,6 +1422,28 @@ function OpenCommandPaletteDialog(props: {},});+ actionItems.push({+ kind: "action",+ value: "action:plugins",+ searchTerms: ["plugins", "mcp", "tools", "executor", "composio"],+ title: "Open plugins",+ icon: <PuzzleIcon className={ITEM_ICON_CLASS} />,+ run: async () => {+ openPlugins();+ },+ });++ actionItems.push({+ kind: "action",+ value: "action:usage",+ searchTerms: ["usage", "limits", "quota", "plan", "subscription"],+ title: "Open usage",+ icon: <ChartNoAxesColumnIcon className={ITEM_ICON_CLASS} />,+ run: async () => {+ openUsage();+ },+ });+actionItems.push({kind: "action",value: "action:settings",@@ -1619,7 +1451,7 @@ function OpenCommandPaletteDialog(props: {title: "Open settings",icon: <SettingsIcon className={ITEM_ICON_CLASS} />,run: async () => {- await navigate({ to: "/settings" });+ openSettings();},});@@ -1723,34 +1555,7 @@ function OpenCommandPaletteDialog(props: {cwd,);if (existing) {- const latestThread = getLatestThreadForProject(- threads.filter((thread) => thread.environmentId === existing.environmentId),- existing.id,- clientSettings.sidebarThreadSortOrder,- );- if (latestThread) {- await navigate({- to: "/$environmentId/$threadId",- params: buildThreadRouteParams(- scopeThreadRef(latestThread.environmentId, latestThread.id),- ),- });- } else {- const navigationResult = await settlePromise(() =>- handleNewThread(scopeProjectRef(existing.environmentId, existing.id)),- );- if (navigationResult._tag === "Failure") {- const error = squashAtomCommandFailure(navigationResult);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to open project",- description: error instanceof Error ? error.message : "An error occurred.",- }),- );- return;- }- }+ await navigate({ to: "/" });setOpen(false);return;}@@ -1787,24 +1592,10 @@ function OpenCommandPaletteDialog(props: {return;}- const navigationResult = await settlePromise(() =>- handleNewThread(scopeProjectRef(input.environmentId, projectId)),- );- if (navigationResult._tag === "Failure") {- const error = squashAtomCommandFailure(navigationResult);- toastManager.add(- stackedThreadToast({- type: "error",- title: "Failed to add project",- description: error instanceof Error ? error.message : "An error occurred.",- }),- );- return;- }+ await navigate({ to: "/" });setOpen(false);},[- handleNewThread,createProject,environments,navigate,diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsxindex d448a720e..37ec6b552 100644--- a/apps/web/src/components/GitActionsControl.tsx+++ b/apps/web/src/components/GitActionsControl.tsx@@ -15,7 +15,6 @@ import type {SourceControlRepositoryVisibility,VcsStatusResult,} from "@t3tools/contracts";-import { useNavigate } from "@tanstack/react-router";import * as Option from "effect/Option";import { useCallback, useEffect, useEffectEvent, useMemo, useRef, useState } from "react";import { flushSync } from "react-dom";@@ -92,6 +91,7 @@ import { type DraftId, useComposerDraftStore } from "~/composerDraftStore";import { readLocalApi } from "~/localApi";import { getSourceControlPresentation } from "~/sourceControlPresentation";import { openPullRequestLink } from "~/lib/openPullRequestLink";+import { openSettings } from "~/settingsDialogStore";interface GitActionsControlProps {gitCwd: string | null;@@ -380,7 +380,6 @@ interface PublishRepositoryDialogProps {}function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {- const navigate = useNavigate();const sourceControlDiscovery = useEnvironmentQuery(props.environmentId === null? null@@ -547,8 +546,8 @@ function PublishRepositoryDialog(props: PublishRepositoryDialogProps) {const openSourceControlSettings = useCallback(() => {handleOpenChange(false);- void navigate({ to: "/settings/source-control" });- }, [handleOpenChange, navigate]);+ openSettings("source-control");+ }, [handleOpenChange]);return (<Dialog open={props.open} onOpenChange={handleOpenChange}>diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsxindex 6d6e26c18..72a0fc7a8 100644--- a/apps/web/src/components/LegacySidebar.tsx+++ b/apps/web/src/components/LegacySidebar.tsx@@ -3567,7 +3567,7 @@ export default function LegacySidebar() {.downloadUpdate().then((result) => {if (result.completed) {- showDesktopUpdateDownloadedToast(bridge, result.state);+ showDesktopUpdateDownloadedToast();}if (!shouldToastDesktopUpdateActionResult(result)) return;const actionError = getDesktopUpdateActionError(result);diff --git a/apps/web/src/components/ProviderUpdateLaunchNotification.tsx b/apps/web/src/components/ProviderUpdateLaunchNotification.tsxindex 2292a2c45..411a9141a 100644--- a/apps/web/src/components/ProviderUpdateLaunchNotification.tsx+++ b/apps/web/src/components/ProviderUpdateLaunchNotification.tsx@@ -1,4 +1,3 @@-import { useNavigate } from "@tanstack/react-router";import { DownloadIcon } from "lucide-react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";@@ -15,6 +14,7 @@ import {} from "./ProviderUpdateLaunchNotification.logic";import { ProviderUpdatePrimaryNotification } from "./ProviderUpdatePrimaryNotification";import { stackedThreadToast, toastManager } from "./ui/toast";+import { openSettings } from "~/settingsDialogStore";/*** True when a desktop-local secondary backend (the parallel WSL backend) is@@ -56,7 +56,6 @@ type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;const SETTLING_GRACE_MS = 30_000;function ProviderUpdateEnvironmentsNotification() {- const navigate = useNavigate();const { groups, isAnySettling } = useLocalEnvironmentUpdateGroups();const { dismissedNotificationKeys, dismissNotificationKey } =useDismissedProviderUpdateNotificationKeys();@@ -113,8 +112,8 @@ function ProviderUpdateEnvironmentsNotification() {toastManager.close(active.toastId);activeToastRef.current = null;}- void navigate({ to: "/settings/providers" });- }, [navigate]);+ openSettings("providers");+ }, []);useEffect(() => {// Whether a fresh prompt can actually be shown for the current update set.diff --git a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsxindex 639f07c38..cfa086202 100644--- a/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx+++ b/apps/web/src/components/ProviderUpdatePrimaryNotification.tsx@@ -1,4 +1,3 @@-import { useNavigate } from "@tanstack/react-router";import { useAtomValue } from "@effect/atom-react";import { DownloadIcon } from "lucide-react";import { useCallback, useEffect, useMemo, useRef } from "react";@@ -22,6 +21,7 @@ import {} from "./ProviderUpdateLaunchNotification.logic";import { hiddenToastActionProps, stackedThreadToast, toastManager } from "./ui/toast";import { useAtomCommand } from "../state/use-atom-command";+import { openSettings } from "~/settingsDialogStore";const seenProviderUpdateNotificationKeys = new Set<string>();type ProviderUpdateToastId = ReturnType<typeof toastManager.add>;@@ -102,7 +102,6 @@ function addProviderUpdateToast(input: {* per-environment split is gated behind WSL presence.*/export function ProviderUpdatePrimaryNotification() {- const navigate = useNavigate();const providers = useAtomValue(primaryServerProvidersAtom);const primaryEnvironment = usePrimaryEnvironment();const updateProvider = useAtomCommand(serverEnvironment.updateProvider, {@@ -135,25 +134,21 @@ export function ProviderUpdatePrimaryNotification() {[providers, updateProviders],);- const openProviderSettings = useCallback(- (toastId?: ProviderUpdateToastId) => {- const activeToast = activeToastRef.current;- if (toastId !== undefined) {- toastManager.close(toastId);- } else if (activeToast?.kind === "prompt") {- toastManager.close(activeToast.toastId);- }- if (- activeToast &&- (toastId === undefined ||- (activeToast.kind === "prompt" && activeToast.toastId === toastId))- ) {- activeToastRef.current = null;- }- void navigate({ to: "/settings/providers" });- },- [navigate],- );+ const openProviderSettings = useCallback((toastId?: ProviderUpdateToastId) => {+ const activeToast = activeToastRef.current;+ if (toastId !== undefined) {+ toastManager.close(toastId);+ } else if (activeToast?.kind === "prompt") {+ toastManager.close(activeToast.toastId);+ }+ if (+ activeToast &&+ (toastId === undefined || (activeToast.kind === "prompt" && activeToast.toastId === toastId))+ ) {+ activeToastRef.current = null;+ }+ openSettings("providers");+ }, []);useEffect(() => {const activeToast = activeToastRef.current;diff --git a/apps/web/src/components/RightPanelTabs.test.tsx b/apps/web/src/components/RightPanelTabs.test.tsxindex 7b0ae9b4c..84c80d05d 100644--- a/apps/web/src/components/RightPanelTabs.test.tsx+++ b/apps/web/src/components/RightPanelTabs.test.tsx@@ -105,7 +105,6 @@ function renderTabs(onCopyFilePath={() => undefined}onAddBrowser={() => undefined}onAddTerminal={() => undefined}- onAddPullRequest={() => undefined}onAddDiff={() => undefined}onAddFiles={() => undefined}onAddAgents={() => undefined}@@ -114,7 +113,6 @@ function renderTabs(terminalAvailable={false}diffAvailable={false}filesAvailable={false}- pullRequestAvailable={false}agentsAvailable={false}><div>content</div>diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsxindex 9d057a3d2..38a50dd76 100644--- a/apps/web/src/components/RightPanelTabs.tsx+++ b/apps/web/src/components/RightPanelTabs.tsx@@ -1,10 +1,9 @@-import type { ContextMenuItem, PreviewSessionSnapshot, PullRequestState } from "@t3tools/contracts";+import type { ContextMenuItem, PreviewSessionSnapshot } from "@t3tools/contracts";import { getTerminalLabel } from "@t3tools/shared/terminalLabels";import {Bot,FileDiff,Files,- GitPullRequest,Globe2,Plus,TerminalSquare,@@ -72,34 +71,22 @@ interface RightPanelTabsProps {onAddTerminal: () => void;onAddDiff: () => void;onAddFiles: () => void;- onAddPullRequest: () => void;onAddAgents: () => void;browserAvailable: boolean;terminalAvailable: boolean;diffAvailable: boolean;filesAvailable: boolean;- pullRequestAvailable: boolean;agentsAvailable: boolean;- pullRequestStatuses?: Readonly<Record<string, PullRequestTabStatus>>;/** Running + waiting subagents; badges the Agents card in the empty state. */liveAgentCount: number;children: ReactNode;}-export interface PullRequestTabStatus {- projectId: string;- repository: string;- number: number;- state: PullRequestState;- isDraft: boolean;-}-const SURFACE_DISABLED_REASONS = {- browser: "Browser previews are only available in the T3 Code desktop app.",+ browser: "Browser previews are only available in the Akeru Bot desktop app.",terminal: "Terminal surfaces are only available from a project thread.",files: "Files are only available when a project is open.",diff: "Diff is only available for server threads in Git repositories.",- pullRequest: "This thread's branch has no pull request yet.",agents: "Agents are only available from a thread.",} as const;@@ -121,7 +108,6 @@ const SURFACE_UNAVAILABLE_HINTS = {terminal: "Available when a project is open.",files: "Available when a project is open.",diff: "Available for Git repositories.",- pullRequest: "No pull request on this branch yet.",agents: "Available from a thread.",} as const;@@ -250,13 +236,11 @@ function RightPanelEmptyState(props: {onAddTerminal: () => void;onAddDiff: () => void;onAddFiles: () => void;- onAddPullRequest: () => void;onAddAgents: () => void;browserAvailable: boolean;terminalAvailable: boolean;diffAvailable: boolean;filesAvailable: boolean;- pullRequestAvailable: boolean;agentsAvailable: boolean;liveAgentCount: number;}) {@@ -304,16 +288,6 @@ function RightPanelEmptyState(props: {onClick: props.onAddDiff,badgeCount: 0,},- {- label: "Pull request",- description: "Open this branch's pull request.",- icon: GitPullRequest,- shortcut: "P",- available: props.pullRequestAvailable,- disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequest,- onClick: props.onAddPullRequest,- badgeCount: 0,- },{label: "Agents",description: "Follow subagents and workflows.",@@ -545,13 +519,11 @@ function SurfaceIcon({sessions,desktopByTabId,theme,- pullRequestStatuses,}: {surface: RightPanelSurface;sessions: Readonly<Record<string, PreviewSessionSnapshot>>;desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;theme: "light" | "dark";- pullRequestStatuses: Readonly<Record<string, PullRequestTabStatus>> | undefined;}) {switch (surface.kind) {case "preview": {@@ -577,20 +549,8 @@ function SurfaceIcon({);case "terminal":return <TerminalSquare className="size-3 shrink-0" />;- case "pull-request": {- const status = pullRequestStatuses?.[surface.id] ?? null;- const toneClassName =- status?.state === "merged"- ? "text-violet-600 dark:text-violet-300/90"- : status?.state === "closed"- ? "text-red-600 dark:text-red-300/90"- : status?.isDraft- ? "text-zinc-500 dark:text-zinc-400/80"- : status?.state === "open"- ? "text-emerald-600 dark:text-emerald-300/90"- : "text-muted-foreground";- return <GitPullRequest className={cn("size-3 shrink-0", toneClassName)} />;- }+ case "pull-request":+ return null;case "agents":return <Bot className="size-3 shrink-0" />;}@@ -635,14 +595,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) {disabledReason: SURFACE_DISABLED_REASONS.diff,onClick: props.onAddDiff,},- {- label: "Pull request",- icon: GitPullRequest,- shortcut: "P",- available: props.pullRequestAvailable,- disabledReason: SURFACE_DISABLED_REASONS.pullRequest,- onClick: props.onAddPullRequest,- },{label: "Agents",icon: Bot,@@ -832,7 +784,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) {sessions={props.previewSessions}desktopByTabId={props.desktopByTabId}theme={resolvedTheme}- pullRequestStatuses={props.pullRequestStatuses}/>{pending ? (<span@@ -936,13 +887,11 @@ export function RightPanelTabs(props: RightPanelTabsProps) {onAddTerminal={props.onAddTerminal}onAddDiff={props.onAddDiff}onAddFiles={props.onAddFiles}- onAddPullRequest={props.onAddPullRequest}onAddAgents={props.onAddAgents}browserAvailable={props.browserAvailable}terminalAvailable={props.terminalAvailable}diffAvailable={props.diffAvailable}filesAvailable={props.filesAvailable}- pullRequestAvailable={props.pullRequestAvailable}agentsAvailable={props.agentsAvailable}liveAgentCount={props.liveAgentCount}/>diff --git a/apps/web/src/components/Sidebar.logic.ts b/apps/web/src/components/Sidebar.logic.tsindex 07fb4bc8a..d0abcf49b 100644--- a/apps/web/src/components/Sidebar.logic.ts+++ b/apps/web/src/components/Sidebar.logic.ts@@ -506,6 +506,67 @@ export function resolveSidebarThreadStatus(thread: SidebarThreadStatusInput): Sireturn "ready";}+export interface SidebarProjectSection<TGroup, TThread> {+ group: TGroup;+ threads: TThread[];+}++/**+ * Splits the already-sorted active thread list into per-project sections for+ * the grouped sidebar presentation. Section order follows the given project+ * group order, thread order inside a section follows the input order, and+ * groups with no active threads get no section. Threads whose project is in+ * no known group (project removed, or its environment not loaded) come back+ * in `ungroupedThreads`, still in input order: they keep rendering after the+ * sections, without a header, because the shell carries nothing truthful to+ * label them with.+ */+export function buildSidebarProjectSections<+ TGroup extends {+ readonly projectKey: string;+ readonly memberProjectRefs: readonly { environmentId: string; projectId: string }[];+ },+ TThread extends { readonly environmentId: string; readonly projectId: string },+>(input: {+ groups: readonly TGroup[];+ threads: readonly TThread[];+}): {+ sections: SidebarProjectSection<TGroup, TThread>[];+ ungroupedThreads: TThread[];+} {+ const groupKeyByProjectRef = new Map<string, string>();+ for (const group of input.groups) {+ for (const projectRef of group.memberProjectRefs) {+ groupKeyByProjectRef.set(+ `${projectRef.environmentId}\0${projectRef.projectId}`,+ group.projectKey,+ );+ }+ }+ const threadsByGroupKey = new Map<string, TThread[]>();+ const ungroupedThreads: TThread[] = [];+ for (const thread of input.threads) {+ const groupKey = groupKeyByProjectRef.get(`${thread.environmentId}\0${thread.projectId}`);+ if (groupKey === undefined) {+ ungroupedThreads.push(thread);+ continue;+ }+ const existing = threadsByGroupKey.get(groupKey);+ if (existing) {+ existing.push(thread);+ } else {+ threadsByGroupKey.set(groupKey, [thread]);+ }+ }+ const sections: SidebarProjectSection<TGroup, TThread>[] = [];+ for (const group of input.groups) {+ const groupThreads = threadsByGroupKey.get(group.projectKey);+ if (groupThreads === undefined) continue;+ sections.push({ group, threads: groupThreads });+ }+ return { sections, ungroupedThreads };+}+/** NaN-safe Date.parse for sort comparators: a malformed timestamp must notpoison the whole ordering, so it sinks to the epoch instead. */export function parseTimestampMs(isoDate: string): number {diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsxindex 63681a548..98a090d7a 100644--- a/apps/web/src/components/Sidebar.tsx+++ b/apps/web/src/components/Sidebar.tsx@@ -124,6 +124,7 @@ import { cn } from "~/lib/utils";import { buildThreadActionMenuItems } from "./threadActionMenu.logic";import {animatePinnedLayoutChanges,+ buildSidebarProjectSections,buildBulkTitleRegenerationContextMenuItem,formatWorkingDurationLabel,firstValidTimestampMs,@@ -719,6 +720,10 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {// the user visits the thread.wokeAt: string | null;isActive: boolean;+ // False for cards rendered under their project's section header, where a+ // per-row project label would repeat the header. Pinned and ungrouped+ // rows keep their own project context.+ showProjectContext: boolean;openPullRequestsInRightPanel: boolean;jumpLabel: string | null;currentEnvironmentId: string | null;@@ -1414,21 +1419,27 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {><div className="relative z-10 h-[4.875rem] px-[var(--sidebar-row-content-inset)] py-[var(--sidebar-content-inset)]"><div className="flex h-5 min-w-0 items-center gap-1.5">- <ProjectFavicon- environmentId={thread.environmentId}- cwd={props.projectCwd ?? ""}- faviconPath={props.projectFaviconPath}- className="size-4 shrink-0"- />- {props.projectTitle ? (- <span- className={cn(- "min-w-0 flex-1 truncate text-secondary-label text-xs",- shouldRecede ? "font-normal" : "font-medium",+ {props.showProjectContext ? (+ <>+ <ProjectFavicon+ environmentId={thread.environmentId}+ cwd={props.projectCwd ?? ""}+ faviconPath={props.projectFaviconPath}+ className="size-4 shrink-0"+ />+ {props.projectTitle ? (+ <span+ className={cn(+ "min-w-0 flex-1 truncate text-secondary-label text-xs",+ shouldRecede ? "font-normal" : "font-medium",+ )}+ >+ {props.projectTitle}+ </span>+ ) : (+ <span className="flex-1" />)}- >- {props.projectTitle}- </span>+ </>) : (<span className="flex-1" />)}@@ -2117,13 +2128,32 @@ export default function Sidebar() {threads,]);+ // Per-project sections for the active list. A pure regrouping of the+ // already-sorted active threads: section order follows the project group+ // order, thread order inside a section is untouched, and threads whose+ // project resolves to no loaded group render after the sections without a+ // header (the shell has nothing truthful to label them with).+ const { sections: activeProjectSections, ungroupedThreads: ungroupedActiveThreads } = useMemo(+ () => buildSidebarProjectSections({ groups: projectGroups, threads: activeThreads }),+ [activeThreads, projectGroups],+ );+ // Keyboard traversal, jump hints, and shift-range selection follow VISUAL+ // order, which is now the sectioned order, not the raw sorted order.+ const sectionedActiveThreads = useMemo(+ () => [+ ...activeProjectSections.flatMap((section) => section.threads),+ ...ungroupedActiveThreads,+ ],+ [activeProjectSections, ungroupedActiveThreads],+ );+const threadSearchInputRef = useRef<HTMLInputElement>(null);const [threadSearchQuery, setThreadSearchQuery] = useState("");const [activeSearchResultIndex, setActiveSearchResultIndex] = useState(0);const isSearchingThreads = threadSearchQuery.trim().length > 0;const searchableThreads = useMemo(- () => [...pinnedThreads, ...activeThreads, ...snoozedThreads, ...settledThreads],- [activeThreads, pinnedThreads, settledThreads, snoozedThreads],+ () => [...pinnedThreads, ...sectionedActiveThreads, ...snoozedThreads, ...settledThreads],+ [sectionedActiveThreads, pinnedThreads, settledThreads, snoozedThreads],);const threadSearchResults = useMemo(() => searchSidebarThreadsByTitle(searchableThreads, threadSearchQuery),@@ -2241,8 +2271,13 @@ export default function Sidebar() {}, [routeThreadKey, snoozedShelfExpanded, snoozedThreads]);const orderedThreads = useMemo(- () => [...pinnedThreads, ...activeThreads, ...visibleSnoozedThreads, ...renderedSettledThreads],- [pinnedThreads, activeThreads, visibleSnoozedThreads, renderedSettledThreads],+ () => [+ ...pinnedThreads,+ ...sectionedActiveThreads,+ ...visibleSnoozedThreads,+ ...renderedSettledThreads,+ ],+ [pinnedThreads, sectionedActiveThreads, visibleSnoozedThreads, renderedSettledThreads],);const orderedThreadKeys = useMemo(() =>@@ -3662,6 +3697,7 @@ export default function Sidebar() {thread: EnvironmentThreadShell,section: "pinned" | "active" | "snoozed" | "settled",sortable?: SortablePinnedRowBag,+ options?: { showProjectContext?: boolean },) => {const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id),@@ -3721,6 +3757,7 @@ export default function Sidebar() {// rows resolve to null on their own.wokeAt={threadWokeAt(thread, { now: snoozeNow })}isActive={routeThreadKey === threadKey}+ showProjectContext={options?.showProjectContext ?? true}openPullRequestsInRightPanel={routeThreadRef !== null}jumpLabel={showThreadJumpHints ? (jumpLabelByKey.get(threadKey) ?? null) : null@@ -3832,7 +3869,40 @@ export default function Sidebar() {/>,);}- for (const thread of activeThreads) {+ // Active threads render under one header per project group+ // (same source as the scope menu), then any threads whose+ // project no longer resolves, headerless. Headers are+ // labels, not controls — scoping and project settings keep+ // their existing entry points.+ for (const section of activeProjectSections) {+ items.push(+ <li+ key={`project-section-${section.group.projectKey}`}+ data-thread-selection-safe+ data-testid="sidebar-project-section"+ className="list-none"+ >+ <div className="mb-0.5 mt-2 flex items-center gap-2 px-2.5">+ <ProjectFavicon+ environmentId={section.group.environmentId}+ cwd={section.group.workspaceRoot}+ faviconPath={section.group.faviconPath}+ className="size-3.5 shrink-0"+ />+ <span className="min-w-0 truncate text-xs font-medium text-muted-foreground/70">+ {section.group.displayName}+ </span>+ <span className="h-px flex-1 bg-sidebar-border/60" />+ </div>+ </li>,+ );+ for (const thread of section.threads) {+ items.push(+ renderThreadRow(thread, "active", undefined, { showProjectContext: false }),+ );+ }+ }+ for (const thread of ungroupedActiveThreads) {items.push(renderThreadRow(thread, "active"));}// Snoozed shelf: between the inbox and Settled — out of thediff --git a/apps/web/src/components/ThreadStatusIndicators.tsx b/apps/web/src/components/ThreadStatusIndicators.tsxindex 843d310dd..79f19fd32 100644--- a/apps/web/src/components/ThreadStatusIndicators.tsx+++ b/apps/web/src/components/ThreadStatusIndicators.tsx@@ -3,7 +3,6 @@ import {scopedThreadKey,scopeThreadRef,} from "@t3tools/client-runtime/environment";-import { pullRequestDetailToVcsStatus } from "@t3tools/client-runtime/state/pull-requests";import type { EnvironmentId, ThreadLinkedPullRequest, VcsStatusResult } from "@t3tools/contracts";import { Atom } from "effect/unstable/reactivity";import { CloudIcon, FolderGit2Icon, GitPullRequestIcon, TerminalIcon } from "lucide-react";@@ -12,7 +11,6 @@ import { appAtomRegistry } from "../rpc/atomRegistry";import { useEnvironment, usePrimaryEnvironmentId } from "../state/environments";import { useProject } from "../state/entities";import { useEnvironmentQuery } from "../state/query";-import { linkedPullRequestDetailAtom } from "../state/pullRequests";import { useThreadRunningTerminalIds } from "../state/terminalSessions";import { vcsEnvironment } from "../state/vcs";import { useUiStateStore } from "../uiStateStore";@@ -45,36 +43,10 @@ export interface LinkedThreadPullRequestStatus {}export function useLinkedThreadPullRequest(- environmentId: EnvironmentId | null,- linkedPullRequest: ThreadLinkedPullRequest | null | undefined,+ _environmentId: EnvironmentId | null,+ _linkedPullRequest: ThreadLinkedPullRequest | null | undefined,): LinkedThreadPullRequestStatus | null {- const detail = useEnvironmentQuery(- environmentId === null || linkedPullRequest == null- ? null- : linkedPullRequestDetailAtom({- environmentId,- input: {- projectId: linkedPullRequest.projectId,- repository: linkedPullRequest.repository,- number: linkedPullRequest.number,- },- }),- ).data;-- return useMemo(- () =>- detail === null- ? null- : {- pr: pullRequestDetailToVcsStatus(detail),- sourceControlProvider: {- kind: detail.provider,- name: detail.provider,- baseUrl: "",- },- },- [detail],- );+ return null;}export function settledPrHoverColorClass(state: NonNullable<ThreadPr>["state"]): string {diff --git a/apps/web/src/components/chat/ChatComposer.controls.test.tsx b/apps/web/src/components/chat/ChatComposer.controls.test.tsxnew file mode 100644index 000000000..2236d397e--- /dev/null+++ b/apps/web/src/components/chat/ChatComposer.controls.test.tsx@@ -0,0 +1,203 @@+import { ApprovalRequestId, OrchestrationProposedPlanId, ThreadId } from "@t3tools/contracts";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vite-plus/test";++vi.mock("../../lib/composerPathSearchState", () => ({+ useComposerPathSearch: () => ({ entries: [], error: null, isPending: false }),+}));+vi.mock("../../hooks/useMediaQuery", () => ({+ useMediaQuery: () => false,+ useIsMobile: () => false,+}));+vi.mock("~/hooks/useSettings", () => ({+ useEnvironmentIdentificationMode: () => "color",+}));+vi.mock("../SidebarStageBackdrop", () => ({+ useSidebarStageBackdropVariant: () => null,+ StageBackdropButtonArt: () => null,+}));+vi.mock("../ComposerPromptEditor", () => ({+ ComposerPromptEditor: (props: { placeholder: string; disabled?: boolean }) => (+ <div+ data-composer-prompt-editor="true"+ data-placeholder={props.placeholder}+ aria-disabled={props.disabled ? "true" : "false"}+ />+ ),+}));++import {+ composerTestEnvironmentId,+ composerTestModelName,+ makeChatComposerProps,+ makeComposerTestThread,+} from "../../test/chatComposerProps";+import { ChatComposer } from "./ChatComposer";++const environmentId = composerTestEnvironmentId;++/** Launch controls LEO-215 removes from the primary composer. */+function expectNoLaunchControls(markup: string) {+ // Model picker trigger (the trigger label rendered the model name). The+ // picker itself survives as a closed dialog, so no content is in markup.+ expect(markup).not.toContain(composerTestModelName);+ expect(markup).not.toContain("data-model-picker-content");+ expect(markup).not.toContain("data-chat-provider-model-picker");+ // Runtime/permission mode select.+ expect(markup).not.toContain("Runtime mode");+ expect(markup).not.toContain("Full access");+ expect(markup).not.toContain("Supervised");+ expect(markup).not.toContain("Auto-accept edits");+ // Plan/Build interaction toggle and reasoning traits.+ expect(markup).not.toContain(">Plan<");+ expect(markup).not.toContain(">Build<");+ expect(markup).not.toContain("plan mode");+ // Compact overflow menu that hosted the same controls.+ expect(markup).not.toContain("More composer controls");+ // Workspace/branch/worktree chips never render inside the composer.+ expect(markup).not.toContain("Local checkout");+ expect(markup).not.toContain("Current checkout");+ expect(markup).not.toContain("New worktree");+}++describe("ChatComposer launch-control removal", () => {+ it("renders a new draft as a plain chat box with send but no launch controls", () => {+ const markup = renderToStaticMarkup(<ChatComposer {...makeChatComposerProps()} />);++ expect(markup).toContain('data-chat-composer-footer="true"');+ expect(markup).toContain('aria-label="Send message"');+ expect(markup).toContain("Ask anything, @tag files/folders, $use skills, or / for commands");+ expectNoLaunchControls(markup);+ });++ it("renders an existing running thread with stop control and no launch controls", () => {+ const markup = renderToStaticMarkup(+ <ChatComposer+ {...makeChatComposerProps({+ composerDraftTarget: {+ environmentId,+ threadId: ThreadId.make("thread-1"),+ },+ routeKind: "server",+ draftId: null,+ isServerThread: true,+ isLocalDraftThread: false,+ activeThread: makeComposerTestThread({+ worktreePath: "/repo/.worktrees/t3-1",+ branch: "main",+ }),+ phase: "running",+ })}+ />,+ );++ expect(markup).toContain('aria-label="Stop generation"');+ expectNoLaunchControls(markup);+ // The thread keeps its worktree, but no chip renders for it.+ expect(markup).not.toContain(".worktrees/t3-1");+ expect(markup).not.toContain(">main<");+ });++ it("keeps the pending-approval surface reachable", () => {+ const approval = {+ requestId: ApprovalRequestId.make("approval-1"),+ requestKind: "command" as const,+ createdAt: "2026-03-01T00:00:00.000Z",+ detail: "rm -rf node_modules",+ };+ const markup = renderToStaticMarkup(+ <ChatComposer+ {...makeChatComposerProps({+ composerDraftTarget: {+ environmentId,+ threadId: ThreadId.make("thread-1"),+ },+ routeKind: "server",+ draftId: null,+ isServerThread: true,+ isLocalDraftThread: false,+ phase: "running",+ activePendingApproval: approval,+ pendingApprovals: [approval],+ })}+ />,+ );++ expect(markup).toContain("rm -rf node_modules");+ expect(markup).toContain("Approve");+ expectNoLaunchControls(markup);+ });++ it("keeps the pending user-input questions reachable", () => {+ const pendingUserInput = {+ requestId: ApprovalRequestId.make("request-1"),+ createdAt: "2026-03-01T00:00:00.000Z",+ questions: [+ {+ id: "question-1",+ header: "Approach",+ question: "Which approach should the migration take?",+ options: [{ label: "Incremental", description: "Move one module at a time" }],+ multiSelect: false,+ },+ ],+ };+ const markup = renderToStaticMarkup(+ <ChatComposer+ {...makeChatComposerProps({+ composerDraftTarget: {+ environmentId,+ threadId: ThreadId.make("thread-1"),+ },+ routeKind: "server",+ draftId: null,+ isServerThread: true,+ isLocalDraftThread: false,+ pendingUserInputs: [pendingUserInput],+ activePendingProgress: {+ questionIndex: 0,+ isLastQuestion: true,+ canAdvance: true,+ customAnswer: "",+ activeQuestion: { id: "question-1" },+ },+ })}+ />,+ );++ expect(markup).toContain("Which approach should the migration take?");+ expect(markup).toContain("Incremental");+ expectNoLaunchControls(markup);+ });++ it("keeps the plan follow-up actions reachable", () => {+ const markup = renderToStaticMarkup(+ <ChatComposer+ {...makeChatComposerProps({+ composerDraftTarget: {+ environmentId,+ threadId: ThreadId.make("thread-1"),+ },+ routeKind: "server",+ draftId: null,+ isServerThread: true,+ isLocalDraftThread: false,+ showPlanFollowUpPrompt: true,+ activeProposedPlan: {+ id: OrchestrationProposedPlanId.make("plan-1"),+ turnId: null,+ planMarkdown: "# Ship the widget\n1. Do the thing",+ implementedAt: null,+ implementationThreadId: null,+ createdAt: "2026-03-01T00:00:00.000Z",+ updatedAt: "2026-03-01T00:00:00.000Z",+ },+ })}+ />,+ );++ expect(markup).toContain(">Implement</button>");+ expect(markup).toContain('aria-label="Implementation actions"');+ expectNoLaunchControls(markup);+ });+});diff --git a/apps/web/src/components/chat/ChatComposer.modelPickerDialog.test.tsx b/apps/web/src/components/chat/ChatComposer.modelPickerDialog.test.tsxnew file mode 100644index 000000000..866cc26e4--- /dev/null+++ b/apps/web/src/components/chat/ChatComposer.modelPickerDialog.test.tsx@@ -0,0 +1,207 @@+import type { ReactElement } from "react";+import { beforeEach, describe, expect, it, vi } from "vite-plus/test";++import { visitElements } from "../../test/reactElementTree";+import { reactHookHarness as hooks } from "../../test/reactHookHarness";++vi.mock("react", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react")>();+ const { reactHookHarness } = await import("../../test/reactHookHarness");+ return {+ ...actual,+ useCallback: reactHookHarness.useCallback,+ useMemo: reactHookHarness.useMemo,+ useRef: reactHookHarness.useRef,+ useState: reactHookHarness.useState,+ useEffect: () => {},+ useLayoutEffect: () => {},+ useDebugValue: () => {},+ useImperativeHandle: (+ ref: { current: unknown } | ((value: unknown) => void) | null,+ create: () => unknown,+ ) => {+ if (typeof ref === "function") {+ ref(create());+ } else if (ref) {+ ref.current = create();+ }+ },+ useSyncExternalStore: <Snapshot,>(+ _subscribe: (listener: () => void) => () => void,+ getSnapshot: () => Snapshot,+ ): Snapshot => getSnapshot(),+ };+});++vi.mock("react/compiler-runtime", async () => {+ const { reactHookHarness } = await import("../../test/reactHookHarness");+ return { c: reactHookHarness.useMemoCache };+});++// Zustand hooks resolve React from node_modules, where the plain-function+// harness cannot reach. Route their selectors at the live store state instead.+vi.mock("../../composerDraftStore", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../../composerDraftStore")>();+ return {+ ...actual,+ useComposerDraftStore: Object.assign(+ (selector: (state: unknown) => unknown) => selector(actual.useComposerDraftStore.getState()),+ actual.useComposerDraftStore,+ ),+ useComposerThreadDraft: () => ({+ prompt: "",+ images: [],+ nonPersistedImageIds: [],+ persistedAttachments: [],+ terminalContexts: [],+ elementContexts: [],+ previewAnnotations: [],+ reviewComments: [],+ modelSelectionByProvider: {},+ activeProvider: null,+ runtimeMode: null,+ interactionMode: null,+ }),+ useEffectiveComposerModelState: () => ({ selectedModel: "gpt-5-codex", modelOptions: null }),+ };+});+vi.mock("../../promptStashStore", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../../promptStashStore")>();+ return {+ ...actual,+ usePromptStashStore: Object.assign(+ (selector: (state: unknown) => unknown) => selector(actual.usePromptStashStore.getState()),+ actual.usePromptStashStore,+ ),+ };+});+vi.mock("../../lib/attachmentUploadQueue", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../../lib/attachmentUploadQueue")>();+ return {+ ...actual,+ useAttachmentUploadStore: Object.assign(+ (selector: (state: unknown) => unknown) =>+ selector(actual.useAttachmentUploadStore.getState()),+ actual.useAttachmentUploadStore,+ ),+ };+});+vi.mock("../../lib/composerPathSearchState", () => ({+ useComposerPathSearch: () => ({ entries: [], error: null, isPending: false }),+}));+vi.mock("../../hooks/useMediaQuery", () => ({+ useMediaQuery: () => false,+ useIsMobile: () => false,+}));+vi.mock("~/hooks/useSettings", () => ({+ useEnvironmentIdentificationMode: () => "color",+}));+vi.mock("../SidebarStageBackdrop", () => ({+ useSidebarStageBackdropVariant: () => null,+ StageBackdropButtonArt: () => null,+}));+vi.mock("../ComposerPromptEditor", () => ({+ ComposerPromptEditor: () => null,+}));++import { composerTestInstanceId, makeChatComposerProps } from "../../test/chatComposerProps";+import { Dialog, DialogTitle } from "../ui/dialog";+import { ChatComposer, type ChatComposerHandle, type ChatComposerProps } from "./ChatComposer";+import { ModelPickerContent } from "./ModelPickerContent";++type ElementWithProps = ReactElement<Record<string, unknown>>;++function renderComposer(props: ChatComposerProps): ElementWithProps {+ hooks.beginRender();+ const component = (+ ChatComposer as unknown as { type: (p: ChatComposerProps) => ElementWithProps }+ ).type;+ return component(props);+}++function findByType(tree: ElementWithProps, type: unknown): ElementWithProps | null {+ return visitElements(tree, (element) => element.type === type);+}++describe("ChatComposer model picker dialog", () => {+ beforeEach(() => {+ hooks.reset();+ });++ it("opens, reports, and closes the triggerless dialog through the composer handle", () => {+ const composerRef: { current: ChatComposerHandle | null } = { current: null };+ const props = makeChatComposerProps({ composerRef });++ let tree = renderComposer(props);+ const handle = composerRef.current;+ expect(handle).not.toBeNull();+ expect(handle!.isModelPickerOpen()).toBe(false);+ expect(findByType(tree, Dialog)?.props.open).toBe(false);++ // The keyboard shortcut path: ChatView's `modelPicker.toggle` handler+ // calls this exact method on the composer handle.+ handle!.toggleModelPicker();+ tree = renderComposer(props);+ expect(composerRef.current!.isModelPickerOpen()).toBe(true);+ const dialog = findByType(tree, Dialog);+ expect(dialog?.props.open).toBe(true);++ // Accessible name without any visible trigger or title.+ const title = findByType(tree, DialogTitle);+ expect(title?.props.className).toBe("sr-only");+ expect(title?.props.children).toBe("Choose model");++ composerRef.current!.closeModelPicker();+ tree = renderComposer(props);+ expect(composerRef.current!.isModelPickerOpen()).toBe(false);+ expect(findByType(tree, Dialog)?.props.open).toBe(false);++ composerRef.current!.openModelPicker();+ tree = renderComposer(props);+ expect(composerRef.current!.isModelPickerOpen()).toBe(true);+ });++ it("routes a model selection through ChatView's callback and closes the dialog", () => {+ const composerRef: { current: ChatComposerHandle | null } = { current: null };+ const onProviderModelSelect = vi.fn();+ const props = makeChatComposerProps({ composerRef, onProviderModelSelect });++ let tree = renderComposer(props);+ composerRef.current!.openModelPicker();+ tree = renderComposer(props);++ const content = findByType(tree, ModelPickerContent);+ expect(content).not.toBeNull();+ expect(content?.props.activeInstanceId).toBe(composerTestInstanceId);+ expect(content?.props.model).toBe("gpt-5-codex");++ (content!.props.onInstanceModelChange as (instanceId: unknown, model: string) => void)(+ composerTestInstanceId,+ "gpt-5-codex",+ );+ expect(onProviderModelSelect).toHaveBeenCalledWith(composerTestInstanceId, "gpt-5-codex");++ tree = renderComposer(props);+ expect(composerRef.current!.isModelPickerOpen()).toBe(false);+ expect(findByType(tree, Dialog)?.props.open).toBe(false);+ });++ it("keeps the picker closed and unopenable when no provider is available", () => {+ const composerRef: { current: ChatComposerHandle | null } = { current: null };+ const props = makeChatComposerProps({ composerRef, providerStatuses: [] });++ let tree = renderComposer(props);+ expect(findByType(tree, Dialog)).toBeNull();+ expect(composerRef.current!.isModelPickerOpen()).toBe(false);++ composerRef.current!.openModelPicker();+ tree = renderComposer(props);+ expect(findByType(tree, Dialog)).toBeNull();+ expect(composerRef.current!.isModelPickerOpen()).toBe(false);++ composerRef.current!.toggleModelPicker();+ tree = renderComposer(props);+ expect(findByType(tree, Dialog)).toBeNull();+ expect(composerRef.current!.isModelPickerOpen()).toBe(false);+ });+});diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex 6d0ca8a76..a77e5af46 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -4,9 +4,7 @@ import type {ModelSelection,PreviewAnnotationPayload,ProviderApprovalDecision,- ProviderInteractionMode,ResolvedKeybindingsConfig,- RuntimeMode,ScopedThreadRef,ServerProvider,ThreadId,@@ -108,29 +106,21 @@ import {shouldUseCompactComposerFooter,} from "../composerFooterLayout";import { type ComposerPromptEditorHandle, ComposerPromptEditor } from "../ComposerPromptEditor";-import { ProviderModelPicker } from "./ProviderModelPicker";import { type ComposerCommandItem, ComposerCommandMenu } from "./ComposerCommandMenu";+import { ModelPickerContent } from "./ModelPickerContent";import { ComposerPendingApprovalActions } from "./ComposerPendingApprovalActions";-import { CompactComposerControlsMenu } from "./CompactComposerControlsMenu";import { ComposerPrimaryActions } from "./ComposerPrimaryActions";import { ComposerPendingApprovalPanel } from "./ComposerPendingApprovalPanel";import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";-import { ComposerControl, ComposerControlIcon, ComposerSelectControl } from "./ComposerControl";import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";import { searchSlashCommandItems } from "./composerSlashCommandSearch";-import {- getComposerPromptInjectionState,- getComposerProviderState,- renderProviderTraitsMenuContent,- renderProviderTraitsPicker,-} from "./composerProviderState";+import { getComposerPromptInjectionState, getComposerProviderState } from "./composerProviderState";import { ContextWindowMeter } from "./ContextWindowMeter";import { resolveContextWindowModelDisplayName } from "./ContextWindowMeter.logic";import { buildExpandedImagePreview, type ExpandedImagePreview } from "./ExpandedImagePreview";import { basenameOfPath } from "../../pierre-icons";import { cn, randomUUID } from "~/lib/utils";-import { Separator } from "../ui/separator";import {getComposerPromptLengthValidationMessage,getComposerSubmissionValidationMessage,@@ -235,23 +225,11 @@ function ComposerCommandMenuLayer(props: { anchor: HTMLElement | null; children:);}import { Button } from "../ui/button";-import { Select, SelectItem, SelectPopup, SelectValue } from "../ui/select";+import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";import { toastManager } from "../ui/toast";-import {- BotIcon,- CircleAlertIcon,- PencilRulerIcon,- type LucideIcon,- LockIcon,- LockOpenIcon,- PenLineIcon,- RotateCcwIcon,- SparklesIcon,- XIcon,-} from "lucide-react";+import { CircleAlertIcon, RotateCcwIcon, XIcon } from "lucide-react";import { proposedPlanTitle } from "../../proposedPlan";-import { getProviderInteractionModeToggle } from "../../providerModels";import {applyProviderInstanceSettings,deriveProviderInstanceEntries,@@ -276,33 +254,6 @@ import { searchProviderSkills } from "../../providerSkillSearch";import { useMediaQuery } from "../../hooks/useMediaQuery";import type { ReviewCommentContext } from "../../reviewCommentContext";-const runtimeModeConfig: Record<- RuntimeMode,- { label: string; description: string; icon: LucideIcon }-> = {- "approval-required": {- label: "Supervised",- description: "Ask before commands and file changes.",- icon: LockIcon,- },- "auto-accept-edits": {- label: "Auto-accept edits",- description: "Auto-approve edits, ask before other actions.",- icon: PenLineIcon,- },- auto: {- label: "Auto",- description: "Supported providers approve routine actions; others still ask.",- icon: SparklesIcon,- },- "full-access": {- label: "Full access",- description: "Allow commands and edits without prompts.",- icon: LockOpenIcon,- },-};--const runtimeModeOptions = Object.keys(runtimeModeConfig) as RuntimeMode[];const COMPOSER_FLOATING_LAYER_SELECTOR = ['[data-composer-drawer-layer="true"]','[data-slot="popover-popup"]',@@ -344,98 +295,6 @@ function isInsideComposerFloatingLayer(element: Element): boolean {return element.closest(COMPOSER_FLOATING_LAYER_SELECTOR) !== null;}-const ComposerFooterModeControls = memo(function ComposerFooterModeControls(props: {- showInteractionModeToggle: boolean;- interactionMode: ProviderInteractionMode;- runtimeMode: RuntimeMode;- onToggleInteractionMode: () => void;- onRuntimeModeChange: (mode: RuntimeMode) => void;-}) {- const runtimeModeOption = runtimeModeConfig[props.runtimeMode];- const RuntimeModeIcon = runtimeModeOption.icon;- const interactionModeTooltip =- props.interactionMode === "plan"- ? "Plan mode — click to return to normal build mode"- : "Default mode — click to enter plan mode";-- const interactionModeToggle = props.showInteractionModeToggle ? (- <>- <Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />- <Tooltip>- <TooltipTrigger- render={- <ComposerControl- className={cn(- "shrink-0 whitespace-nowrap",- props.interactionMode === "plan"- ? "bg-accent text-accent-foreground hover:bg-accent/80"- : "text-secondary-label hover:text-foreground",- )}- type="button"- onClick={props.onToggleInteractionMode}- aria-label={interactionModeTooltip}- />- }- >- {props.interactionMode === "plan" ? (- <ComposerControlIcon icon={PencilRulerIcon} className="text-current opacity-100" />- ) : (- <ComposerControlIcon icon={BotIcon} opticalSize="large" />- )}- <span className="sr-only sm:not-sr-only">- {props.interactionMode === "plan" ? "Plan" : "Build"}- </span>- </TooltipTrigger>- <TooltipPopup side="top">{interactionModeTooltip}</TooltipPopup>- </Tooltip>- </>- ) : null;-- return (- <>- <Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />-- <Tooltip>- <Select- value={props.runtimeMode}- onValueChange={(value) => props.onRuntimeModeChange(value!)}- >- <TooltipTrigger- render={<ComposerSelectControl className="font-medium" aria-label="Runtime mode" />}- >- <ComposerControlIcon icon={RuntimeModeIcon} />- <SelectValue>{runtimeModeOption.label}</SelectValue>- </TooltipTrigger>- <SelectPopup alignItemWithTrigger={false}>- {runtimeModeOptions.map((mode) => {- const option = runtimeModeConfig[mode];- const OptionIcon = option.icon;- return (- <SelectItem key={mode} value={mode} hideIndicator className="min-w-64 py-2">- <div className="flex min-w-0 items-center gap-3">- <div className="grid min-w-0 flex-1 gap-0.5">- <span className="inline-flex items-center gap-1.5 font-medium text-foreground">- <OptionIcon className="size-3.5 shrink-0 text-muted-foreground" />- {option.label}- </span>- <span className="text-muted-foreground text-xs leading-4">- {option.description}- </span>- </div>- </div>- </SelectItem>- );- })}- </SelectPopup>- </Select>- <TooltipPopup side="top">{runtimeModeOption.description}</TooltipPopup>- </Tooltip>-- {interactionModeToggle}- </>- );-});-const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(props: {compact: boolean;activeContextWindow: ContextWindowSnapshot | null;@@ -512,6 +371,7 @@ export interface ChatComposerHandle {insertTextAtEnd: (text: string, options?: { ensureLeadingBoundary?: boolean }) => boolean;openModelPicker: () => void;toggleModelPicker: () => void;+ closeModelPicker: () => void;isModelPickerOpen: () => boolean;compactContext: () => void;readSnapshot: () => {@@ -558,7 +418,6 @@ export interface ChatComposerProps {attachmentUploadsCapabilityKnown: boolean;supportsAttachmentUploads: boolean;routeKind: "server" | "draft";- routeThreadRef: ScopedThreadRef;draftId: DraftId | null;// Thread context@@ -605,10 +464,6 @@ export interface ChatComposerProps {activeTasksProgress: ComposerTasksProgress | null;activeTaskSteps: readonly ComposerTaskStep[] | null;- // Mode- runtimeMode: RuntimeMode;- interactionMode: ProviderInteractionMode;-// Provider / modellockedProvider: ProviderDriverKind | null;providerStatuses: ServerProvider[];@@ -655,12 +510,8 @@ export interface ChatComposerProps {onProviderModelSelect: (instanceId: ProviderInstanceId, model: string) => void;getModelDisabledReason: (instanceId: ProviderInstanceId, model: string) => string | null;- toggleInteractionMode: () => void;- handleRuntimeModeChange: (mode: RuntimeMode) => void;- handleInteractionModeChange: (mode: ProviderInteractionMode) => void;focusComposer: () => void;- scheduleComposerFocus: () => void;setThreadError: (threadId: ThreadId | null, error: string | null) => void;onExpandImage: (preview: ExpandedImagePreview) => void;}@@ -676,7 +527,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)attachmentUploadsCapabilityKnown,supportsAttachmentUploads,routeKind,- routeThreadRef,draftId,activeThreadId,activeThreadEnvironmentId: _activeThreadEnvironmentId,@@ -704,8 +554,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)activeProposedPlan,activeTasksProgress,activeTaskSteps,- runtimeMode,- interactionMode,lockedProvider,providerStatuses,activeProjectDefaultModelSelection,@@ -733,11 +581,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)onChangeActivePendingUserInputCustomAnswer,onProviderModelSelect,getModelDisabledReason,- toggleInteractionMode,- handleRuntimeModeChange,- handleInteractionModeChange,focusComposer,- scheduleComposerFocus,setThreadError,onExpandImage,} = props;@@ -978,17 +822,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)const selectedPromptEffort = composerProviderState.promptEffort;const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;- // Plan mode is a legacy feature behind Settings → Beta. With the flag off,- // ChatView forces the effective mode to "default", so hiding the toggle- // can't trap anyone in plan mode.- const planModeUiEnabled = settings.planModeEnabled;- const composerProviderControls = useMemo(- () => ({- showInteractionModeToggle:- planModeUiEnabled && getProviderInteractionModeToggle(providerStatuses, selectedProvider),- }),- [planModeUiEnabled, providerStatuses, selectedProvider],- );const selectedModelSelection = useMemo<ModelSelection>(() => createModelSelection(selectedInstanceId, selectedModel, selectedModelOptionsForDispatch),[selectedInstanceId, selectedModel, selectedModelOptionsForDispatch],@@ -1007,6 +840,10 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)}return out;}, [providerInstanceEntries, settings]);++ // ------------------------------------------------------------------+ // Context window+ // ------------------------------------------------------------------const selectedModelForPickerWithCustomFallback = useMemo(() => {const currentOptions = modelOptionsByInstance.get(selectedInstanceId) ?? [];return currentOptions.some((option) => option.slug === selectedModelForPicker)@@ -1014,9 +851,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps): (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker);}, [modelOptionsByInstance, selectedInstanceId, selectedModelForPicker, selectedProvider]);- // ------------------------------------------------------------------- // Context window- // ------------------------------------------------------------------const activeThreadModelDisplayName = useMemo(() => resolveContextWindowModelDisplayName(activeThreadModelSelection, modelOptionsByInstance),[activeThreadModelSelection, modelOptionsByInstance],@@ -1040,6 +874,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);const [isComposerFocused, setIsComposerFocused] = useState(false);++ // Close stale picker state when the last available provider disappears+ // while the dialog is open.+ useEffect(() => {+ if (noProviderAvailable) {+ setIsComposerModelPickerOpen(false);+ }+ }, [noProviderAvailable]);const [composerSubmissionError, setComposerSubmissionError] = useState<string | null>(null);const [providerInputSubmissionError, setProviderInputSubmissionError] = useState<string | null>(null,@@ -1136,33 +978,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)}));}if (composerTrigger.kind === "slash-command") {- const builtInSlashCommandItems = [- {- id: "slash:model",- type: "slash-command",- command: "model",- label: "/model",- description: "Switch response model for this thread",- },- ...(planModeUiEnabled- ? ([- {- id: "slash:plan",- type: "slash-command",- command: "plan",- label: "/plan",- description: "Switch this thread into plan mode",- },- {- id: "slash:default",- type: "slash-command",- command: "default",- label: "/default",- description: "Switch this thread back to normal build mode",- },- ] as const)- : []),- ] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;const slashMenuSkills = getProviderSkillsForSlashMenu(selectedProviderStatus?.skills ?? [],settings.showSkillsInSlashMenu,@@ -1190,11 +1005,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)skill.description ??(skill.scope ? `${skill.scope} skill` : ""),}));- const slashCommandItems = [- ...builtInSlashCommandItems,- ...providerSlashCommandItems,- ...skillItems,- ];+ const slashCommandItems = [...providerSlashCommandItems, ...skillItems];return searchSlashCommandItems(slashCommandItems, query);}if (composerTrigger.kind === "skill") {@@ -1215,7 +1026,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)return [];}, [composerTrigger,- planModeUiEnabled,selectedProvider,selectedProviderStatus,settings.showSkillsInSlashMenu,@@ -1297,46 +1107,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)// ------------------------------------------------------------------// Provider traits UI// ------------------------------------------------------------------- const setPromptFromTraits = useCallback(- (nextPrompt: string) => {- if (nextPrompt === promptRef.current) {- scheduleComposerFocus();- return;- }- promptRef.current = nextPrompt;- setComposerDraftPrompt(composerDraftTarget, nextPrompt);- const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length);- setComposerCursor(nextCursor);- setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length));- scheduleComposerFocus();- },- [composerDraftTarget, promptRef, scheduleComposerFocus, setComposerDraftPrompt],- );-- const providerTraitsMenuContent = renderProviderTraitsMenuContent({- provider: selectedProvider,- instanceId: selectedInstanceId,- ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}),- ...(routeKind === "draft" && draftId ? { draftId } : {}),- model: selectedModel,- models: selectedProviderModels,- modelOptions: composerModelOptions?.[selectedInstanceId],- prompt,- onPromptChange: setPromptFromTraits,- planModeEnabled: settings.planModeEnabled,- });- const providerTraitsPicker = renderProviderTraitsPicker({- provider: selectedProvider,- instanceId: selectedInstanceId,- ...(routeKind === "server" ? { threadRef: routeThreadRef } : {}),- ...(routeKind === "draft" && draftId ? { draftId } : {}),- model: selectedModel,- models: selectedProviderModels,- modelOptions: composerModelOptions?.[selectedInstanceId],- prompt,- onPromptChange: setPromptFromTraits,- planModeEnabled: settings.planModeEnabled,- });const pendingPrimaryAction = useMemo(() =>activePendingProgress@@ -1818,27 +1588,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)}return;}- if (item.type === "slash-command") {- if (item.command === "model") {- const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {- expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),- focusEditorAfterReplace: false,- });- if (applied) {- setComposerHighlightedItemId(null);- setIsComposerModelPickerOpen(true);- }- return;- }- void handleInteractionModeChange(item.command === "plan" ? "plan" : "default");- const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", {- expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd),- });- if (applied) {- setComposerHighlightedItemId(null);- }- return;- }if (item.type === "provider-slash-command") {const replacement = `/${item.command.name} `;const replacementRangeEnd = extendReplacementRangeForTrailingSpace(@@ -1876,7 +1625,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)return;}},- [applyPromptReplacement, handleInteractionModeChange, resolveActiveComposerTrigger],+ [applyPromptReplacement, resolveActiveComposerTrigger],);const onComposerMenuItemHighlighted = useCallback(@@ -2078,9 +1827,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)event: KeyboardEvent,) => {if (key === "Tab" && event.shiftKey) {- if (!planModeUiEnabled) return false;- toggleInteractionMode();- return true;+ // Reverse focus traversal stays native; the composer no longer hosts a+ // plan-mode toggle.+ return false;}const { trigger } = resolveActiveComposerTrigger();const menuIsActive = composerMenuOpenRef.current || trigger !== null;@@ -2820,13 +2569,18 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)},insertTextAtEnd: insertComposerTextAtEnd,openModelPicker: () => {+ if (noProviderAvailable) return;setIsComposerModelPickerOpen(true);},toggleModelPicker: () => {+ if (noProviderAvailable) return;setIsComposerModelPickerOpen((open) => !open);},+ closeModelPicker: () => {+ setIsComposerModelPickerOpen(false);+ },compactContext: compactThreadContext,- isModelPickerOpen: () => isComposerModelPickerOpen,+ isModelPickerOpen: () => !noProviderAvailable && isComposerModelPickerOpen,readSnapshot: () => {return readComposerSnapshot();},@@ -3485,64 +3239,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)<CircleAlertIcon className="size-4" />No provider available</Button>- ) : (- <ProviderModelPicker- compact={isComposerFooterCompact}- activeInstanceId={selectedInstanceId}- model={selectedModelForPickerWithCustomFallback}- lockedProvider={lockedProvider}- lockedContinuationGroupKey={lockedContinuationGroupKey}- instanceEntries={providerInstanceEntries}- keybindings={keybindings}- modelOptionsByInstance={modelOptionsByInstance}- triggerClassName="-ms-2.5"- terminalOpen={terminalOpen}- open={isComposerModelPickerOpen}- {...(composerProviderState.modelPickerIconClassName- ? {- activeProviderIconClassName:- composerProviderState.modelPickerIconClassName,- }- : {})}- onOpenChange={(open) => {- setIsComposerModelPickerOpen(open);- }}- getModelDisabledReason={getModelDisabledReason}- onInstanceModelChange={onProviderModelSelect}- />- )}-- {isComposerFooterCompact ? (- <CompactComposerControlsMenu- interactionMode={interactionMode}- runtimeMode={runtimeMode}- showInteractionModeToggle={composerProviderControls.showInteractionModeToggle}- traitsMenuContent={providerTraitsMenuContent}- onToggleInteractionMode={toggleInteractionMode}- onRuntimeModeChange={handleRuntimeModeChange}- />- ) : (- <>- {providerTraitsPicker ? (- <>- <Separator- orientation="vertical"- className="mx-0.5 hidden h-4 sm:block"- />- {providerTraitsPicker}- </>- ) : null}- <ComposerFooterModeControls- showInteractionModeToggle={- composerProviderControls.showInteractionModeToggle- }- interactionMode={interactionMode}- runtimeMode={runtimeMode}- onToggleInteractionMode={toggleInteractionMode}- onRuntimeModeChange={handleRuntimeModeChange}- />- </>- )}+ ) : null}</div>{/* Right side: send / stop button */}@@ -3594,6 +3291,33 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)</div></div></div>+ {noProviderAvailable ? null : (+ <Dialog open={isComposerModelPickerOpen} onOpenChange={setIsComposerModelPickerOpen}>+ <DialogPopup+ showCloseButton={false}+ bottomStickOnMobile={false}+ className="w-fit overflow-hidden p-0"+ >+ <DialogTitle className="sr-only">Choose model</DialogTitle>+ <ModelPickerContent+ activeInstanceId={selectedInstanceId}+ model={selectedModelForPickerWithCustomFallback}+ lockedProvider={lockedProvider}+ lockedContinuationGroupKey={lockedContinuationGroupKey}+ instanceEntries={providerInstanceEntries}+ keybindings={keybindings}+ modelOptionsByInstance={modelOptionsByInstance}+ terminalOpen={terminalOpen}+ onRequestClose={() => setIsComposerModelPickerOpen(false)}+ getModelDisabledReason={getModelDisabledReason}+ onInstanceModelChange={(instanceId, model) => {+ onProviderModelSelect(instanceId, model);+ setIsComposerModelPickerOpen(false);+ }}+ />+ </DialogPopup>+ </Dialog>+ )}</form>);});diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsxindex dbba32748..03e677514 100644--- a/apps/web/src/components/chat/ChatHeader.tsx+++ b/apps/web/src/components/chat/ChatHeader.tsx@@ -32,6 +32,8 @@ import ProjectScriptsControl, {type ProjectScriptActionResult,} from "../ProjectScriptsControl";import { OpenInPicker } from "./OpenInPicker";+import { type PresentationMode } from "./quietPresentation";+import { ActiveBotHeaderChip } from "../roster/ActiveBotHeaderChip";import { useRemoteOpenState, type RemoteOpenMode } from "../../remoteOpen";import { usePrimaryEnvironmentId } from "../../state/environments";import { useT3ProjectFileScripts } from "~/hooks/useT3ProjectFileScripts";@@ -65,6 +67,8 @@ interface ChatHeaderProps {availableEditors: ReadonlyArray<EditorId>;rightPanelOpen: boolean;gitCwd: string | null;+ presentationMode: PresentationMode;+ onTogglePresentationMode: () => void;readonly onOpenPullRequest?: ((number: number) => void) | undefined;onNewThreadInProject: () => void;onRunProjectScript: (script: ProjectScript) => void;@@ -134,6 +138,8 @@ export const ChatHeader = memo(function ChatHeader({availableEditors,rightPanelOpen,gitCwd,+ presentationMode,+ onTogglePresentationMode,onOpenPullRequest,onNewThreadInProject,onRunProjectScript,@@ -288,6 +294,7 @@ export const ChatHeader = memo(function ChatHeader({className="@container/header-actions flex min-w-0 flex-1 items-center gap-2 sm:gap-3"onContextMenu={handleHeaderContextMenu}>+ <ActiveBotHeaderChip /><WorkspaceBreadcrumb ariaLabel="Thread breadcrumb" className="flex-1">{/* The project always leads the header: knowing which project athread lives in is priority zero, and the thread title alone@@ -380,6 +387,24 @@ export const ChatHeader = memo(function ChatHeader({rightPanelOpen ? "pr-0" : "pr-16",)}>+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ onClick={onTogglePresentationMode}+ className="cursor-pointer rounded-sm text-xs text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring"+ />+ }+ >+ {presentationMode === "quiet" ? "Show work" : "Hide work"}+ </TooltipTrigger>+ <TooltipPopup side="top">+ {presentationMode === "quiet"+ ? "Show tool activity in this thread"+ : "Hide tool activity in this thread"}+ </TooltipPopup>+ </Tooltip>{activeProjectScripts && (<ProjectScriptsControlscripts={activeProjectScripts}diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsxindex af920c0d6..fe91ebb75 100644--- a/apps/web/src/components/chat/MessagesTimeline.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.tsx@@ -109,6 +109,8 @@ import { cn } from "~/lib/utils";import { useUiStateStore } from "~/uiStateStore";import { type TimestampFormat } from "@t3tools/contracts/settings";import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";+import { BotAvatarView } from "../roster/BotAvatarView";+import { useSelectedBot } from "../roster/rosterStore";import {buildInlineTerminalContextText,@@ -1136,42 +1138,48 @@ function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {const ctx = use(TimelineRowCtx);+ const bot = useSelectedBot();const messageText = row.message.text || (row.message.streaming ? "" : "(empty response)");return (<>- <div className="relative min-w-0 px-1 py-0.5">- <ChatMarkdown- text={messageText}- cwd={ctx.markdownCwd}- threadRef={ctx.threadRef ?? undefined}- isStreaming={Boolean(row.message.streaming)}- lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}- skills={ctx.skills}- />- <AssistantChangedFilesSection- turnSummary={row.assistantTurnDiffSummary}- routeThreadKey={ctx.routeThreadKey}- resolvedTheme={ctx.resolvedTheme}- onOpenTurnDiff={ctx.onOpenTurnDiff}- />- {row.showAssistantMeta ? (- <div className="mt-1.5 flex items-center gap-2 text-xs tabular-nums opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover/assistant:opacity-100">- <AssistantCopyButton row={row} />- {!row.message.streaming && (- <Tooltip>- <TooltipTrigger- render={<p className="text-muted-foreground text-xs tabular-nums" />}- >- {formatDayAwareTimestamp(row.message.updatedAt, ctx.timestampFormat)}- </TooltipTrigger>- <TooltipPopup>- {formatChatTimestampTooltip(row.message.updatedAt, ctx.timestampFormat)}- </TooltipPopup>- </Tooltip>- )}- </div>+ <div className="relative flex min-w-0 items-start gap-2 px-1 py-0.5">+ {bot !== null ? (+ <BotAvatarView avatar={bot.avatar} name={bot.name} className="mt-1 size-5" />) : null}+ <div className="min-w-0 flex-1">+ <ChatMarkdown+ text={messageText}+ cwd={ctx.markdownCwd}+ threadRef={ctx.threadRef ?? undefined}+ isStreaming={Boolean(row.message.streaming)}+ lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}+ skills={ctx.skills}+ />+ <AssistantChangedFilesSection+ turnSummary={row.assistantTurnDiffSummary}+ routeThreadKey={ctx.routeThreadKey}+ resolvedTheme={ctx.resolvedTheme}+ onOpenTurnDiff={ctx.onOpenTurnDiff}+ />+ {row.showAssistantMeta ? (+ <div className="mt-1.5 flex items-center gap-2 text-xs tabular-nums opacity-0 transition-opacity duration-200 focus-within:opacity-100 group-hover/assistant:opacity-100">+ <AssistantCopyButton row={row} />+ {!row.message.streaming && (+ <Tooltip>+ <TooltipTrigger+ render={<p className="text-muted-foreground text-xs tabular-nums" />}+ >+ {formatDayAwareTimestamp(row.message.updatedAt, ctx.timestampFormat)}+ </TooltipTrigger>+ <TooltipPopup>+ {formatChatTimestampTooltip(row.message.updatedAt, ctx.timestampFormat)}+ </TooltipPopup>+ </Tooltip>+ )}+ </div>+ ) : null}+ </div></div></>);diff --git a/apps/web/src/components/chat/quietPresentation.test.ts b/apps/web/src/components/chat/quietPresentation.test.tsnew file mode 100644index 000000000..9995448dc--- /dev/null+++ b/apps/web/src/components/chat/quietPresentation.test.ts@@ -0,0 +1,120 @@+import { describe, expect, it } from "vite-plus/test";+import {+ applyQuietPresentation,+ QUIET_FAILURE_LABEL,+ readStoredPresentationMode,+ storePresentationMode,+} from "./quietPresentation";+import { type TimelineEntry, type WorkLogEntry } from "../../session-logic";++function workEntry(overrides: Partial<WorkLogEntry> & { id: string }): TimelineEntry {+ const entry: WorkLogEntry = {+ createdAt: "2026-01-01T00:00:00Z",+ label: "Ran command",+ tone: "tool",+ ...overrides,+ };+ return { id: entry.id, kind: "work", createdAt: entry.createdAt, entry };+}++function messageEntry(id: string): TimelineEntry {+ return {+ id,+ kind: "message",+ createdAt: "2026-01-01T00:00:00Z",+ message: {+ id,+ role: "assistant",+ text: "done",+ createdAt: "2026-01-01T00:00:00Z",+ updatedAt: "2026-01-01T00:00:00Z",+ streaming: false,+ },+ } as TimelineEntry;+}++describe("applyQuietPresentation", () => {+ it("keeps messages and drops successful tool rows", () => {+ const entries = [+ messageEntry("m1"),+ workEntry({ id: "w1", command: "ls -la", toolLifecycleStatus: "completed" }),+ messageEntry("m2"),+ ];+ const result = applyQuietPresentation(entries);+ expect(result.map((entry) => entry.id)).toEqual(["m1", "m2"]);+ });++ it("drops thinking and in-progress tool rows", () => {+ const entries = [+ workEntry({ id: "w1", tone: "thinking", label: "Thinking" }),+ workEntry({ id: "w2", toolLifecycleStatus: "inProgress" }),+ ];+ expect(applyQuietPresentation(entries)).toEqual([]);+ });++ it("collapses a failed tool row to a plain status row without command or output", () => {+ const entries = [+ workEntry({+ id: "w1",+ command: "rm -rf /tmp/thing",+ detail: "exit code: 1",+ toolLifecycleStatus: "failed",+ toolData: { raw: "trace" },+ }),+ ];+ const result = applyQuietPresentation(entries);+ expect(result).toHaveLength(1);+ const only = result[0];+ if (only?.kind !== "work") throw new Error("expected work entry");+ expect(only.entry.label).toBe(QUIET_FAILURE_LABEL);+ expect(only.entry.tone).toBe("error");+ expect(only.entry.command).toBeUndefined();+ expect(only.entry.detail).toBeUndefined();+ expect(only.entry.toolData).toBeUndefined();+ expect(only.entry.id).toBe("w1");+ });++ it("keeps agent spawn CTA rows", () => {+ const entries = [+ workEntry({+ id: "w1",+ tone: "thinking",+ label: "Kicked off 2 subagents",+ agentSpawn: { workflowId: null, agentTaskIds: ["t1", "t2"] },+ }),+ ];+ expect(applyQuietPresentation(entries).map((entry) => entry.id)).toEqual(["w1"]);+ });++ it("keeps non-tool info rows", () => {+ const entries = [workEntry({ id: "w1", tone: "info", label: "Checkpoint saved" })];+ expect(applyQuietPresentation(entries).map((entry) => entry.id)).toEqual(["w1"]);+ });+});++describe("presentation mode storage", () => {+ function memoryStorage(): Storage {+ const map = new Map<string, string>();+ return {+ get length() {+ return map.size;+ },+ clear: () => map.clear(),+ getItem: (key: string) => map.get(key) ?? null,+ key: (index: number) => [...map.keys()][index] ?? null,+ removeItem: (key: string) => void map.delete(key),+ setItem: (key: string, value: string) => void map.set(key, value),+ };+ }++ it("defaults to quiet and round-trips the detailed opt-out", () => {+ const storage = memoryStorage();+ expect(readStoredPresentationMode("thread-1", storage)).toBe("quiet");+ storePresentationMode("thread-1", "detailed", storage);+ expect(readStoredPresentationMode("thread-1", storage)).toBe("detailed");+ expect(readStoredPresentationMode("thread-2", storage)).toBe("quiet");+ storePresentationMode("thread-1", "quiet", storage);+ expect(readStoredPresentationMode("thread-1", storage)).toBe("quiet");+ expect(storage.length).toBe(0);+ });+});diff --git a/apps/web/src/components/chat/quietPresentation.ts b/apps/web/src/components/chat/quietPresentation.tsnew file mode 100644index 000000000..056e2a2cb--- /dev/null+++ b/apps/web/src/components/chat/quietPresentation.ts@@ -0,0 +1,95 @@+import {+ workEntryDisplayIndicatesToolFailure,+ workLogEntryIsToolLike,+ type TimelineEntry,+ type WorkLogEntry,+} from "../../session-logic";++/**+ * Quiet presentation hides tool-call chrome so a bot reads like a teammate:+ * messages and plans stay, tool rows disappear, and a failure collapses to+ * one plain status row. Detailed presentation is the full work log.+ */+export type PresentationMode = "quiet" | "detailed";++export const QUIET_FAILURE_LABEL = "A step failed";++/**+ * Strip a failed tool row down to a plain status row: no command, no output,+ * no tool payload. The id is kept so timeline keys stay stable across mode+ * flips and streaming updates.+ */+export function quietFailureEntry(entry: WorkLogEntry): WorkLogEntry {+ return {+ id: entry.id,+ createdAt: entry.createdAt,+ ...(entry.turnId !== undefined ? { turnId: entry.turnId } : {}),+ label: QUIET_FAILURE_LABEL,+ tone: "error",+ };+}++export function applyQuietPresentation(entries: ReadonlyArray<TimelineEntry>): TimelineEntry[] {+ const result: TimelineEntry[] = [];+ for (const item of entries) {+ if (item.kind !== "work") {+ result.push(item);+ continue;+ }+ // Spawn CTA rows stay: they are navigation to child agents, not tool chrome.+ if (item.entry.agentSpawn !== undefined) {+ result.push(item);+ continue;+ }+ if (!workLogEntryIsToolLike(item.entry)) {+ result.push(item);+ continue;+ }+ if (workEntryDisplayIndicatesToolFailure(item.entry)) {+ result.push({ ...item, entry: quietFailureEntry(item.entry) });+ }+ // Successful, neutral, and in-progress tool rows are dropped.+ }+ return result;+}++const DETAILED_STORAGE_PREFIX = "akeru.presentation.detailed:";++function storageOrNull(storage?: Storage): Storage | null {+ if (storage) return storage;+ try {+ return globalThis.localStorage ?? null;+ } catch {+ return null;+ }+}++/** Quiet is the product default; storage only records the detailed opt-out. */+export function readStoredPresentationMode(threadKey: string, storage?: Storage): PresentationMode {+ const store = storageOrNull(storage);+ if (!store) return "quiet";+ try {+ return store.getItem(DETAILED_STORAGE_PREFIX + threadKey) === "1" ? "detailed" : "quiet";+ } catch {+ return "quiet";+ }+}++export function storePresentationMode(+ threadKey: string,+ mode: PresentationMode,+ storage?: Storage,+): void {+ const store = storageOrNull(storage);+ if (!store) return;+ try {+ if (mode === "detailed") {+ store.setItem(DETAILED_STORAGE_PREFIX + threadKey, "1");+ } else {+ store.removeItem(DETAILED_STORAGE_PREFIX + threadKey);+ }+ } catch {+ // Storage can be unavailable (private mode, quota); the toggle still+ // works for the session via component state.+ }+}diff --git a/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.test.ts b/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.test.tsindex fcc660e83..002ff0827 100644--- a/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.test.ts+++ b/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.test.ts@@ -31,7 +31,7 @@ describe("mobile client presentation", () => {it("describes the client platform and enabled notification events", () => {const client = device();- expect(mobileClientPlatformLabel(client)).toBe("iOS 18 · T3 Code 1.2.3");+ expect(mobileClientPlatformLabel(client)).toBe("iOS 18 · Akeru Bot 1.2.3");expect(mobileClientNotificationDetail(client)).toBe("Alerts enabled for approvals, completions.",);diff --git a/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.ts b/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.tsindex 5ca9595be..9801ef93f 100644--- a/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.ts+++ b/apps/web/src/components/clerk/MobileClientsUserProfilePage.logic.ts@@ -15,7 +15,7 @@ const NOTIFICATION_PREFERENCES = [>;export function mobileClientPlatformLabel(device: RelayClientDeviceRecord): string {- return `iOS ${device.iosMajorVersion}${device.appVersion ? ` · T3 Code ${device.appVersion}` : ""}`;+ return `iOS ${device.iosMajorVersion}${device.appVersion ? ` · Akeru Bot ${device.appVersion}` : ""}`;}export function mobileClientNotificationDetail(device: RelayClientDeviceRecord): string {diff --git a/apps/web/src/components/clerk/MobileClientsUserProfilePage.tsx b/apps/web/src/components/clerk/MobileClientsUserProfilePage.tsxindex 22449c336..0b2115718 100644--- a/apps/web/src/components/clerk/MobileClientsUserProfilePage.tsx+++ b/apps/web/src/components/clerk/MobileClientsUserProfilePage.tsx@@ -94,7 +94,7 @@ function EmptyMobileClients() {<EmptyHeader><EmptyTitle className="text-[1.0625rem] leading-6">No mobile clients</EmptyTitle><EmptyDescription className="text-[0.8125rem] leading-[1.125rem]">- Sign in to T3 Code on your iPhone to register it for push notifications and Live+ Sign in to Akeru Bot on your iPhone to register it for push notifications and LiveActivities.</EmptyDescription></EmptyHeader>@@ -112,7 +112,7 @@ export function MobileClientsUserProfilePage() {return (<ClerkUserProfilePagetitle="Mobile clients"- description="Devices registered to receive T3 Connect activity from your environments."+ description="Devices registered to receive activity from your environments."action={<ClerkUserProfileRefreshButtonisPending={devicesState.isPending}diff --git a/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsx b/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsxindex 9dfd8dce1..cb103fa19 100644--- a/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsx+++ b/apps/web/src/components/clerk/T3ConnectSidebarSignIn.tsx@@ -1,7 +1,8 @@import { UserButton, useAuth } from "@clerk/react";-import { LogInIcon, ServerIcon, SmartphoneIcon } from "lucide-react";+import { Login01Icon, ServerIcon, SmartphoneIcon } from "@hugeicons/core-free-icons";import { hasCloudPublicConfig } from "../../cloud/publicConfig";+import { AppIcon } from "../ui/app-icon";import { SidebarMenu, SidebarMenuButton, SidebarMenuItem } from "../ui/sidebar";import { MobileClientsUserProfilePage } from "./MobileClientsUserProfilePage";import { T3ConnectUserProfilePage } from "./T3ConnectUserProfilePage";@@ -26,23 +27,28 @@ function ConfiguredT3ConnectSidebarAvatar() {return (<UserButton+ showNameappearance={{elements: {- avatarBox: "size-7",- userButtonTrigger: "rounded-lg p-1 hover:bg-sidebar-row-hover",+ rootBox: "w-full",+ userButtonBox: "w-full",+ avatarBox: "size-8 ring-1 ring-sidebar-border",+ userButtonTrigger:+ "w-full min-h-11 justify-start gap-2.5 rounded-lg px-2 py-1.5 text-sidebar-foreground hover:bg-sidebar-row-hover focus-visible:ring-2 focus-visible:ring-ring",+ userButtonOuterIdentifier: "min-w-0 truncate text-sm font-medium",},}}><UserButton.UserProfilePagelabel="Mobile clients"- labelIcon={<SmartphoneIcon className="size-4" />}+ labelIcon={<AppIcon className="size-4" icon={SmartphoneIcon} />}url="mobile-clients"><MobileClientsUserProfilePage /></UserButton.UserProfilePage><UserButton.UserProfilePage- label="T3 Connect"- labelIcon={<ServerIcon className="size-4" />}+ label="Linked environments"+ labelIcon={<AppIcon className="size-4" icon={ServerIcon} />}url="t3-connect"><T3ConnectUserProfilePage />@@ -62,8 +68,8 @@ function ConfiguredT3ConnectSidebarSignIn() {<SidebarMenu><SidebarMenuItem><SidebarMenuButton onClick={openAuthPrompt}>- <LogInIcon />- <span>Sign in to T3 Connect</span>+ <AppIcon icon={Login01Icon} />+ <span>Sign in for remote access</span></SidebarMenuButton></SidebarMenuItem></SidebarMenu>diff --git a/apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsx b/apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsxindex 377c9c945..17ea936b7 100644--- a/apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsx+++ b/apps/web/src/components/clerk/T3ConnectUserProfilePage.test.tsx@@ -34,7 +34,7 @@ function renderRow({);}-describe("T3 Connect environment row", () => {+describe("Linked environment row", () => {it("keeps deregistration confirmation inline and collapsed by default", () => {const markup = renderRow();diff --git a/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx b/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsxindex 15ed56905..86298db0b 100644--- a/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx+++ b/apps/web/src/components/clerk/T3ConnectUserProfilePage.tsx@@ -86,8 +86,8 @@ export function T3ConnectEnvironmentRow(props: {“{environment.label}” will be removed from this account.</p><p className="mt-4 max-w-xl text-[0.8125rem] leading-[1.125rem] text-muted-foreground">- T3 Connect access will be revoked, any managed tunnel will be removed, and a host- space will become available. Local connections on your devices are not changed.+ Remote access will be revoked, any managed tunnel will be removed, and a host space+ will become available. Local connections on your devices are not changed.</p><div className="mt-4 flex justify-end gap-2"><Button@@ -157,7 +157,7 @@ export function T3ConnectUserProfilePage() {toastManager.add({type: "success",title: "Server deregistered",- description: "T3 Connect access was revoked and a host space is now available.",+ description: "Remote access was revoked and a host space is now available.",});return;}@@ -200,7 +200,7 @@ export function T3ConnectUserProfilePage() {return (<ClerkUserProfilePage- title="T3 Connect"+ title="Linked environments"description="Environments registered to your account. Connections on this device are managed in Settings."action={<ClerkUserProfileRefreshButton@@ -214,7 +214,7 @@ export function T3ConnectUserProfilePage() {{environmentsState.error ? (<div className="mb-4 border-t border-destructive/35 py-3 text-[0.8125rem]" role="alert"><p className="font-medium text-destructive-foreground">- Could not load T3 Connect environments+ Could not load linked environments</p><p className="mt-1 text-xs text-muted-foreground">{environmentsState.error}</p></div>@@ -245,11 +245,9 @@ export function T3ConnectUserProfilePage() {<ServerIcon /></EmptyMedia><EmptyHeader>- <EmptyTitle className="text-[1.0625rem] leading-6">- No T3 Connect environments- </EmptyTitle>+ <EmptyTitle className="text-[1.0625rem] leading-6">No linked environments</EmptyTitle><EmptyDescription className="text-[0.8125rem] leading-[1.125rem]">- Link an environment from its local Settings to make it available through T3 Connect.+ Link an environment from its local Settings to make it available for remote access.</EmptyDescription></EmptyHeader></Empty>diff --git a/apps/web/src/components/clerk/clerkAppearance.test.ts b/apps/web/src/components/clerk/clerkAppearance.test.tsindex 18ecb7b23..f7439810b 100644--- a/apps/web/src/components/clerk/clerkAppearance.test.ts+++ b/apps/web/src/components/clerk/clerkAppearance.test.ts@@ -1,14 +1,7 @@+import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";import { describe, expect, it } from "vite-plus/test";-import {- EMBER_THEME,- GROVE_THEME,- IRIS_THEME,- OCEAN_THEME,- T3_CHAT_THEME,- themeColorToHex,- type ThemeColors,-} from "../../themePalette";+import { themeColorToHex, type ThemeColors } from "../../themePalette";import { clerkAppearance } from "./clerkAppearance";function contrastRatio(first: string, second: string): number {@@ -40,13 +33,7 @@ function mixThemeColors(first: string, second: string, firstWeight: number): strreturn `#${mixed.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;}-const builtInThemeModes = [- T3_CHAT_THEME,- GROVE_THEME,- OCEAN_THEME,- EMBER_THEME,- IRIS_THEME,-].flatMap((theme) =>+const builtInThemeModes = BUILT_IN_THEMES.flatMap((theme) =>[theme.colors, theme.variants?.dark].filter((colors): colors is ThemeColors => !!colors),);diff --git a/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx b/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsxindex 460a25381..aba8ef6b0 100644--- a/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx+++ b/apps/web/src/components/cloud/CloudEnvironmentConnectList.tsx@@ -45,7 +45,7 @@ export function RemoteEnvironmentRowsSkeleton() {}/**- * The user's T3 Connect environments from relay discovery, each with a+ * The user's linked environments from relay discovery, each with a* Connect button. The primary environment is always excluded; already-saved* environments are hidden unless `showSavedEnvironments` renders them with* their live connection state (used by onboarding, where the full device mesh@@ -100,7 +100,7 @@ export function CloudEnvironmentConnectRows({toastManager.add({type: "success",title: "Environment added",- description: `Connecting to ${environment.label} through T3 Connect.`,+ description: `Connecting to ${environment.label} through its managed tunnel.`,});return;}@@ -109,7 +109,7 @@ export function CloudEnvironmentConnectRows({}const cause = squashAtomCommandFailure(result);const message =- cause instanceof Error ? cause.message : "Could not connect the T3 Connect environment.";+ cause instanceof Error ? cause.message : "Could not connect the linked environment.";const traceId = findErrorTraceId(cause);console.error("[t3-connect] Could not connect environment", { message, traceId, cause });toastManager.add({@@ -153,9 +153,7 @@ export function CloudEnvironmentConnectRows({if (discoveryProblem !== null && !environmentsState.refreshing) {return (<div className={ITEM_ROW_CLASSNAME}>- <p className="text-sm font-medium text-destructive">- Could not load T3 Connect environments- </p>+ <p className="text-sm font-medium text-destructive">Could not load linked environments</p><p className="mt-1 text-xs text-muted-foreground">{discoveryProblem}</p><Buttonsize="sm"diff --git a/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx b/apps/web/src/components/cloud/ConnectCliAuthSurface.tsxindex 5d5c280bb..5bfbc89e0 100644--- a/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx+++ b/apps/web/src/components/cloud/ConnectCliAuthSurface.tsx@@ -111,8 +111,8 @@ export function ConnectCliAuthorizeSurface() {title="Connecting your terminal"description={isSignedIn- ? "Redirecting to authorize T3 Connect for your CLI…"- : "Sign in to continue authorizing T3 Connect for your CLI."+ ? "Redirecting to authorize remote access for your CLI…"+ : "Sign in to continue authorizing remote access for your CLI."}/>{isLoaded && !isSignedIn ? (@@ -202,7 +202,7 @@ export function ConnectCliCallbackSurface() {<p className="mt-6 text-xs leading-relaxed text-muted-foreground">Only enter this code in a terminal session you started yourself. Anyone holding it can link- their machine to your T3 Connect account while it is valid.+ their machine to your account while it is valid.</p></AuthSurfaceShell>);diff --git a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsxindex 6248fb00b..93fb50e01 100644--- a/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx+++ b/apps/web/src/components/cloud/ConnectOnboardingDialog.tsx@@ -30,12 +30,12 @@ import { Switch } from "../ui/switch";import { toastManager } from "../ui/toast";/**- * Post-sign-in onboarding wizard for T3 Connect. Opens on every in-session+ * Post-sign-in onboarding wizard for remote access. Opens on every in-session* sign-in — sign-out removes the connected relay environments, so each new* session starts with no devices to reach. It first prompts to publish this* environment (managed tunnel + agent activity, both defaulting on) when the* current session is authorized to manage the relay link, then lists the- * account's T3 Connect environments so every device can be connected right+ * account's linked environments so every device can be connected right* away. A cold load with a restored session does not count as a sign-in.*/export function ConnectOnboardingDialog() {@@ -200,9 +200,9 @@ function ConfiguredConnectOnboardingDialog() {if (!ok) return;toastManager.add({type: "success",- title: "T3 Connect enabled",+ title: "Remote access enabled",description: exposeEnvironment- ? "This environment is available to your other devices through T3 Connect."+ ? "This environment is available to your other devices through its managed tunnel.": "This environment publishes agent activity to your mobile clients.",});setStep("devices");@@ -219,7 +219,7 @@ function ConfiguredConnectOnboardingDialog() {><DialogPopup className="max-w-xl"><DialogHeader>- <DialogTitle>Set up T3 Connect</DialogTitle>+ <DialogTitle>Set up remote access</DialogTitle><DialogDescription>Mesh your devices together — publish this environment and connect the rest, all in oneplace.@@ -361,7 +361,7 @@ function PublishStep({<div className="rounded-lg border"><OnboardingToggleRowtitle="Publish this environment"- description="Make this environment available to your other devices through T3 Connect."+ description="Make this environment available to your other devices through a managed tunnel."checked={exposeEnvironment}disabled={disabled}onCheckedChange={onExposeEnvironmentChange}diff --git a/apps/web/src/components/cloud/RelayClientInstallDialog.tsx b/apps/web/src/components/cloud/RelayClientInstallDialog.tsxindex 78282f659..2198c1c68 100644--- a/apps/web/src/components/cloud/RelayClientInstallDialog.tsx+++ b/apps/web/src/components/cloud/RelayClientInstallDialog.tsx@@ -69,8 +69,8 @@ export function RelayClientInstallDialog() {</DialogTitle><DialogDescription>{isInstalling- ? "T3 Code is preparing this environment for secure access through T3 Connect."- : "T3 Code needs the relay client to make this environment available through T3 Connect."}+ ? "Akeru Bot is preparing this environment for secure remote access."+ : "Akeru Bot needs the relay client to make this environment available for remote access."}</DialogDescription></DialogHeader><DialogPanel scrollFade={false}>@@ -91,14 +91,14 @@ export function RelayClientInstallDialog() {value={activeStepIndex + 1}/><p className="text-xs leading-relaxed text-muted-foreground">- Keep T3 Code open while the relay client is installed.+ Keep Akeru Bot open while the relay client is installed.</p></div>) : (<div className="rounded-xl border border-border/70 bg-muted/35 p-3"><p className="text-sm font-medium text-foreground">Managed relay client</p><p className="mt-1 text-sm leading-relaxed text-muted-foreground">- T3 Code will download and install version{" "}+ Akeru Bot will download and install version{" "}{view.status === "confirming" ? view.version : ""} locally.</p></div>diff --git a/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx b/apps/web/src/components/desktop/SshPasswordPromptDialog.tsxindex a6ff9d8c4..62d6232e2 100644--- a/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx+++ b/apps/web/src/components/desktop/SshPasswordPromptDialog.tsx@@ -160,8 +160,9 @@ function ActiveSshPasswordPrompt({<DialogHeader><DialogTitle>SSH Password Required</DialogTitle><DialogDescription>- T3 needs your SSH password to connect to <code>{target}</code>. The password is passed- to the local SSH process for this connection attempt and is not saved by T3 Code.+ Akeru Bot needs your SSH password to connect to <code>{target}</code>. The password is+ passed to the local SSH process for this connection attempt and is not saved by Akeru+ Bot.</DialogDescription></DialogHeader><DialogPanel className="space-y-3" scrollFade={false}>diff --git a/apps/web/src/components/desktopUpdate.logic.test.ts b/apps/web/src/components/desktopUpdate.logic.test.tsindex 918ffe0c3..5d8e25c11 100644--- a/apps/web/src/components/desktopUpdate.logic.test.ts+++ b/apps/web/src/components/desktopUpdate.logic.test.ts@@ -7,7 +7,6 @@ import {getDesktopUpdateActionError,getDesktopUpdateButtonTooltip,getDesktopUpdateInstallConfirmationMessage,- getDesktopUpdateReleaseUrl,isDesktopUpdateButtonDisabled,resolveDesktopUpdateButtonAction,shouldShowArm64IntelBuildWarning,@@ -185,23 +184,6 @@ describe("getDesktopUpdateActionError", () => {});describe("desktop update UI helpers", () => {- it("builds the stable release URL for a downloaded version", () => {- expect(getDesktopUpdateReleaseUrl("0.0.30")).toBe(- "https://github.com/pingdotgg/t3code/releases/tag/v0.0.30",- );- });-- it("builds the nightly release URL without dropping its version suffix", () => {- expect(getDesktopUpdateReleaseUrl("0.0.30-nightly.20260728.931")).toBe(- "https://github.com/pingdotgg/t3code/releases/tag/v0.0.30-nightly.20260728.931",- );- });-- it("omits the release URL when the updater does not report a version", () => {- expect(getDesktopUpdateReleaseUrl(null)).toBeNull();- expect(getDesktopUpdateReleaseUrl(" ")).toBeNull();- });-it("toasts only for actionable updater errors", () => {expect(shouldToastDesktopUpdateActionResult({@@ -258,7 +240,7 @@ describe("desktop update UI helpers", () => {availableVersion: "1.1.0",downloadedVersion: "1.1.1",}),- ).toContain("Install update 1.1.1 and restart T3 Code?");+ ).toContain("Install update 1.1.1 and restart Akeru Bot?");});it("falls back to generic install confirmation copy when no version is available", () => {@@ -267,7 +249,7 @@ describe("desktop update UI helpers", () => {availableVersion: null,downloadedVersion: null,}),- ).toContain("Install update and restart T3 Code?");+ ).toContain("Install update and restart Akeru Bot?");});it("keeps the same install confirmation copy across desktop platforms", () => {@@ -277,7 +259,7 @@ describe("desktop update UI helpers", () => {downloadedVersion: "1.1.0",}),).toBe(- "Install update 1.1.0 and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.",+ "Install update 1.1.0 and restart Akeru Bot?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.",);});});diff --git a/apps/web/src/components/desktopUpdate.logic.ts b/apps/web/src/components/desktopUpdate.logic.tsindex 59dfbd385..6e451ae53 100644--- a/apps/web/src/components/desktopUpdate.logic.ts+++ b/apps/web/src/components/desktopUpdate.logic.ts@@ -2,24 +2,6 @@ import type { DesktopUpdateActionResult, DesktopUpdateState } from "@t3tools/conexport type DesktopUpdateButtonAction = "download" | "install" | "none";-const DESKTOP_RELEASE_TAG_URL = "https://github.com/pingdotgg/t3code/releases/tag";--/**- * The main process fills `downloadedVersion` from the updater's `update-downloaded`- * event, which is dispatched on its own fiber. A download RPC can therefore resolve- * before that write lands, so fall back to the version the download was started for.- */-export function getDesktopUpdateDownloadedVersion(state: DesktopUpdateState): string | null {- return state.downloadedVersion ?? state.availableVersion;-}--/** Release notes for an exact downloaded build; nightly suffixes are part of the tag. */-export function getDesktopUpdateReleaseUrl(version: string | null): string | null {- const normalizedVersion = version?.trim();- if (!normalizedVersion) return null;- return `${DESKTOP_RELEASE_TAG_URL}/v${encodeURIComponent(normalizedVersion)}`;-}-export function resolveDesktopUpdateButtonAction(state: DesktopUpdateState,): DesktopUpdateButtonAction {@@ -67,12 +49,12 @@ export function getArm64IntelBuildWarningDescription(state: DesktopUpdateState):const action = resolveDesktopUpdateButtonAction(state);if (action === "download") {- return "This Mac has Apple Silicon, but T3 Code is still running the Intel build under Rosetta. Download the available update to switch to the native Apple Silicon build.";+ return "This Mac has Apple Silicon, but Akeru Bot is still running the Intel build under Rosetta. Download the available update to switch to the native Apple Silicon build.";}if (action === "install") {- return "This Mac has Apple Silicon, but T3 Code is still running the Intel build under Rosetta. Restart to install the downloaded Apple Silicon build.";+ return "This Mac has Apple Silicon, but Akeru Bot is still running the Intel build under Rosetta. Restart to install the downloaded Apple Silicon build.";}- return "This Mac has Apple Silicon, but T3 Code is still running the Intel build under Rosetta. The next app update will replace it with the native Apple Silicon build.";+ return "This Mac has Apple Silicon, but Akeru Bot is still running the Intel build under Rosetta. The next app update will replace it with the native Apple Silicon build.";}export function getDesktopUpdateButtonTooltip(state: DesktopUpdateState): string {@@ -106,7 +88,7 @@ export function getDesktopUpdateInstallConfirmationMessage(state: Pick<DesktopUpdateState, "availableVersion" | "downloadedVersion">,): string {const version = state.downloadedVersion ?? state.availableVersion;- return `Install update${version ? ` ${version}` : ""} and restart T3 Code?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.`;+ return `Install update${version ? ` ${version}` : ""} and restart Akeru Bot?\n\nAny running tasks will be interrupted. Make sure you're ready before continuing.`;}export function getDesktopUpdateActionError(result: DesktopUpdateActionResult): string | null {diff --git a/apps/web/src/components/desktopUpdate.toast.test.tsx b/apps/web/src/components/desktopUpdate.toast.test.tsxindex 369a3cdf4..880865a25 100644--- a/apps/web/src/components/desktopUpdate.toast.test.tsx+++ b/apps/web/src/components/desktopUpdate.toast.test.tsx@@ -1,6 +1,4 @@-import { isValidElement, type ReactElement, type ReactNode } from "react";import { beforeEach, describe, expect, it, vi } from "vite-plus/test";-import type { DesktopUpdateState } from "@t3tools/contracts";const testState = vi.hoisted(() => ({addToast: vi.fn(),@@ -12,110 +10,19 @@ vi.mock("./ui/toast", () => ({import { showDesktopUpdateDownloadedToast } from "./desktopUpdate.toast";-type ClickableElement = ReactElement<{ readonly onClick?: () => void }>;--/** Walks the rendered description, invoking function components, to find the link button. */-function findReleaseNotesLink(node: ReactNode): ClickableElement | null {- if (Array.isArray(node)) {- for (const child of node) {- const found = findReleaseNotesLink(child);- if (found) return found;- }- return null;- }- if (!isValidElement(node)) return null;- const element = node as ReactElement<{ readonly children?: ReactNode }>;- if (element.type === "button") return element as ClickableElement;- if (typeof element.type === "function") {- const render = element.type as (props: unknown) => ReactNode;- return findReleaseNotesLink(render(element.props));- }- return findReleaseNotesLink(element.props.children);-}--function getDescription(): ReactNode {- const toast = testState.addToast.mock.calls[0]?.[0] as { description?: ReactNode } | undefined;- return toast?.description ?? null;-}--function downloadedState(overrides: Partial<DesktopUpdateState> = {}): DesktopUpdateState {- return {- enabled: true,- status: "downloaded",- channel: "latest",- currentVersion: "0.0.29",- hostArch: "arm64",- appArch: "arm64",- runningUnderArm64Translation: false,- availableVersion: "0.0.30",- downloadedVersion: "0.0.30",- releaseNotes: [],- downloadPercent: 100,- checkedAt: null,- message: null,- errorContext: null,- canRetry: true,- ...overrides,- };-}-describe("showDesktopUpdateDownloadedToast", () => {beforeEach(() => {testState.addToast.mockReset();});- it("opens the downloaded version's release notes", async () => {- const openExternal = vi.fn().mockResolvedValue(true);+ it("announces the downloaded update without external links", () => {+ showDesktopUpdateDownloadedToast();- showDesktopUpdateDownloadedToast({ openExternal }, downloadedState());- const link = findReleaseNotesLink(getDescription());- link?.props.onClick?.();- await vi.waitFor(() => {- expect(openExternal).toHaveBeenCalledWith(- "https://github.com/pingdotgg/t3code/releases/tag/v0.0.30",- );- });expect(testState.addToast).toHaveBeenCalledTimes(1);- });-- it("falls back to the version the download was started for", async () => {- const openExternal = vi.fn().mockResolvedValue(true);-- // The `update-downloaded` event can land after the download RPC resolves.- showDesktopUpdateDownloadedToast(- { openExternal },- downloadedState({ downloadedVersion: null }),- );- findReleaseNotesLink(getDescription())?.props.onClick?.();-- await vi.waitFor(() => {- expect(openExternal).toHaveBeenCalledWith(- "https://github.com/pingdotgg/t3code/releases/tag/v0.0.30",- );- });- });-- it("omits the link when the updater reports no version at all", () => {- showDesktopUpdateDownloadedToast(- { openExternal: vi.fn() },- downloadedState({ availableVersion: null, downloadedVersion: null }),- );-- expect(findReleaseNotesLink(getDescription())).toBeNull();- });-- it.each([- ["returns false", vi.fn().mockResolvedValue(false)],- ["rejects", vi.fn().mockRejectedValue(new Error("open failed"))],- ])("shows an error when opening release notes %s", async (_description, openExternal) => {- showDesktopUpdateDownloadedToast({ openExternal }, downloadedState());- findReleaseNotesLink(getDescription())?.props.onClick?.();-- await vi.waitFor(() => {- expect(testState.addToast).toHaveBeenLastCalledWith({- type: "error",- title: "Unable to open release notes",- });+ expect(testState.addToast).toHaveBeenCalledWith({+ type: "success",+ title: "Update downloaded",+ description: "Restart the app from the update button to install it.",});});});diff --git a/apps/web/src/components/desktopUpdate.toast.tsx b/apps/web/src/components/desktopUpdate.toast.tsxindex 4e55f3a28..933eca016 100644--- a/apps/web/src/components/desktopUpdate.toast.tsx+++ b/apps/web/src/components/desktopUpdate.toast.tsx@@ -1,59 +1,9 @@-import type { DesktopBridge, DesktopUpdateState } from "@t3tools/contracts";-import { ArrowRightIcon } from "lucide-react";--import {- getDesktopUpdateDownloadedVersion,- getDesktopUpdateReleaseUrl,-} from "./desktopUpdate.logic";import { toastManager } from "./ui/toast";-type DesktopUpdateShell = Pick<DesktopBridge, "openExternal">;--function ReleaseNotesLink({- shell,- releaseUrl,-}: {- shell: DesktopUpdateShell;- releaseUrl: string;-}) {- return (- <button- className="ml-2 inline cursor-pointer text-muted-foreground underline decoration-dotted underline-offset-4 transition-colors hover:text-foreground"- onClick={() => {- void (async () => {- try {- if (await shell.openExternal(releaseUrl)) return;- } catch {- // Surface rejected IPC calls through the same user-visible fallback.- }- toastManager.add({ type: "error", title: "Unable to open release notes" });- })();- }}- type="button"- >- Read more- <ArrowRightIcon- aria-hidden- className="ml-1 inline size-3 -rotate-45 align-[-0.125em]"- strokeWidth={2.25}- />- </button>- );-}--export function showDesktopUpdateDownloadedToast(- shell: DesktopUpdateShell,- state: DesktopUpdateState,-): void {- const releaseUrl = getDesktopUpdateReleaseUrl(getDesktopUpdateDownloadedVersion(state));+export function showDesktopUpdateDownloadedToast(): void {toastManager.add({type: "success",title: "Update downloaded",- description: (- <>- Restart the app from the update button to install it.- {releaseUrl ? <ReleaseNotesLink releaseUrl={releaseUrl} shell={shell} /> : null}- </>- ),+ description: "Restart the app from the update button to install it.",});}diff --git a/apps/web/src/components/dither-kit/area-chart.tsx b/apps/web/src/components/dither-kit/area-chart.tsxnew file mode 100644index 000000000..0fbecdd87--- /dev/null+++ b/apps/web/src/components/dither-kit/area-chart.tsx@@ -0,0 +1,20 @@+// @ts-nocheck+import { CartesianCanvas } from "./cartesian-canvas";+import { type CartesianChartProps, CartesianRoot } from "./cartesian-root";++// `object` rather than `Record<string, unknown>`: interfaces don't get an+// implicit index signature, so interface-typed rows failed to satisfy the+// generic. Internal layers still index rows through their own Row type.+type Row = object;++/** Composable dither **area** chart. Compose `<Area>`, `<Grid>`, axes, … inside. */+export function AreaChart<TData extends Row>(props: CartesianChartProps<TData>) {+ return <CartesianRoot chartType="area" Canvas={CartesianCanvas} {...props} />;+}++/** Composable dither **line** chart — `<Line>` series with a glow under the line. */+export function LineChart<TData extends Row>(props: CartesianChartProps<TData>) {+ return <CartesianRoot chartType="line" Canvas={CartesianCanvas} {...props} />;+}++export type AreaChartProps<TData extends Row> = CartesianChartProps<TData>;diff --git a/apps/web/src/components/dither-kit/area.tsx b/apps/web/src/components/dither-kit/area.tsxnew file mode 100644index 000000000..fc84a898d--- /dev/null+++ b/apps/web/src/components/dither-kit/area.tsx@@ -0,0 +1,94 @@+// @ts-nocheck+import { type ReactNode, useEffect } from "react";+import {+ type AreaVariant,+ type SeriesKind,+ type StrokeVariant,+ useChartPart,+} from "./chart-context";+import { SeriesContext } from "./series-context";++export type SeriesProps = {+ dataKey: string;+ variant?: AreaVariant;+ strokeVariant?: StrokeVariant;+ isClickable?: boolean;+ children?: ReactNode;+};++/**+ * Shared implementation for the continuous series (`<Area>`, `<Line>`). The+ * dithered fill/line is painted on the canvas; this registers the series so the+ * canvas knows how to draw it, wires click-to-select via a transparent band+ * polygon, and exposes the series to child `<Dot>`/`<ActiveDot>` markers.+ */+function CartesianSeries({+ part,+ kind,+ dataKey,+ variant = "gradient",+ strokeVariant = "solid",+ isClickable = false,+ children,+}: SeriesProps & { part: string; kind: SeriesKind }) {+ const ctx = useChartPart(part, kind === "line" ? "line" : "area");+ const { registerSeries, unregisterSeries } = ctx;++ if (process.env.NODE_ENV !== "production" && !ctx.config[dataKey]) {+ console.warn(+ `<${part} dataKey="${dataKey}" />: "${dataKey}" is not in the chart \`config\`. Add it so the series has a colour and label.`,+ );+ }++ useEffect(() => {+ registerSeries({ dataKey, kind, variant, strokeVariant });+ return () => unregisterSeries(dataKey);+ }, [dataKey, kind, variant, strokeVariant, registerSeries, unregisterSeries]);++ const band = ctx.bands[dataKey];+ if (!ctx.ready || !band) return null;++ const seed = ctx.seedOf(dataKey);+ const emphasis = ctx.selectedDataKey ?? ctx.focusDataKey;+ const dimmed = emphasis !== null && emphasis !== dataKey;+ const onClick = isClickable+ ? () => ctx.selectDataKey(ctx.selectedDataKey === dataKey ? null : dataKey)+ : undefined;++ // Transparent hit polygon tracing the series' own band, so clicking a series+ // selects *that* series. The Legend offers the same toggle accessibly.+ // One pass out along the top edge, one pass back along the floor.+ let hitPath: string | null = null;+ if (isClickable) {+ const parts: string[] = [];+ band.forEach((b, i) => {+ parts.push(`${i === 0 ? "M" : "L"}${ctx.xCenter(i)},${ctx.y(b[1])}`);+ });+ for (let i = band.length - 1; i >= 0; i -= 1) {+ parts.push(`L${ctx.xCenter(i)},${ctx.y(band[i][0])}`);+ }+ hitPath = `${parts.join(" ")} Z`;+ }++ return (+ <>+ {hitPath && (+ // biome-ignore lint/a11y/noStaticElementInteractions: progressive enhancement; the Legend offers the same toggle accessibly+ <path d={hitPath} fill="transparent" style={{ cursor: "pointer" }} onClick={onClick} />+ )}+ <SeriesContext value={{ dataKey, seed, dimmed }}>{children}</SeriesContext>+ </>+ );+}++export type AreaProps = SeriesProps;++/** One area series — dithered fill from the value line down to its floor. */+export function Area(props: AreaProps) {+ return <CartesianSeries part="Area" kind="area" {...props} />;+}++/** One line series — bright line with a thin dither glow hugging it. */+export function Line(props: AreaProps) {+ return <CartesianSeries part="Line" kind="line" {...props} />;+}diff --git a/apps/web/src/components/dither-kit/bar-canvas.tsx b/apps/web/src/components/dither-kit/bar-canvas.tsxnew file mode 100644index 000000000..c714f26eb--- /dev/null+++ b/apps/web/src/components/dither-kit/bar-canvas.tsx@@ -0,0 +1,223 @@+// @ts-nocheck+"use client";++import { useEffect, useMemo, useRef } from "react";+import { useChart } from "./chart-context";+import {+ backingSize,+ bloomLayerStyle,+ clamp01,+ easeOutCubic,+ paintColumn,+ prefersReducedMotion,+} from "./dither-paint";++type Bars = { top: number[]; base: number[] }; // per data index, in backing rows++// Fraction of the timeline spent staggering bar starts — the rest is each bar's+// own grow window, so the rise sweeps across the chart as a wave.+const STAGGER = 0.55;++/**+ * Dither canvas for bar charts. Each category owns a band; grouped series split+ * it into side-by-side bars, stacked series share its full width and pile in y.+ * Every bar is filled with the shared {@link paintColumn} ordered dither. Bars+ * grow up from their base in a staggered left-to-right wave (eased), and the+ * hovered category lifts while the rest dim.+ */+export function BarCanvas() {+ const ctx = useChart();+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const bloomRef = useRef<HTMLCanvasElement>(null);++ const { width, height } = ctx.plot;+ const { cols, rows } = backingSize(width, height);+ const { ready, configKeys, bands, y } = ctx;++ // Memoized: per-series bar tops/bases (backing rows) over the data indices.+ // The canvas re-renders on every hover/cursor tick, so pin this map to the+ // exact ctx fields it reads plus the backing geometry — a bar hover must not+ // rebuild every band's geometry.+ const targets = useMemo(() => {+ const out: Record<string, Bars> = {};+ if (!ready) return out;+ const h = height || 1;+ for (const key of configKeys) {+ const band = bands[key];+ if (!band) continue;+ out[key] = {+ top: band.map((b) => (y(b[1]) / h) * (rows - 1)),+ base: band.map((b) => (y(b[0]) / h) * (rows - 1)),+ };+ }+ return out;+ }, [ready, configKeys, bands, y, height, rows]);++ // The RAF loop reads these through refs so it always sees the latest values;+ // refs are written in an effect (never during render) — mutating a ref+ // mid-render tears under Strict Mode / concurrent rendering.+ const state = useRef(ctx);+ const targetsRef = useRef(targets);+ useEffect(() => {+ state.current = ctx;+ targetsRef.current = targets;+ });++ useEffect(() => {+ const canvas = canvasRef.current;+ const c = canvas?.getContext("2d");+ if (!(canvas && c) || cols <= 0 || rows <= 0) return;+ canvas.width = cols;+ canvas.height = rows;++ const bloomCanvas = bloomRef.current;+ const bloomCtx = bloomCanvas?.getContext("2d") ?? null;+ if (bloomCanvas) {+ bloomCanvas.width = cols;+ bloomCanvas.height = rows;+ }++ const reduce = prefersReducedMotion();+ const animate = state.current.animate && !reduce;+ const duration = state.current.animationDuration;+ const fx = cols / Math.max(width, 1);++ // Eased grow factor for bar `i` at global progress `prog`.+ const barProgress = (i: number, len: number, prog: number) => {+ if (!animate) return 1;+ const start = len > 1 ? (i / (len - 1)) * STAGGER : 0;+ return easeOutCubic(clamp01((prog - start) / (1 - STAGGER)));+ };++ const paint = (prog: number) => {+ const s = state.current;+ c.clearRect(0, 0, cols, rows);+ const stacked = s.stackType === "stacked" || s.stackType === "percent";+ const keys = s.configKeys;+ keys.forEach((key, si) => {+ const t = targetsRef.current[key];+ if (!t) return;+ const seed = s.seedOf(key);+ const variant = s.seriesSpecs[key]?.variant ?? "gradient";+ const emphasis = s.selectedDataKey ?? s.focusDataKey;+ const selDim = emphasis !== null && emphasis !== key ? 0.3 : 1;+ for (let i = 0; i < s.dataLength; i++) {+ const bp = barProgress(i, s.dataLength, prog);+ const base = t.base[i] ?? rows - 1;+ const grown = base + ((t.top[i] ?? base) - base) * bp;+ // Bars grow from the zero baseline toward the value. Positive values+ // sit above the baseline (smaller pixel), negative ones below it —+ // paintColumn wants the higher edge first, so order the pair.+ const top = Math.min(grown, base);+ const bottom = Math.max(grown, base);+ const active = s.hoverIndex === i;+ const hoverDim = s.hoverIndex != null && !active && s.isMouseInChart ? 0.5 : 1;+ const slot = s.barSlot(i, si, keys.length);+ const c0 = Math.round(slot.x * fx);+ const c1 = Math.round((slot.x + slot.width) * fx);+ for (let x = c0; x < c1; x++) {+ paintColumn(c, x, top, bottom, seed, {+ variant,+ intensity: intensity + (active ? 0.4 : 0),+ dim: selDim * hoverDim,+ stacked,+ });+ }+ }+ });+ };++ let raf = 0;+ let animStart = 0;+ let lastProg = -1;+ let lastRevision = state.current.revision;+ let intensity = 0;+ let needsFill = true;+ let lastPaintSig = "";+ let lastSelected: string | null | undefined = Symbol() as never;+ let lastHover: number | null | undefined = Symbol() as never;++ const draw = (now: number) => {+ raf = requestAnimationFrame(draw);+ const s = state.current;+ if (!s.ready) return;+ if (bloomCtx) {+ const on = s.bloom !== "off" && (!s.bloomOnHover || s.isMouseInChart || s.hovered);+ if (on) {+ bloomCtx.clearRect(0, 0, cols, rows);+ bloomCtx.drawImage(canvas, 0, 0);+ }+ }+ if (s.revision !== lastRevision) {+ lastRevision = s.revision;+ animStart = 0; // re-play the wave on data change / replay+ lastProg = -1;+ }+ if (!animStart) animStart = now;+ const prog = animate ? Math.min(1, (now - animStart) / duration) : 1;++ if (prog !== lastProg) {+ lastProg = prog;+ needsFill = true;+ }+ const emphasisNow = s.selectedDataKey ?? s.focusDataKey;+ if (emphasisNow !== lastSelected) {+ lastSelected = emphasisNow;+ needsFill = true;+ }+ if (s.hoverIndex !== lastHover) {+ lastHover = s.hoverIndex;+ needsFill = true;+ }+ const itTarget = s.isMouseInChart || s.hovered ? 1 : 0;+ if (Math.abs(intensity - itTarget) > 0.001) {+ intensity += (itTarget - intensity) * (reduce ? 1 : 0.16);+ needsFill = true;+ } else intensity = itTarget;++ // Live tweak repaint (variant, stacking) without replaying the wave.+ const paintSig = `${s.stackType}|${s.configKeys+ .map((k) => s.seriesSpecs[k]?.variant ?? "")+ .join(",")}`;+ if (paintSig !== lastPaintSig) {+ lastPaintSig = paintSig;+ needsFill = true;+ }++ if (!needsFill) return;+ paint(prog);+ needsFill = false;+ };++ raf = requestAnimationFrame(draw);+ return () => cancelAnimationFrame(raf);+ }, [cols, rows, width]);++ const bloomActive = ctx.bloomOnHover ? ctx.isMouseInChart || ctx.hovered : true;+ const bloom = bloomLayerStyle(ctx.bloom, bloomActive);+ const pos = {+ left: ctx.margins.left,+ top: ctx.margins.top,+ width,+ height,+ } as const;++ return (+ <>+ <canvas+ ref={canvasRef}+ className="pointer-events-none absolute"+ style={{ ...pos, imageRendering: "pixelated" }}+ />+ <canvas+ ref={bloomRef}+ className="pointer-events-none absolute"+ style={{+ ...pos,+ transition: "opacity 220ms ease",+ ...(bloom ?? { opacity: 0 }),+ }}+ />+ </>+ );+}diff --git a/apps/web/src/components/dither-kit/bar-chart.tsx b/apps/web/src/components/dither-kit/bar-chart.tsxnew file mode 100644index 000000000..a9073fd0b--- /dev/null+++ b/apps/web/src/components/dither-kit/bar-chart.tsx@@ -0,0 +1,13 @@+// @ts-nocheck+import { BarCanvas } from "./bar-canvas";+import { type CartesianChartProps, CartesianRoot } from "./cartesian-root";++// `object` rather than `Record<string, unknown>`: interfaces don't get an+// implicit index signature, so interface-typed rows failed to satisfy the+// generic. Internal layers still index rows through their own Row type.+type Row = object;++/** Composable dither **bar** chart — `<Bar>` series, grouped or stacked. */+export function BarChart<TData extends Row>(props: CartesianChartProps<TData>) {+ return <CartesianRoot chartType="bar" Canvas={BarCanvas} {...props} />;+}diff --git a/apps/web/src/components/dither-kit/bar.tsx b/apps/web/src/components/dither-kit/bar.tsxnew file mode 100644index 000000000..8957a808f--- /dev/null+++ b/apps/web/src/components/dither-kit/bar.tsx@@ -0,0 +1,75 @@+// @ts-nocheck+import { type ReactNode, useEffect } from "react";+import { type AreaVariant, type StrokeVariant, useChartPart } from "./chart-context";+import { SeriesContext } from "./series-context";++export type BarProps = {+ dataKey: string;+ variant?: AreaVariant;+ strokeVariant?: StrokeVariant;+ isClickable?: boolean;+ children?: ReactNode;+};++/**+ * One bar series. The dithered bars are painted on the canvas; this registers+ * the series and (when `isClickable`) lays transparent hit rects over each bar+ * — using the shared `barSlot` geometry so clicks line up with the pixels — to+ * select the series. The Legend offers the same toggle accessibly.+ */+export function Bar({+ dataKey,+ variant = "gradient",+ strokeVariant = "solid",+ isClickable = false,+ children,+}: BarProps) {+ const ctx = useChartPart("Bar", "bar");+ const { registerSeries, unregisterSeries } = ctx;++ if (process.env.NODE_ENV !== "production" && !ctx.config[dataKey]) {+ console.warn(+ `<Bar dataKey="${dataKey}" />: "${dataKey}" is not in the chart \`config\`. Add it so the series has a colour and label.`,+ );+ }++ useEffect(() => {+ registerSeries({ dataKey, kind: "bar", variant, strokeVariant });+ return () => unregisterSeries(dataKey);+ }, [dataKey, variant, strokeVariant, registerSeries, unregisterSeries]);++ const band = ctx.bands[dataKey];+ if (!ctx.ready || !band) return null;++ const seed = ctx.seedOf(dataKey);+ const dimmed = ctx.selectedDataKey !== null && ctx.selectedDataKey !== dataKey;+ const si = ctx.configKeys.indexOf(dataKey);+ const n = ctx.configKeys.length;+ const onClick = () => ctx.selectDataKey(ctx.selectedDataKey === dataKey ? null : dataKey);++ return (+ <>+ {isClickable &&+ band.map((b, i) => {+ const slot = ctx.barSlot(i, si, n);+ const top = ctx.y(b[1]);+ const base = ctx.y(b[0]);+ return (+ // biome-ignore lint/a11y/noStaticElementInteractions: progressive enhancement; the Legend offers the same toggle accessibly+ <rect+ // biome-ignore lint/suspicious/noArrayIndexKey: index is the stable category position+ key={i}+ x={slot.x}+ y={Math.min(top, base)}+ width={slot.width}+ height={Math.abs(base - top)}+ fill="transparent"+ style={{ cursor: "pointer" }}+ onClick={onClick}+ />+ );+ })}+ <SeriesContext value={{ dataKey, seed, dimmed }}>{children}</SeriesContext>+ </>+ );+}diff --git a/apps/web/src/components/dither-kit/block-legend.tsx b/apps/web/src/components/dither-kit/block-legend.tsxnew file mode 100644index 000000000..d370c908d--- /dev/null+++ b/apps/web/src/components/dither-kit/block-legend.tsx@@ -0,0 +1,59 @@+// @ts-nocheck+import type { ChartConfig } from "./chart-context";+import { cn } from "./lib";+import { rgb, seedOfColor } from "./palette";++/**+ * An in-flow legend rendered as a sibling of the chart rather than an overlay.+ *+ * The overlay {@link Legend} is pinned absolutely to the top of the plot, so+ * with more than ~3 entries (or a narrow container) its wrapped rows sit on top+ * of the chart. `<BlockLegend>` lives in normal document flow, so it can never+ * overlap the plot at any width — use it for multi-entry charts (donuts, many+ * series) and reserve the overlay `<Legend>` for ≤2–3 entries.+ *+ * It needs no chart context: feed it the same `config` you pass the chart, and+ * optionally a `values` map to show a number beside each entry (e.g. allocation+ * shares or totals).+ */+export function BlockLegend({+ config,+ values,+ valueFormatter = (v) => String(v),+ align = "start",+ className,+}: {+ config: ChartConfig;+ values?: Record<string, number>;+ valueFormatter?: (value: number) => string;+ align?: "start" | "center" | "end";+ className?: string;+}) {+ return (+ <ul+ className={cn(+ "flex flex-wrap gap-x-4 gap-y-1.5 px-1",+ align === "center" && "justify-center",+ align === "end" && "justify-end",+ className,+ )}+ >+ {Object.entries(config).map(([name, entry]) => {+ const seed = seedOfColor(entry.color);+ const value = values?.[name];+ return (+ <li+ key={name}+ className="flex items-center gap-1.5 font-mono text-[11px] text-muted-foreground"+ >+ <span className="size-2 rounded-[1px]" style={{ backgroundColor: rgb(seed.fill) }} />+ <span>{entry.label ?? name}</span>+ {value !== undefined ? (+ <span className="text-foreground">{valueFormatter(value)}</span>+ ) : null}+ </li>+ );+ })}+ </ul>+ );+}diff --git a/apps/web/src/components/dither-kit/cartesian-canvas.tsx b/apps/web/src/components/dither-kit/cartesian-canvas.tsxnew file mode 100644index 000000000..b7b0f6687--- /dev/null+++ b/apps/web/src/components/dither-kit/cartesian-canvas.tsx@@ -0,0 +1,388 @@+// @ts-nocheck+"use client";++import { type RefObject, useEffect, useMemo, useRef } from "react";+import { type ChartContextValue, useChart } from "./chart-context";+import {+ backingSize,+ bloomLayerStyle,+ easeInOutCubic,+ paintColumn,+ prefersReducedMotion,+ resample,+} from "./dither-paint";+import { rgb } from "./palette";++type Star = { key: string; xi: number; depth: number; phase: number };+type Surface = { top: number[]; floor: number[] };++type LoopArgs = {+ canvas: HTMLCanvasElement;+ bloomCanvas: HTMLCanvasElement | null;+ cols: number;+ rows: number;+ state: RefObject<ChartContextValue>;+ targets: RefObject<Record<string, Surface>>;+ stars: RefObject<Star[]>;+};++/**+ * The requestAnimationFrame paint loop — eases each series toward its target+ * surface, paints the dither fill (with the entrance reveal), then layers the+ * crosshair marker and winking stars on top. Lives outside the component so the+ * component stays small and this hot closure isn't re-created on every render.+ * Returns a cleanup that cancels the loop.+ */+function startCartesianLoop({+ canvas,+ bloomCanvas,+ cols,+ rows,+ state,+ targets,+ stars,+}: LoopArgs): (() => void) | undefined {+ const c = canvas.getContext("2d");+ if (!c || cols <= 0 || rows <= 0) return undefined;+ canvas.width = cols;+ canvas.height = rows;++ const off = document.createElement("canvas");+ off.width = cols;+ off.height = rows;+ const octx = off.getContext("2d");+ if (!octx) return undefined;++ // Bloom layer: a blurred, additive copy of the crisp canvas.+ const bloomCtx = bloomCanvas?.getContext("2d") ?? null;+ if (bloomCanvas) {+ bloomCanvas.width = cols;+ bloomCanvas.height = rows;+ }++ const reduce = prefersReducedMotion();+ const EASE = reduce ? 1 : 0.18;+ const animate = state.current.animate && !reduce;+ const duration = state.current.animationDuration;+ const current: Record<string, Surface> = {};++ // `reveal` (0–1) sweeps the fill in left-to-right on first paint.+ const paintFill = (intensity: number, reveal: number) => {+ octx.clearRect(0, 0, cols, rows);+ const s = state.current;+ const stacked = s.stackType === "stacked" || s.stackType === "percent";+ const revealCols = Math.ceil(reveal * cols);+ s.configKeys.forEach((key, si) => {+ const cur = current[key];+ if (!cur) return;+ const seed = s.seedOf(key);+ const variant = s.seriesSpecs[key]?.variant ?? "gradient";+ const isLine =+ (s.seriesSpecs[key]?.kind ?? (s.chartType === "line" ? "line" : "area")) === "line";+ const emphasis = s.selectedDataKey ?? s.focusDataKey;+ const dim = emphasis !== null && emphasis !== key ? 0.3 : 1;+ // Overlapping (non-stacked) layers thin out front-to-back so they+ // read as distinct layers instead of a muddy blend.+ const sparse = stacked ? 0 : si * 0.14;+ for (let x = 0; x < cols; x++) {+ if (x > revealCols) break;+ // For a value that dips below the zero baseline the value line ends up+ // *below* the floor in pixels; paintColumn needs the higher edge first,+ // so order the pair (a no-op for the common positive case).+ const a = cur.top[x] ?? 0;+ const b = cur.floor[x] ?? 0;+ paintColumn(octx, x, Math.min(a, b), Math.max(a, b), seed, {+ variant,+ intensity,+ dim,+ stacked: stacked && !isLine,+ sparse,+ });+ }+ });+ };++ let raf = 0;+ let tick = 0;+ let last = 0;+ let animStart = 0;+ let lastProg = -1;+ let lastRevision = state.current.revision;+ let entranceReported = !animate;+ let intensity = 0;+ let needsFill = true;+ let lastPaintSig = "";+ let lastSelected: string | null | undefined = Symbol() as never;++ const draw = (now: number) => {+ raf = requestAnimationFrame(draw);+ const s = state.current;+ if (!s.ready) return;+ // Keep the bloom layer in sync with the crisp canvas while it's active.+ if (bloomCtx) {+ const on = s.bloom !== "off" && (!s.bloomOnHover || s.isMouseInChart || s.hovered);+ if (on) {+ bloomCtx.clearRect(0, 0, cols, rows);+ bloomCtx.drawImage(canvas, 0, 0);+ }+ }+ const tgt = targets.current;+ if (s.revision !== lastRevision) {+ lastRevision = s.revision;+ animStart = 0; // re-play the entrance on data change / replay+ lastProg = -1;+ entranceReported = false;+ }+ if (!animStart) animStart = now;+ const prog = animate ? Math.min(1, (now - animStart) / duration) : 1;+ const progChanged = prog !== lastProg;+ // Tell the context the reveal is done so DOM markers fade in in sync.+ if (prog >= 1 && !entranceReported) {+ entranceReported = true;+ s.markEntranceDone();+ }++ let moving = false;+ for (const key of s.configKeys) {+ const t = tgt[key];+ if (!t) continue;+ const cur = current[key];+ if (!cur || cur.top.length !== cols) {+ current[key] = { top: t.top.slice(), floor: t.floor.slice() };+ needsFill = true;+ continue;+ }+ for (let x = 0; x < cols; x++) {+ const dt = t.top[x] - cur.top[x];+ const df = t.floor[x] - cur.floor[x];+ if (Math.abs(dt) > 0.01 || Math.abs(df) > 0.01) {+ cur.top[x] += dt * EASE;+ cur.floor[x] += df * EASE;+ moving = true;+ } else {+ cur.top[x] = t.top[x];+ cur.floor[x] = t.floor[x];+ }+ }+ }+ for (const key of Object.keys(current)) {+ if (!tgt[key]) {+ delete current[key];+ needsFill = true;+ }+ }+ if (moving) needsFill = true;+ const emphasisNow = s.selectedDataKey ?? s.focusDataKey;+ if (emphasisNow !== lastSelected) {+ lastSelected = emphasisNow;+ needsFill = true;+ }++ const itTarget = s.isMouseInChart || s.hovered ? 1 : 0;+ let settling = false;+ if (Math.abs(intensity - itTarget) > 0.001) {+ intensity += (itTarget - intensity) * 0.16;+ settling = true;+ needsFill = true;+ } else intensity = itTarget;++ // Live hover wins; the controlled markerIndex (e.g. a committed point)+ // is the fallback shown when nothing is hovered.+ const marker = s.hoverIndex != null ? s.hoverIndex : s.markerIndex;+ const winkDue = !reduce && now - last >= 100;+ // Repaint when a tweak-driven paint input changes (variant, stacking) so+ // the panel updates the fill live — without resetting the entrance reveal.+ const paintSig = `${s.stackType}|${s.configKeys+ .map((k) => s.seriesSpecs[k]?.variant ?? "")+ .join(",")}`;+ const sigChanged = paintSig !== lastPaintSig;+ if (sigChanged) {+ lastPaintSig = paintSig;+ needsFill = true;+ }+ if (!(moving || settling || winkDue || marker != null || progChanged || sigChanged)) return;+ if (progChanged) {+ lastProg = prog;+ needsFill = true;+ }+ if (winkDue) {+ last = now;+ tick += 1;+ }++ // Reveal front (left-to-right) — stars + crosshair stay behind it so+ // they don't float over the not-yet-drawn area during the entrance.+ const reveal = animate ? easeInOutCubic(prog) : 1;+ const revealCols = reveal * cols;++ if (needsFill) {+ paintFill(intensity, reveal);+ needsFill = false;+ }+ c.clearRect(0, 0, cols, rows);+ c.drawImage(off, 0, 0);++ const mx =+ marker != null && s.dataLength > 1+ ? Math.round((marker / (s.dataLength - 1)) * (cols - 1))+ : -1;+ if (mx >= 0 && mx <= revealCols) {+ for (const key of s.configKeys) {+ const cur = current[key];+ if (!cur) continue;+ const seed = s.seedOf(key);+ const my = Math.round(cur.top[mx] ?? 0);+ // Full-height column + a chunky marker block at the point — the+ // series colour at higher opacity, so it reads on either theme.+ c.fillStyle = rgb(seed.fill, 1, 0.55);+ for (let y = my; y < rows; y++) c.fillRect(mx, y, 1, 1);+ c.fillStyle = rgb(seed.fill);+ c.fillRect(mx - 1, my - 1, 3, 3);+ }+ }++ for (const star of stars.current) {+ const cur = current[star.key];+ if (!cur) continue;+ const sx = Math.round((star.xi / Math.max(s.dataLength - 1, 1)) * (cols - 1));+ if (sx > revealCols) continue; // behind the reveal front+ const top = cur.top[sx] ?? 0;+ const floor = cur.floor[sx] ?? rows - 1;+ const sy = Math.round(top + star.depth * (floor - top));+ const tw = reduce ? 0.85 : (Math.sin((tick + star.phase) * 0.35) + 1) / 2;+ const lift = tw * (0.7 + 0.3 * intensity);+ if (lift < 0.55 || sy < 0 || sy >= rows) continue;+ // Sparkles glint in the series colour via opacity (the `lift` wink)+ // rather than a lighter shade — so they never read as stray white+ // pixels on a light background.+ const starColor = s.seedOf(star.key).fill;+ c.fillStyle = rgb(starColor, 1, lift);+ c.fillRect(sx, sy, 1, 1);+ // At the peak of a wink the star flares into a 4-point glint.+ if (tw > 0.9) {+ c.fillStyle = rgb(starColor, 1, lift * 0.6 * (tw - 0.9) * 10);+ c.fillRect(sx - 1, sy, 1, 1);+ c.fillRect(sx + 1, sy, 1, 1);+ c.fillRect(sx, sy - 1, 1, 1);+ c.fillRect(sx, sy + 1, 1, 1);+ }+ }+ };++ raf = requestAnimationFrame(draw);+ return () => cancelAnimationFrame(raf);+}++/**+ * Continuous dither canvas for area and line charts. Each series is reduced to a+ * `[top, floor]` band per backing column: areas fill from their value line down+ * to their floor; lines fill only a thin glow band hugging the line. The shared+ * {@link paintColumn} renders the ordered-dither scatter, capped by the bright+ * series line, with winking stars + scrub crosshair on top.+ */+export function CartesianCanvas() {+ const ctx = useChart();+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const bloomRef = useRef<HTMLCanvasElement>(null);++ const { width, height } = ctx.plot;+ const { cols, rows } = backingSize(width, height);+ const { ready, chartType, configKeys, bands, seriesSpecs, y, dataLength } = ctx;++ // Memoized: the pricey bit in the render path — a `resample` per series to+ // the backing column count. The canvas re-renders on every hover/cursor tick+ // (it consumes ctx), so without this the whole surface is rebuilt each time.+ // Pinned to the exact ctx fields it reads, plus the backing geometry.+ const targets = useMemo(() => {+ const out: Record<string, Surface> = {};+ if (!ready) return out;+ const h = height || 1;+ const glow = Math.max(6, Math.round(rows * 0.16));+ const defaultKind = chartType === "line" ? "line" : "area";+ for (const key of configKeys) {+ const band = bands[key];+ if (!band) continue;+ const line = (seriesSpecs[key]?.kind ?? defaultKind) === "line";+ const top = band.map((b) => (y(b[1]) / h) * (rows - 1));+ const floor = band.map((b, i) =>+ line ? Math.min(rows - 1, top[i] + glow) : (y(b[0]) / h) * (rows - 1),+ );+ out[key] = { top: resample(top, cols), floor: resample(floor, cols) };+ }+ return out;+ }, [ready, chartType, configKeys, bands, seriesSpecs, y, height, rows, cols]);++ // Memoized: the star field is deterministic — only its shape (series ×+ // column count) matters, so it need not be rebuilt on unrelated re-renders.+ const stars = useMemo(() => {+ const out: Star[] = [];+ const per = Math.max(4, Math.round(cols / 14));+ configKeys.forEach((key, k) => {+ for (let i = 0; i < per; i++) {+ const seed = i * 67 + 13 + k * 131;+ out.push({+ key,+ xi: seed % Math.max(dataLength, 1),+ depth: ((seed * 53 + 7) % 100) / 100,+ phase: (seed * 41) % 360,+ });+ }+ });+ return out;+ }, [configKeys, dataLength, cols]);++ // The RAF loop reads these through refs so it always sees the latest values+ // without re-subscribing. Refs are written in an effect (never during+ // render) — mutating a ref mid-render is a React anti-pattern that tears+ // under Strict Mode / concurrent rendering.+ const stateRef = useRef(ctx);+ const targetsRef = useRef(targets);+ const starsRef = useRef(stars);+ useEffect(() => {+ stateRef.current = ctx;+ targetsRef.current = targets;+ starsRef.current = stars;+ });++ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return;+ return startCartesianLoop({+ canvas,+ bloomCanvas: bloomRef.current,+ cols,+ rows,+ state: stateRef,+ targets: targetsRef,+ stars: starsRef,+ });+ }, [cols, rows]);++ const bloomActive = ctx.bloomOnHover ? ctx.isMouseInChart || ctx.hovered : true;+ const bloom = bloomLayerStyle(ctx.bloom, bloomActive);+ const pos = {+ left: ctx.margins.left,+ top: ctx.margins.top,+ width,+ height,+ } as const;++ return (+ <>+ <canvas+ ref={canvasRef}+ className="pointer-events-none absolute"+ style={{ ...pos, imageRendering: "pixelated" }}+ />+ <canvas+ ref={bloomRef}+ className="pointer-events-none absolute"+ style={{+ ...pos,+ transition: "opacity 220ms ease",+ ...(bloom ?? { opacity: 0 }),+ }}+ />+ </>+ );+}diff --git a/apps/web/src/components/dither-kit/cartesian-root.tsx b/apps/web/src/components/dither-kit/cartesian-root.tsxnew file mode 100644index 000000000..4feb1a0b4--- /dev/null+++ b/apps/web/src/components/dither-kit/cartesian-root.tsx@@ -0,0 +1,182 @@+// @ts-nocheck+import { Children, type ComponentType, isValidElement, type ReactNode } from "react";+import {+ type ChartConfig,+ ChartContext,+ type ChartType,+ type Margins,+ useChartController,+} from "./chart-context";+import { CommonChartContext } from "./common-context";+import type { BloomInput } from "./dither-paint";+import { cn } from "./lib";+import type { StackType } from "./scales";+import { useChartDimensions } from "./use-chart-dimensions";++// `object` rather than `Record<string, unknown>`: interfaces don't get an+// implicit index signature, so interface-typed rows failed to satisfy the+// generic. Internal layers still index rows through their own Row type.+type Row = object;++const DEFAULT_MARGINS: Margins = {+ top: 10,+ right: 12,+ bottom: 22,+ left: 36,+};++export type CartesianChartProps<TData extends Row> = {+ data: TData[];+ config: ChartConfig;+ children: ReactNode;+ stackType?: StackType;+ margins?: Partial<Margins>;+ className?: string;+ animate?: boolean;+ animationDuration?: number;+ replayToken?: number; // change to re-play the entrance without remounting+ /** Set false for a decorative sparkline: keeps the hover lift but no scrub+ * crosshair / tooltip. */+ interactive?: boolean;+ /** Controlled crosshair position (e.g. a committed point) — overrides the+ * internal hover when set. */+ markerIndex?: number | null;+ /** Parent-driven hover (e.g. the whole card/row) — lifts the fill. */+ hovered?: boolean;+ /** Glow on the dither fill. */+ bloom?: BloomInput;+ /** Only bloom while the chart is hovered. */+ bloomOnHover?: boolean;+ /** Fires with the scrubbed index as the pointer moves (null on leave). */+ onHoverChange?: (index: number | null) => void;+ defaultSelectedDataKey?: string | null;+ onSelectionChange?: (key: string | null) => void;+};++/** Which render layer a composed part targets — defaults to the front SVG. */+function layerOf(node: ReactNode): "back" | "dom" | "svg" {+ if (!isValidElement(node) || typeof node.type === "string") return "svg";+ return (node.type as { chartLayer?: "back" | "dom" }).chartLayer ?? "svg";+}++/**+ * Shared root for the cartesian dither charts (area, line, bar). Owns the+ * measured size, the shared context, and pointer interaction; every visual is+ * composed as children. Back chrome (grid) sits behind the dither canvas; the+ * canvas paints the fill/line/bars + stars; front chrome (axes, dots) and DOM+ * legend/tooltip layer on top. `chartType` drives the scales/interaction and the+ * `Canvas` prop supplies the family's painter (continuous for area/line, bars for+ * bar) — so each chart ships only its own canvas.+ */+export function CartesianRoot<TData extends Row>({+ chartType,+ Canvas,+ data,+ config,+ children,+ stackType = "default",+ margins: marginsProp,+ className,+ animate = true,+ animationDuration = 900,+ replayToken = 0,+ interactive = true,+ markerIndex = null,+ hovered = false,+ bloom = "off",+ bloomOnHover = false,+ onHoverChange,+ defaultSelectedDataKey = null,+ onSelectionChange,+}: CartesianChartProps<TData> & {+ chartType: ChartType;+ Canvas: ComponentType;+}) {+ const { ref, size } = useChartDimensions<HTMLDivElement>();+ const margins = { ...DEFAULT_MARGINS, ...marginsProp };++ const ctx = useChartController({+ chartType,+ // Safe: the controller only reads row[key] for the configured series keys.+ data: data as Record<string, unknown>[],+ config,+ stackType,+ dimensions: size,+ margins,+ animate,+ animationDuration,+ replayToken,+ markerIndex,+ hovered,+ bloom,+ bloomOnHover,+ defaultSelectedDataKey,+ onSelectionChange,+ });++ const backChildren: ReactNode[] = [];+ const svgChildren: ReactNode[] = [];+ const domChildren: ReactNode[] = [];+ Children.forEach(children, (child) => {+ const layer = layerOf(child);+ if (layer === "back") backChildren.push(child);+ else if (layer === "dom") domChildren.push(child);+ else svgChildren.push(child);+ });++ const onMove = (clientX: number) => {+ const el = ref.current;+ if (!el) return;+ const rect = el.getBoundingClientRect();+ const px = clientX - rect.left - margins.left;+ const index = ctx.indexAtX(px);+ ctx.setHoverIndex(index);+ ctx.setCursorX(clientX - rect.left);+ onHoverChange?.(index);+ };++ return (+ <ChartContext value={ctx}>+ <CommonChartContext value={ctx.common}>+ <div+ ref={ref}+ className={cn("relative h-full w-full", className)}+ onPointerEnter={() => ctx.setMouseInChart(true)}+ onPointerMove={interactive ? (e) => onMove(e.clientX) : undefined}+ onPointerLeave={() => {+ ctx.setMouseInChart(false);+ ctx.setHoverIndex(null);+ onHoverChange?.(null);+ }}+ >+ {ctx.ready && backChildren.length > 0 && (+ <svg+ width={size.width}+ height={size.height}+ className="absolute inset-0 overflow-visible"+ aria-hidden+ role="presentation"+ >+ <g transform={`translate(${margins.left},${margins.top})`}>{backChildren}</g>+ </svg>+ )}+ <Canvas />+ {ctx.ready && (+ <svg+ width={size.width}+ height={size.height}+ className="absolute inset-0 overflow-visible"+ role="img"+ aria-label="Chart"+ >+ <g transform={`translate(${margins.left},${margins.top})`}>{svgChildren}</g>+ </svg>+ )}+ {domChildren}+ </div>+ </CommonChartContext>+ </ChartContext>+ );+}++export type AreaChartProps<TData extends Row> = CartesianChartProps<TData>;diff --git a/apps/web/src/components/dither-kit/chart-context.tsx b/apps/web/src/components/dither-kit/chart-context.tsxnew file mode 100644index 000000000..4c7cd1b24--- /dev/null+++ b/apps/web/src/components/dither-kit/chart-context.tsx@@ -0,0 +1,484 @@+// @ts-nocheck+import type { ScaleLinear } from "d3-scale";+import { createContext, use, useCallback, useMemo, useState } from "react";+import type { CommonChart } from "./common-context";+import type { BloomInput } from "./dither-paint";+import type { DitherColor, Seed } from "./palette";+import { seedOfColor } from "./palette";+import {+ buildBandScale,+ buildXScale,+ buildYScale,+ computeBands,+ indexAtBand,+ nearestIndex,+ type StackType,+} from "./scales";+import type { Dimensions } from "./use-chart-dimensions";++/** Which chart root a part is composed under — drives the boundary guards. */+export type ChartType = "area" | "bar" | "line" | "pie" | "radar";++export type ChartConfig = Record<string, { label?: string; color: DitherColor }>;++export type Margins = {+ top: number;+ right: number;+ bottom: number;+ left: number;+};++type Row = Record<string, unknown>;++export type AreaVariant = "gradient" | "dotted" | "hatched" | "solid";+export type StrokeVariant = "solid" | "dashed";+export type SeriesKind = "area" | "line" | "bar";++/** What each series part (<Area />, <Line />, <Bar />) registers so the canvas+ * knows which series to paint and how. */+export type SeriesSpec = {+ dataKey: string;+ kind: SeriesKind;+ variant: AreaVariant;+ strokeVariant: StrokeVariant;+};++export type ChartContextValue = {+ chartType: ChartType; // which root this part is under+ config: ChartConfig;+ configKeys: string[]; // series order — drives stacking + legend+ data: Row[];+ dataLength: number;+ stackType: StackType;++ margins: Margins;+ plot: { width: number; height: number }; // inner drawing area+ ready: boolean; // true once measured (width > 0)++ xCenter: (index: number) => number; // category centre px within the plot+ bandwidth: number; // category slot width (0 for point/area scales)+ indexAtX: (px: number) => number; // nearest category for a pointer x+ // Bar geometry in plot px — one source of truth for the canvas + click rects.+ barSlot: (+ index: number,+ seriesIndex: number,+ seriesCount: number,+ ) => { x: number; width: number };+ y: ScaleLinear<number, number>; // value → px within the plot+ bands: Record<string, [number, number][]>; // per-series [y0, y1] per row+ max: number;+ min: number; // most-negative value (0 when nothing dips below the baseline)++ // Interaction state, shared by every part.+ selectedDataKey: string | null;+ selectDataKey: (key: string | null) => void;+ /** Legend-hover spotlight — dims every series but this one while set. */+ focusDataKey: string | null;+ setFocusDataKey: (key: string | null) => void;+ hoverIndex: number | null;+ setHoverIndex: (index: number | null) => void;+ markerIndex: number | null; // controlled crosshair override (e.g. committed point)+ cursorX: number;+ setCursorX: (px: number) => void;+ isMouseInChart: boolean;+ setMouseInChart: (over: boolean) => void;+ hovered: boolean; // parent-driven hover (e.g. the whole card) — lifts the fill+ bloom: BloomInput; // glow on the dither canvas+ bloomOnHover: boolean; // only bloom while hovered++ // Series register themselves so the canvas knows what (and how) to paint.+ seriesSpecs: Record<string, SeriesSpec>;+ registerSeries: (spec: SeriesSpec) => void;+ unregisterSeries: (dataKey: string) => void;++ // Entrance animation (prop-driven). `revision` bumps when the data changes or+ // the replay token advances, so the canvas can re-play its entrance.+ animate: boolean;+ animationDuration: number;+ revision: number;+ entranceDone: boolean; // true once the entrance has played — gates SVG markers+ markEntranceDone: () => void; // the canvas calls this when its reveal completes++ // Helpers.+ seedOf: (key: string) => Seed;+ common: CommonChart; // shared surface for <Legend> / <Tooltip>+};++const ChartContext = createContext<ChartContextValue | null>(null);++const ROOT_OF: Record<ChartType, string> = {+ area: "<AreaChart />",+ bar: "<BarChart />",+ line: "<LineChart />",+ pie: "<PieChart />",+ radar: "<RadarChart />",+};++/** Generic accessor for internal layers (canvas/overlay) that work for any root. */+export function useChart() {+ const ctx = use(ChartContext);+ if (!ctx) {+ throw new Error("Chart parts must be used within a chart root (e.g. <AreaChart />).");+ }+ return ctx;+}++/**+ * Boundary guard for a composable part. Throws a precise error when used outside+ * a root, or inside the wrong chart type — e.g. `<Bar />` placed in an area+ * chart. `kind` omitted means the part works under any root (grid, axes, …).+ */+export function useChartPart(part: string, kind?: ChartType | ChartType[]): ChartContextValue {+ const ctx = use(ChartContext);+ if (!ctx) {+ const where = kind ? ROOT_OF[Array.isArray(kind) ? kind[0] : kind] : "a chart root";+ throw new Error(`<${part} /> must be used within ${where}.`);+ }+ if (kind) {+ const allowed = Array.isArray(kind) ? kind : [kind];+ if (!allowed.includes(ctx.chartType)) {+ throw new Error(+ `<${part} /> is not valid inside ${ROOT_OF[ctx.chartType]} — it belongs in ${allowed+ .map((k) => ROOT_OF[k])+ .join(" or ")}.`,+ );+ }+ }+ return ctx;+}++export { ChartContext };++/** A counter that advances whenever `data` changes identity or `token` advances+ * — drives entrance replays without remounting. Uses the adjust-state-during-+ * render pattern (https://react.dev/reference/react/useState) instead of a ref:+ * the revision is derived purely from render inputs, so it stays consistent+ * across the memoized values below rather than lagging a render behind. */+export function useRevision(data: unknown, token: number) {+ const [prev, setPrev] = useState({ data, token, revision: 0 });+ if (prev.data !== data || prev.token !== token) {+ const next = { data, token, revision: prev.revision + 1 };+ setPrev(next);+ return next.revision;+ }+ return prev.revision;+}++/**+ * Builds the shared context value: resolves the plot rect from the measured+ * size minus margins, computes the x/y scales and the per-series stack bands,+ * and owns the selection + hover state every part reads.+ */+export function useChartController({+ chartType,+ data,+ config,+ stackType,+ dimensions,+ margins,+ animate = true,+ animationDuration = 900,+ replayToken = 0,+ markerIndex = null,+ hovered = false,+ bloom = "off",+ bloomOnHover = false,+ defaultSelectedDataKey = null,+ onSelectionChange,+}: {+ chartType: ChartType;+ data: Row[];+ config: ChartConfig;+ stackType: StackType;+ dimensions: Dimensions;+ margins: Margins;+ animate?: boolean;+ animationDuration?: number;+ replayToken?: number;+ markerIndex?: number | null;+ hovered?: boolean;+ bloom?: BloomInput;+ bloomOnHover?: boolean;+ defaultSelectedDataKey?: string | null;+ onSelectionChange?: (key: string | null) => void;+}): ChartContextValue {+ // This object becomes the ChartContext value, so its identity — and the+ // identity of every function/object it carries — must stay stable across+ // renders that don't change the underlying inputs. Otherwise every consumer+ // (axes, legend, tooltip, dots) re-renders on every parent render. So the+ // expensive derivations, the exposed callbacks, and the returned value are+ // memoized below; only cheap scalars (bandwidth, ready, plot sizes) are left+ // bare, since they're just recomputed reads, not identities anyone depends on.++ // Memoized: configKeys is the dep that drives `bands`, `common` and the+ // canvas `targets` memo — a fresh array each render would bust all of them.+ const configKeys = useMemo(() => Object.keys(config), [config]);+ const revision = useRevision(data, replayToken);++ const [selectedDataKey, setSelectedDataKey] = useState<string | null>(defaultSelectedDataKey);+ const [focusDataKey, setFocusDataKey] = useState<string | null>(null);+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);+ const [cursorX, setCursorX] = useState(0);+ const [isMouseInChart, setMouseInChart] = useState(false);+ const [seriesSpecs, setSeriesSpecs] = useState<Record<string, SeriesSpec>>({});++ // useCallback because the series effects in area.tsx/bar.tsx list these as+ // deps — without stable identities the unregister/register effect re-fires+ // every render and its setState pair loops ("Maximum update depth exceeded").+ const registerSeries = useCallback((spec: SeriesSpec) => {+ setSeriesSpecs((prev) => {+ const cur = prev[spec.dataKey];+ return cur &&+ cur.kind === spec.kind &&+ cur.variant === spec.variant &&+ cur.strokeVariant === spec.strokeVariant+ ? prev+ : { ...prev, [spec.dataKey]: spec };+ });+ }, []);+ const unregisterSeries = useCallback((dataKey: string) => {+ setSeriesSpecs((prev) => {+ if (!(dataKey in prev)) return prev;+ const next = { ...prev };+ delete next[dataKey];+ return next;+ });+ }, []);++ // Stable so the memoized value keeps its identity; only re-created when the+ // caller's selection handler does.+ const selectDataKey = useCallback(+ (key: string | null) => {+ setSelectedDataKey(key);+ onSelectionChange?.(key);+ },+ [onSelectionChange],+ );++ // The root spreads `{ ...DEFAULT_MARGINS, ...marginsProp }` fresh every+ // render, so `margins` never keeps its identity. Pin one off the four numbers+ // so it doesn't, on its own, invalidate the value or the plot geometry.+ const { top: mTop, right: mRight, bottom: mBottom, left: mLeft } = margins;+ const stableMargins = useMemo(+ () => ({ top: mTop, right: mRight, bottom: mBottom, left: mLeft }),+ [mTop, mRight, mBottom, mLeft],+ );++ const plotWidth = Math.max(0, dimensions.width - mLeft - mRight);+ const plotHeight = Math.max(0, dimensions.height - mTop - mBottom);+ const ready = plotWidth > 0 && plotHeight > 0;++ // The entrance gate flips true when the canvas reveal completes (via+ // `markEntranceDone`) so DOM markers fade in with the fill, and re-arms on+ // each replay. Adjust-state-during-render instead of an effect, so the reset+ // lands in the same render as the revision bump.+ const [entrance, setEntrance] = useState({ revision, done: !animate });+ if (entrance.revision !== revision) {+ setEntrance({ revision, done: !animate });+ }+ const entranceDone = entrance.revision === revision ? entrance.done : !animate;+ // Stable across renders at the same revision; the canvas holds this in a ref.+ const markEntranceDone = useCallback(() => setEntrance({ revision, done: true }), [revision]);++ // Memoized: the priciest derivation in the render path — it walks every+ // row × series to build the stack bands. Hover/cursor state changes must not+ // recompute it, only a real data/series/stack change.+ const { bands, max, min } = useMemo(+ () => computeBands(data, configKeys, stackType),+ [data, configKeys, stackType],+ );++ const isBar = chartType === "bar";+ // The d3 scale factories are memoized so `y` keeps a stable identity: the+ // canvas `targets` memo (cartesian-canvas / bar-canvas) deps on ctx.y, and+ // xCenter/indexAtX/barSlot below close over these.+ const xPoint = useMemo(() => buildXScale(data.length, plotWidth), [data.length, plotWidth]);+ const xBand = useMemo(() => buildBandScale(data.length, plotWidth), [data.length, plotWidth]);+ const bandwidth = isBar ? xBand.bandwidth() : 0;+ const xCenter = useCallback(+ (i: number) => (isBar ? (xBand(i) ?? 0) + xBand.bandwidth() / 2 : (xPoint(i) ?? 0)),+ [isBar, xBand, xPoint],+ );+ const indexAtX = useCallback(+ (px: number) =>+ isBar ? indexAtBand(px, data.length, plotWidth) : nearestIndex(px, data.length, plotWidth),+ [isBar, data.length, plotWidth],+ );+ const stacked = stackType === "stacked" || stackType === "percent";+ const barSlot = useCallback(+ (i: number, si: number, n: number) => {+ const center = xCenter(i);+ if (stacked) {+ const w = bandwidth * 0.9;+ return { x: center - w / 2, width: w };+ }+ const slot = bandwidth / Math.max(n, 1);+ return {+ x: center - bandwidth / 2 + si * slot + slot * 0.08,+ width: slot * 0.84,+ };+ },+ [xCenter, stacked, bandwidth],+ );+ const y = useMemo(() => buildYScale(min, max, plotHeight), [min, max, plotHeight]);++ // Stable so `common` and the value stay stable; re-created only on config.+ const seedOf = useCallback((key: string) => seedOfColor(config[key]?.color ?? "grey"), [config]);++ // Memoized: this is the value handed to CommonChartContext (Legend/Tooltip),+ // so it needs its own stable identity independent of the parent value.+ const common: CommonChart = useMemo(+ () => ({+ names: configKeys,+ labelOf: (n) => config[n]?.label ?? n,+ seedOf,+ selectedDataKey,+ selectDataKey,+ focusDataKey,+ setFocusDataKey,+ hoverIndex,+ ready,+ tooltipLeft: Math.max(48, Math.min(plotWidth + mLeft - 48, cursorX)),+ // Follow the highest hovered node so the card rides the data path, but+ // keep enough headroom that the upward-lifted card never clips the top.+ tooltipTop: (() => {+ const floor = mTop + 44;+ if (hoverIndex == null) return floor;+ let minY = Number.POSITIVE_INFINITY;+ for (const key of configKeys) {+ const b = bands[key]?.[hoverIndex];+ if (b) minY = Math.min(minY, y(b[1]));+ }+ if (!Number.isFinite(minY)) return floor;+ return Math.max(floor, mTop + minY);+ })(),+ heading: (i, labelKey) => (labelKey ? String(data[i]?.[labelKey] ?? "") : null),+ itemsAt: (i) =>+ configKeys.map((name) => {+ const raw = data[i]?.[name];+ return {+ name,+ label: config[name]?.label ?? name,+ value: typeof raw === "number" ? raw : 0,+ seed: seedOf(name),+ dimmed: (() => {+ const emphasis = selectedDataKey ?? focusDataKey;+ return emphasis !== null && emphasis !== name;+ })(),+ };+ }),+ }),+ [+ configKeys,+ config,+ seedOf,+ selectedDataKey,+ selectDataKey,+ focusDataKey,+ setFocusDataKey,+ hoverIndex,+ ready,+ plotWidth,+ mLeft,+ mTop,+ cursorX,+ bands,+ y,+ data,+ ],+ );++ // Memoized: this is the ChartContext value. A fresh object here would+ // re-render every consumer on every parent render — the whole reason the+ // pieces above are stabilized. Rebuilds only when a listed input changes+ // (which is exactly when a consumer needs the update). The useState setters+ // are listed but never change identity, so they never trigger a rebuild.+ return useMemo<ChartContextValue>(+ () => ({+ chartType,+ config,+ configKeys,+ data,+ dataLength: data.length,+ stackType,+ margins: stableMargins,+ plot: { width: plotWidth, height: plotHeight },+ ready,+ xCenter,+ bandwidth,+ indexAtX,+ barSlot,+ y,+ bands,+ max,+ min,+ selectedDataKey,+ selectDataKey,+ focusDataKey,+ setFocusDataKey,+ hoverIndex,+ setHoverIndex,+ markerIndex,+ cursorX,+ setCursorX,+ isMouseInChart,+ setMouseInChart,+ hovered,+ bloom,+ bloomOnHover,+ seriesSpecs,+ registerSeries,+ unregisterSeries,+ animate,+ animationDuration,+ revision,+ entranceDone,+ markEntranceDone,+ seedOf,+ common,+ }),+ [+ chartType,+ config,+ configKeys,+ data,+ stackType,+ stableMargins,+ plotWidth,+ plotHeight,+ ready,+ xCenter,+ bandwidth,+ indexAtX,+ barSlot,+ y,+ bands,+ max,+ min,+ selectedDataKey,+ selectDataKey,+ focusDataKey,+ setFocusDataKey,+ hoverIndex,+ setHoverIndex,+ markerIndex,+ cursorX,+ setCursorX,+ isMouseInChart,+ setMouseInChart,+ hovered,+ bloom,+ bloomOnHover,+ seriesSpecs,+ registerSeries,+ unregisterSeries,+ animate,+ animationDuration,+ revision,+ entranceDone,+ markEntranceDone,+ seedOf,+ common,+ ],+ );+}diff --git a/apps/web/src/components/dither-kit/common-context.tsx b/apps/web/src/components/dither-kit/common-context.tsxnew file mode 100644index 000000000..372bfd590--- /dev/null+++ b/apps/web/src/components/dither-kit/common-context.tsx@@ -0,0 +1,47 @@+// @ts-nocheck+"use client";++import { createContext, use } from "react";+import type { Seed } from "./palette";++/** A single tooltip row — one series (cartesian/radar) or one slice (pie). */+export type TooltipItem = {+ name: string;+ label: string;+ value: number;+ seed: Seed;+ dimmed: boolean;+};++/**+ * The minimal surface shared by every chart family, so `<Legend>` and+ * `<Tooltip>` work identically whether they sit in a cartesian, bar, or polar+ * root. Each root publishes one of these alongside its family-specific context.+ */+export type CommonChart = {+ names: string[]; // legend entries — series keys (cartesian) or slice names (pie)+ labelOf: (name: string) => string;+ seedOf: (name: string) => Seed;+ selectedDataKey: string | null;+ selectDataKey: (key: string | null) => void;+ /** Transient legend-hover emphasis — spotlights one series (others dim)+ * while the pointer rests on its legend entry. Selection still wins. */+ focusDataKey: string | null;+ setFocusDataKey: (key: string | null) => void;+ hoverIndex: number | null;+ heading: (index: number, labelKey?: string) => string | null;+ itemsAt: (index: number) => TooltipItem[];+ ready: boolean;+ tooltipLeft: number; // clamped px for the floating tooltip+ tooltipTop: number; // px — follows the hovered node (cartesian) / cursor (polar)+};++export const CommonChartContext = createContext<CommonChart | null>(null);++export function useCommonChart() {+ const ctx = use(CommonChartContext);+ if (!ctx) {+ throw new Error("<Legend /> / <Tooltip /> must be used within a chart root.");+ }+ return ctx;+}diff --git a/apps/web/src/components/dither-kit/dither-paint.ts b/apps/web/src/components/dither-kit/dither-paint.tsnew file mode 100644index 000000000..3e91698b6--- /dev/null+++ b/apps/web/src/components/dither-kit/dither-paint.ts@@ -0,0 +1,170 @@+// @ts-nocheck+import type { AreaVariant } from "./chart-context";+import { rgb, type Seed } from "./palette";++// 4×4 ordered (Bayer) matrix, normalized to 0–1 thresholds — the exact matrix+// the legacy chart dithers with.+export const BAYER = [+ [0, 8, 2, 10],+ [12, 4, 14, 6],+ [3, 11, 1, 9],+ [15, 7, 13, 5],+].map((row) => row.map((v) => (v + 0.5) / 16));++export const CELL = 2; // css px per dither cell — chunky enough to read pixelated+export const MAX_COLS = 520;+export const MAX_ROWS = 200;+// Opacity of the top border outline (just under solid, so it reads as a soft+// edge rather than a hard line). See the note on colour vs opacity below.+export const BORDER_ALPHA = 0.72;+// Opacity of a dither "off" cell relative to an "on" cell. The scatter modulates+// between these two tiers of the *same* colour instead of leaving holes, so the+// background never shows through as stark white on a light theme.+export const OFF_TIER = 0.4;++export type PaintOpts = {+ variant: AreaVariant;+ intensity: number; // 0–1 hover lift+ dim: number; // selection dim multiplier (0.3 dimmed, 1 normal)+ stacked: boolean; // denser + solid floor when layers stack+ sparse?: number; // raise the dither threshold (thin out) — front layers+};++// Colour vs opacity — the guiding rule for the whole engine:+//+// Work with opacities instead of different shades of the same color. This will+// make sure it looks good on both light and dark mode.+//+// So every pixel is the series' single `fill` colour and we vary only its alpha.+// The old lighter `line` / near-white `star` shades were dropped: a shade that+// pops on a dark background reads as a jarring bright speck on a light one, while+// the same colour at a lower opacity simply blends into whatever sits behind it.++/**+ * Fill one backing-canvas column `x` from row `top` down to `floor` with the+ * ordered-dither scatter — solid at the floor, dissolving upward so it *fades+ * out toward the value line* — then cap the top with a soft border outline in+ * the series colour. Density drives opacity (see the note above), so the fade+ * reads correctly against both light and dark backgrounds. The single source of+ * the dither look across area / line / bar.+ */+export function paintColumn(+ octx: CanvasRenderingContext2D,+ x: number,+ top: number,+ floor: number,+ seed: Seed,+ { variant, intensity, dim, stacked, sparse = 0 }: PaintOpts,+) {+ const t = Math.round(top);+ const f = Math.round(floor);+ const depth = f - t;+ if (depth <= 0) {+ octx.fillStyle = rgb(seed.fill, 1, BORDER_ALPHA * dim);+ octx.fillRect(x, t, 1, 1);+ return;+ }+ const bias = (variant === "dotted" ? 0.12 : 0) + (stacked ? 0.2 : 0) - sparse;+ for (let y = t; y < f; y++) {+ // Inverted falloff: 0 at the top line, 1 at the floor — dense at the+ // bottom, thinning as it rises toward the outline.+ let density = (y - t) / depth;+ if (stacked) density = 0.5 + 0.5 * density;+ if (variant === "hatched" && ((x + y) & 3) >= 2) continue;+ const lit = variant === "solid" || density > BAYER[y & 3][x & 3] - 0.1 * intensity - bias;+ // "dotted" keeps real gaps for its open look; every other variant covers+ // the cell and lets the dither ride the alpha (on = full tier, off = a+ // faint tint) so nothing shows the background through as white.+ if (variant === "dotted" && !lit) continue;+ // Density → alpha (see the colour-vs-opacity note above).+ const k = (0.3 + density * 0.7) * (1 + 0.22 * intensity);+ const alpha = clamp01((lit ? k : k * OFF_TIER) * dim);+ octx.fillStyle = rgb(seed.fill, 1, alpha);+ octx.fillRect(x, y, 1, 1);+ }+ // Top border outline — the shape's edge now that the fill fades out here.+ // Kept just under full opacity, with a faint feather row beneath, so it reads+ // as a soft edge rather than a hard line floating over the fade.+ octx.fillStyle = rgb(seed.fill, 1, BORDER_ALPHA * dim);+ octx.fillRect(x, t, 1, 1);+ if (depth > 1) {+ octx.fillStyle = rgb(seed.fill, 1, BORDER_ALPHA * 0.5 * dim);+ octx.fillRect(x, t + 1, 1, 1);+ }+}++/** Linear-resample a per-index fraction array to `cols` columns. */+export function resample(src: number[], cols: number): number[] {+ const out = new Array<number>(cols);+ const last = Math.max(src.length - 1, 1);+ for (let c = 0; c < cols; c++) {+ const t = (c / Math.max(cols - 1, 1)) * last;+ const i = Math.floor(t);+ const f = t - i;+ const a = src[i] ?? 0;+ const b = src[Math.min(i + 1, src.length - 1)] ?? a;+ out[c] = a + (b - a) * f;+ }+ return out;+}++/** Backing-canvas resolution for a plot rect — low-res, scaled up `pixelated`. */+export function backingSize(width: number, height: number) {+ return {+ cols: Math.min(MAX_COLS, Math.max(8, Math.round(width / CELL))),+ rows: Math.min(MAX_ROWS, Math.max(8, Math.round(height / CELL))),+ };+}++// Bloom — a real "shader" glow that comes from the colours themselves: a blurred+// copy of the rendered canvas, composited additively (`plus-lighter`) so each+// hue blooms in its own colour instead of a grey wash. Lives on a second canvas+// layered over the crisp one (which stays sharp/pixelated).+export type BloomLevel = "off" | "low" | "high" | "aura";+export type BloomBlend = "plus-lighter" | "screen" | "lighten";+export type BloomConfig = {+ blur: number; // px+ brightness: number; // 1 = none+ opacity: number; // 0–1+ /** Saturation of the glow — >1 keeps it vividly in the dither's colour+ * instead of washing toward white. */+ saturate?: number;+ blend?: BloomBlend; // additive by default+};+/** A preset name, a full config, or "off". */+export type BloomInput = BloomLevel | BloomConfig;++const PRESET: Record<Exclude<BloomLevel, "off">, BloomConfig> = {+ low: { blur: 3, brightness: 1.35, opacity: 0.7, saturate: 1.4 },+ high: { blur: 5, brightness: 1.5, opacity: 0.78, saturate: 1.5 },+ aura: { blur: 15, brightness: 2.9, opacity: 0.1, saturate: 3 },+};++export type BloomStyle = {+ filter: string;+ opacity: number;+ mixBlendMode: BloomBlend;+ imageRendering: "auto";+};++/** Style for the bloom *layer* canvas (a blurred, additive copy). null when off. */+export function bloomLayerStyle(input: BloomInput, active: boolean): BloomStyle | null {+ if (!active || input === "off") return null;+ const cfg = typeof input === "string" ? PRESET[input] : input;+ return {+ filter: `blur(${cfg.blur}px) brightness(${cfg.brightness}) saturate(${cfg.saturate ?? 1})`,+ opacity: cfg.opacity,+ mixBlendMode: cfg.blend ?? "plus-lighter",+ imageRendering: "auto",+ };+}++// Easing — gentle start + soft settle so entrances don't feel linear.+export const easeInOutCubic = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);+export const easeOutCubic = (t: number) => 1 - (1 - t) ** 3;+export const clamp01 = (t: number) => (t < 0 ? 0 : t > 1 ? 1 : t);++/** Whether the OS asks for reduced motion (snap + steady stars). */+export function prefersReducedMotion() {+ return window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches ?? false;+}diff --git a/apps/web/src/components/dither-kit/dot.tsx b/apps/web/src/components/dither-kit/dot.tsxnew file mode 100644index 000000000..e87eb817e--- /dev/null+++ b/apps/web/src/components/dither-kit/dot.tsx@@ -0,0 +1,82 @@+// @ts-nocheck+import { useChart } from "./chart-context";+import { rgb, type Seed } from "./palette";+import { useSeries } from "./series-context";++export type DotVariant = "border" | "colored-border" | "filled";++function dotPaint(variant: DotVariant, seed: Seed) {+ switch (variant) {+ case "colored-border":+ return {+ fill: "var(--card, #0b0b0c)",+ stroke: rgb(seed.line),+ strokeWidth: 1.5,+ };+ case "filled":+ return { fill: rgb(seed.star), stroke: rgb(seed.line), strokeWidth: 1 };+ default:+ return {+ fill: "var(--card, #0b0b0c)",+ stroke: rgb(seed.star, 0.8),+ strokeWidth: 1,+ };+ }+}++/** A marker at every data point along the series' top line. */+export function Dot({ variant = "border", r = 2 }: { variant?: DotVariant; r?: number }) {+ const ctx = useChart();+ const { dataKey, seed } = useSeries("Dot");+ const band = ctx.bands[dataKey];+ if (!ctx.ready || !band) return null;+ const paint = dotPaint(variant, seed);++ return (+ // Fade in once the fill has drawn so dots don't float over the entrance.+ <g+ style={{+ opacity: ctx.entranceDone ? 1 : 0,+ transition: "opacity 300ms ease",+ }}+ >+ {band.map((b, i) => (+ <circle+ {...paint}+ // biome-ignore lint/suspicious/noArrayIndexKey: index is the stable x position+ key={i}+ cx={ctx.xCenter(i) ?? 0}+ cy={ctx.y(b[1])}+ r={r}+ />+ ))}+ </g>+ );+}++/** A single marker at the hovered point — keys off the shared hover index. */+export function ActiveDot({+ variant = "colored-border",+ r = 3,+}: {+ variant?: DotVariant;+ r?: number;+}) {+ const ctx = useChart();+ const { dataKey, seed } = useSeries("ActiveDot");+ const band = ctx.bands[dataKey];+ if (!ctx.ready || !band || ctx.hoverIndex == null || !ctx.entranceDone) return null;+ const b = band[ctx.hoverIndex];+ if (!b) return null;+ const paint = dotPaint(variant, seed);+ const cx = ctx.xCenter(ctx.hoverIndex);+ const cy = ctx.y(b[1]);++ return (+ <g>+ {/* Soft halo so the active point is unmistakable over the dither. */}+ <circle cx={cx} cy={cy} r={r + 3} fill={rgb(seed.line, 1, 0.18)} />+ <circle cx={cx} cy={cy} r={r} {...paint} strokeWidth={2} />+ </g>+ );+}diff --git a/apps/web/src/components/dither-kit/grid.tsx b/apps/web/src/components/dither-kit/grid.tsxnew file mode 100644index 000000000..2c4af7c10--- /dev/null+++ b/apps/web/src/components/dither-kit/grid.tsx@@ -0,0 +1,39 @@+// @ts-nocheck+import { useChartPart } from "./chart-context";++export function Grid({+ horizontal = true,+ vertical = false,+ strokeDasharray = "3 3",+}: {+ horizontal?: boolean;+ vertical?: boolean;+ strokeDasharray?: string;+}) {+ const ctx = useChartPart("Grid");+ if (!ctx.ready) return null;+ const { width } = ctx.plot;++ return (+ <g className="stroke-border" strokeDasharray={strokeDasharray}>+ {horizontal &&+ ctx.y+ .ticks(4)+ .map((t) => <line key={`h-${t}`} x1={0} x2={width} y1={ctx.y(t)} y2={ctx.y(t)} />)}+ {vertical &&+ ctx.data.map((_, i) => (+ <line+ // biome-ignore lint/suspicious/noArrayIndexKey: index is the stable x position+ key={`v-${i}`}+ x1={ctx.xCenter(i) ?? 0}+ x2={ctx.xCenter(i) ?? 0}+ y1={0}+ y2={ctx.plot.height}+ />+ ))}+ </g>+ );+}++// Render beneath the dither canvas so grid lines sit behind the fill.+Grid.chartLayer = "back" as const;diff --git a/apps/web/src/components/dither-kit/legend.tsx b/apps/web/src/components/dither-kit/legend.tsxnew file mode 100644index 000000000..8f9dbae97--- /dev/null+++ b/apps/web/src/components/dither-kit/legend.tsx@@ -0,0 +1,64 @@+// @ts-nocheck+"use client";++import { useCommonChart } from "./common-context";+import { cn } from "./lib";+import { rgb } from "./palette";++/** Series/slice legend. With `isClickable`, each entry toggles its selection.+ * Works in every chart family via the shared common context.+ *+ * Note: this is an absolute overlay pinned to the top of the plot, so it's best+ * for ≤2–3 entries. With more entries (or a narrow container) it wraps onto+ * extra rows that overlay the chart — reach for the in-flow `<BlockLegend>`+ * instead, which renders as a sibling and can't overlap at any width. */+export function Legend({+ isClickable = false,+ align = "right",+}: {+ isClickable?: boolean;+ align?: "left" | "center" | "right";+}) {+ const chart = useCommonChart();++ return (+ <div+ className={cn(+ "pointer-events-none absolute inset-x-0 top-0 flex flex-wrap gap-3 px-1",+ align === "right" && "justify-end",+ align === "center" && "justify-center",+ align === "left" && "justify-start",+ )}+ >+ {chart.names.map((name) => {+ const seed = chart.seedOf(name);+ const emphasis = chart.selectedDataKey ?? chart.focusDataKey;+ const dimmed = emphasis !== null && emphasis !== name;+ return (+ <button+ key={name}+ type="button"+ disabled={!isClickable}+ onClick={() => chart.selectDataKey(chart.selectedDataKey === name ? null : name)}+ // Hovering an entry spotlights its series so overlapping layers+ // (e.g. two meshed radar polygons) can be told apart at a glance.+ onPointerEnter={() => chart.setFocusDataKey(name)}+ onPointerLeave={() => chart.setFocusDataKey(null)}+ onFocus={() => chart.setFocusDataKey(name)}+ onBlur={() => chart.setFocusDataKey(null)}+ className={cn(+ "flex items-center gap-1.5 font-mono text-[11px] text-muted-foreground transition-opacity",+ isClickable && "pointer-events-auto cursor-pointer hover:text-foreground",+ dimmed && "opacity-40",+ )}+ >+ <span className="size-2 rounded-[1px]" style={{ backgroundColor: rgb(seed.fill) }} />+ {chart.labelOf(name)}+ </button>+ );+ })}+ </div>+ );+}++Legend.chartLayer = "dom" as const;diff --git a/apps/web/src/components/dither-kit/lib.ts b/apps/web/src/components/dither-kit/lib.tsnew file mode 100644index 000000000..6d6936209--- /dev/null+++ b/apps/web/src/components/dither-kit/lib.ts@@ -0,0 +1,9 @@+// @ts-nocheck+import { type ClassValue, clsx } from "clsx";+import { twMerge } from "tailwind-merge";++/** Tailwind-aware className combiner — local copy so the chart pack is+ * self-contained and portable as a registry. */+export function cn(...inputs: ClassValue[]) {+ return twMerge(clsx(inputs));+}diff --git a/apps/web/src/components/dither-kit/palette.ts b/apps/web/src/components/dither-kit/palette.tsnew file mode 100644index 000000000..a18ec7929--- /dev/null+++ b/apps/web/src/components/dither-kit/palette.ts@@ -0,0 +1,34 @@+// @ts-nocheck+export type Rgb = [number, number, number];++export type DitherColor = "green" | "blue" | "purple" | "pink" | "orange" | "red" | "grey";++export type Seed = { fill: Rgb; line: Rgb; star: Rgb };++// Each seed: the area-fill hue, the bright series line, and the star sparkle.+export const PALETTE: Record<DitherColor, Seed> = {+ green: { fill: [40, 210, 110], line: [150, 255, 180], star: [200, 255, 220] },+ blue: { fill: [53, 143, 243], line: [150, 200, 255], star: [205, 228, 255] },+ purple: {+ fill: [150, 110, 255],+ line: [200, 175, 255],+ star: [225, 210, 255],+ },+ pink: { fill: [240, 90, 190], line: [255, 170, 220], star: [255, 205, 235] },+ orange: {+ fill: [255, 150, 50],+ line: [255, 195, 130],+ star: [255, 220, 175],+ },+ red: { fill: [240, 70, 70], line: [255, 150, 140], star: [255, 195, 185] },+ // No-data: a muted grey so empty metrics read as "nothing here".+ grey: { fill: [92, 92, 100], line: [140, 140, 150], star: [165, 165, 175] },+};++export const rgb = ([r, g, b]: Rgb, k = 1, a = 1) =>+ `rgba(${Math.round(r * k)},${Math.round(g * k)},${Math.round(b * k)},${a})`;++export const seedOfColor = (color: DitherColor): Seed => PALETTE[color];++export const isDitherColor = (value: unknown): value is DitherColor =>+ typeof value === "string" && value in PALETTE;diff --git a/apps/web/src/components/dither-kit/pie-canvas.tsx b/apps/web/src/components/dither-kit/pie-canvas.tsxnew file mode 100644index 000000000..d8b8d2edf--- /dev/null+++ b/apps/web/src/components/dither-kit/pie-canvas.tsx@@ -0,0 +1,215 @@+// @ts-nocheck+import { useEffect, useRef } from "react";+import {+ BAYER,+ backingSize,+ bloomLayerStyle,+ easeInOutCubic,+ OFF_TIER,+ prefersReducedMotion,+} from "./dither-paint";+import { rgb } from "./palette";+import { sliceAtAngle } from "./polar";+import { usePolarChart } from "./polar-context";++const TOP = -Math.PI / 2;+const TAU = Math.PI * 2;+const POP = 6; // px the hovered slice bulges outward++/**+ * Dither canvas for pie / donut charts. Each backing pixel is mapped back to+ * plot space, tested for its slice by angle, and filled with the ordered-dither+ * scatter — dense at the outer edge, thinning toward the centre — capped by a+ * bright arc on the rim. The pie sweeps in clockwise on mount; the hovered slice+ * bulges outward with a brighter rim while the rest dim.+ */+export function PieCanvas() {+ const ctx = usePolarChart();+ const canvasRef = useRef<HTMLCanvasElement>(null);+ const bloomRef = useRef<HTMLCanvasElement>(null);++ const { width, height } = ctx.plot;+ const { cols, rows } = backingSize(width, height);++ // The RAF loop reads the latest ctx through a ref; written in an effect+ // (never during render) — mutating a ref mid-render tears under Strict Mode /+ // concurrent rendering.+ const state = useRef(ctx);+ useEffect(() => {+ state.current = ctx;+ });++ useEffect(() => {+ const canvas = canvasRef.current;+ const c = canvas?.getContext("2d");+ if (!(canvas && c) || cols <= 0 || rows <= 0) return;+ canvas.width = cols;+ canvas.height = rows;++ const bloomCanvas = bloomRef.current;+ const bloomCtx = bloomCanvas?.getContext("2d") ?? null;+ if (bloomCanvas) {+ bloomCanvas.width = cols;+ bloomCanvas.height = rows;+ }++ const reduce = prefersReducedMotion();+ const animate = state.current.animate && !reduce;+ const duration = state.current.animationDuration;+ let raf = 0;+ let animStart = 0;+ let lastProg = -1;+ let lastRevision = state.current.revision;+ let intensity = 0;+ let popEase = 0; // eases the hovered slice's outward bulge+ let needsFill = true;+ let lastPaintSig = "";+ let lastSelected: string | null | undefined = Symbol() as never;+ let lastHover: number | null | undefined = Symbol() as never;++ const paint = (prog: number) => {+ const s = state.current;+ const slices = s.pie;+ if (!slices) return;+ c.clearRect(0, 0, cols, rows);+ const cx = s.center.x;+ const cy = s.center.y;+ const outerR = s.outerRadius;+ const innerR = s.innerRadius;+ const revealAngle = TOP + easeInOutCubic(prog) * TAU;++ for (let y = 0; y < rows; y++) {+ const py = ((y + 0.5) * height) / rows;+ for (let x = 0; x < cols; x++) {+ const px = ((x + 0.5) * width) / cols;+ const dx = px - cx;+ const dy = py - cy;+ const r = Math.hypot(dx, dy);+ if (r < innerR) continue;+ const angle = Math.atan2(dy, dx);+ let na = angle;+ while (na < TOP) na += TAU;+ while (na >= TOP + TAU) na -= TAU;+ if (na > revealAngle) continue; // clockwise sweep-in+ const si = sliceAtAngle(slices, angle);+ if (si < 0) continue;+ const slice = slices[si];+ const active = s.hoverIndex === si;+ const localOuter = active ? outerR + POP * popEase : outerR;+ if (r > localOuter) continue;++ const seed = s.seedOf(slice.name);+ const variant = s.variantOf(slice.name);+ const emphasis = s.selectedDataKey ?? s.focusDataKey;+ const selDim = emphasis !== null && emphasis !== slice.name ? 0.3 : 1;+ const it = intensity + (active ? 0.4 * popEase : 0);++ // Bright rim on the outer edge — thicker on the hovered slice.+ if (localOuter - r < (active ? 1.4 + popEase : 1.4)) {+ c.fillStyle = rgb(seed.fill, 1, selDim);+ c.fillRect(x, y, 1, 1);+ continue;+ }+ const density = (r - innerR) / Math.max(localOuter - innerR, 1);+ const bias = variant === "dotted" ? 0.12 : 0;+ if (variant === "hatched" && ((x + y) & 3) >= 2) continue;+ const lit = variant === "solid" || density > BAYER[y & 3][x & 3] - 0.1 * it - bias;+ if (variant === "dotted" && !lit) continue;+ // Density → opacity (see the colour-vs-opacity note in dither-paint);+ // off cells drop to a faint tier, never a hole to the background.+ const k = (0.35 + density * 0.65) * (1 + 0.22 * it);+ const alpha = Math.min(1, (lit ? k : k * OFF_TIER) * selDim);+ c.fillStyle = rgb(seed.fill, 1, alpha);+ c.fillRect(x, y, 1, 1);+ }+ }+ };++ const draw = (now: number) => {+ raf = requestAnimationFrame(draw);+ const s = state.current;+ if (!s.ready || !s.pie) return;+ if (bloomCtx) {+ const on = s.bloom !== "off" && (!s.bloomOnHover || s.isMouseInChart);+ if (on) {+ bloomCtx.clearRect(0, 0, cols, rows);+ bloomCtx.drawImage(canvas, 0, 0);+ }+ }+ if (s.revision !== lastRevision) {+ lastRevision = s.revision;+ animStart = 0;+ lastProg = -1;+ }+ if (!animStart) animStart = now;+ const prog = animate ? Math.min(1, (now - animStart) / duration) : 1;++ const emphasisNow = s.selectedDataKey ?? s.focusDataKey;+ if (emphasisNow !== lastSelected) {+ lastSelected = emphasisNow;+ needsFill = true;+ }+ if (s.hoverIndex !== lastHover) {+ lastHover = s.hoverIndex;+ popEase = 0; // a freshly-hovered slice bulges out from rest+ needsFill = true;+ }+ const itTarget = s.isMouseInChart ? 1 : 0;+ if (Math.abs(intensity - itTarget) > 0.001) {+ intensity += (itTarget - intensity) * (reduce ? 1 : 0.16);+ needsFill = true;+ } else intensity = itTarget;+ // Ease the hovered slice's bulge in (and back out when nothing's hovered).+ const popTarget = s.hoverIndex != null ? 1 : 0;+ if (Math.abs(popEase - popTarget) > 0.001) {+ popEase += (popTarget - popEase) * (reduce ? 1 : 0.22);+ needsFill = true;+ } else popEase = popTarget;+ if (prog !== lastProg) {+ lastProg = prog;+ needsFill = true;+ }++ // Live tweak repaint (variant, donut inner radius) without re-sweeping.+ const paintSig = `${s.innerRadius}|${s.pie.map((sl) => s.variantOf(sl.name)).join(",")}`;+ if (paintSig !== lastPaintSig) {+ lastPaintSig = paintSig;+ needsFill = true;+ }++ if (!needsFill) return;+ paint(prog);+ needsFill = false;+ };++ raf = requestAnimationFrame(draw);+ return () => cancelAnimationFrame(raf);+ }, [cols, rows, width, height]);++ const bloom = bloomLayerStyle(ctx.bloom, ctx.bloomOnHover ? ctx.isMouseInChart : true);+ const pos = {+ left: ctx.margins.left,+ top: ctx.margins.top,+ width,+ height,+ } as const;++ return (+ <>+ <canvas+ ref={canvasRef}+ className="pointer-events-none absolute"+ style={{ ...pos, imageRendering: "pixelated" }}+ />+ <canvas+ ref={bloomRef}+ className="pointer-events-none absolute"+ style={{+ ...pos,+ transition: "opacity 220ms ease",+ ...(bloom ?? { opacity: 0 }),+ }}+ />+ </>+ );+}diff --git a/apps/web/src/components/dither-kit/pie-chart.tsx b/apps/web/src/components/dither-kit/pie-chart.tsxnew file mode 100644index 000000000..ba9b52e62--- /dev/null+++ b/apps/web/src/components/dither-kit/pie-chart.tsx@@ -0,0 +1,36 @@+// @ts-nocheck+"use client";++import type { ReactNode } from "react";+import type { ChartConfig, Margins } from "./chart-context";+import type { BloomInput } from "./dither-paint";+import { PieCanvas } from "./pie-canvas";+import { PolarRoot } from "./polar-root";++// `object` rather than `Record<string, unknown>`: interfaces don't get an+// implicit index signature, so interface-typed rows failed to satisfy the+// generic. Internal layers still index rows through their own Row type.+type Row = object;++export type PieChartProps<TData extends Row> = {+ data: TData[];+ config: ChartConfig;+ children: ReactNode;+ dataKey: string; // value field+ nameKey: string; // slice-name field (looked up in config for colour)+ innerRadius?: number; // 0–1 ratio for a donut+ margins?: Partial<Margins>;+ className?: string;+ animate?: boolean;+ animationDuration?: number;+ replayToken?: number;+ bloom?: BloomInput;+ bloomOnHover?: boolean;+ defaultSelectedDataKey?: string | null;+ onSelectionChange?: (key: string | null) => void;+};++/** Composable dither **pie / donut** chart. Compose `<Pie>`, `<Legend>`, … inside. */+export function PieChart<TData extends Row>(props: PieChartProps<TData>) {+ return <PolarRoot chartType="pie" Canvas={PieCanvas} {...props} />;+}diff --git a/apps/web/src/components/dither-kit/pie.tsx b/apps/web/src/components/dither-kit/pie.tsxnew file mode 100644index 000000000..055f96bfd--- /dev/null+++ b/apps/web/src/components/dither-kit/pie.tsx@@ -0,0 +1,27 @@+// @ts-nocheck+"use client";++import { useEffect } from "react";+import type { AreaVariant } from "./chart-context";+import { usePolarPart } from "./polar-context";++export type PieProps = {+ /** Fill texture applied to every slice. */+ variant?: AreaVariant;+};++/**+ * The pie/donut ring. Slices come from the chart `data` (one per row); this part+ * sets the shared fill variant. The dithered wedges are painted on the canvas.+ */+export function Pie({ variant = "gradient" }: PieProps) {+ const ctx = usePolarPart("Pie", "pie");+ const { registerVariant, unregisterVariant } = ctx;++ useEffect(() => {+ registerVariant("*", variant);+ return () => unregisterVariant("*");+ }, [variant, registerVariant, unregisterVariant]);++ return null;+}diff --git a/apps/web/src/components/dither-kit/polar-context.tsx b/apps/web/src/components/dither-kit/polar-context.tsxnew file mode 100644index 000000000..126c5ed97--- /dev/null+++ b/apps/web/src/components/dither-kit/polar-context.tsx@@ -0,0 +1,376 @@+// @ts-nocheck+"use client";++import { createContext, use, useCallback, useMemo, useState } from "react";+import {+ type AreaVariant,+ type ChartConfig,+ type ChartType,+ type Margins,+ useRevision,+} from "./chart-context";+import type { CommonChart } from "./common-context";+import type { BloomInput } from "./dither-paint";+import type { Seed } from "./palette";+import { seedOfColor } from "./palette";+import { type PieSlice, pieSlices, type RadarAxis, radarAxes } from "./polar";+import type { Dimensions } from "./use-chart-dimensions";++type Row = Record<string, unknown>;++const ROOT_OF: Record<string, string> = {+ pie: "<PieChart />",+ radar: "<RadarChart />",+};++export type PolarChartContextValue = {+ chartType: ChartType;+ config: ChartConfig;+ configKeys: string[];+ data: Row[];+ dataLength: number;+ ready: boolean;+ plot: { width: number; height: number };+ margins: Margins;+ center: { x: number; y: number };+ outerRadius: number;+ innerRadius: number;+ animate: boolean;+ animationDuration: number;+ revision: number;+ bloom: BloomInput;+ bloomOnHover: boolean;++ seedOf: (key: string) => Seed;+ variantOf: (key: string) => AreaVariant;+ registerVariant: (key: string, variant: AreaVariant) => void;+ unregisterVariant: (key: string) => void;++ selectedDataKey: string | null;+ selectDataKey: (key: string | null) => void;+ /** Legend-hover spotlight — dims every series but this one while set. */+ focusDataKey: string | null;+ setFocusDataKey: (key: string | null) => void;+ hoverIndex: number | null;+ setHoverIndex: (i: number | null) => void;+ setCursor: (px: number, py: number) => void;+ isMouseInChart: boolean;+ setMouseInChart: (over: boolean) => void;++ pie: PieSlice[] | null; // present for pie charts+ radar: { axes: RadarAxis[]; max: number } | null; // present for radar charts++ common: CommonChart;+};++const PolarChartContext = createContext<PolarChartContextValue | null>(null);++export function usePolarChart() {+ const ctx = use(PolarChartContext);+ if (!ctx) {+ throw new Error("Polar chart parts must be used within a polar chart root.");+ }+ return ctx;+}++/** Boundary guard for polar parts (`<Pie>`, `<Radar>`). */+export function usePolarPart(part: string, kind: "pie" | "radar") {+ const ctx = use(PolarChartContext);+ if (!ctx) {+ throw new Error(`<${part} /> must be used within ${ROOT_OF[kind]}.`);+ }+ if (ctx.chartType !== kind) {+ throw new Error(+ `<${part} /> is not valid inside ${ROOT_OF[ctx.chartType]} — it belongs in ${ROOT_OF[kind]}.`,+ );+ }+ return ctx;+}++export { PolarChartContext };++export function usePolarController({+ chartType,+ data,+ config,+ dataKey,+ nameKey,+ innerRadiusRatio,+ dimensions,+ margins,+ animate = true,+ animationDuration = 900,+ replayToken = 0,+ bloom = "off",+ bloomOnHover = false,+ defaultSelectedDataKey = null,+ onSelectionChange,+}: {+ chartType: "pie" | "radar";+ data: Row[];+ config: ChartConfig;+ dataKey: string;+ nameKey: string;+ innerRadiusRatio: number;+ dimensions: Dimensions;+ margins: Margins;+ animate?: boolean;+ animationDuration?: number;+ replayToken?: number;+ bloom?: BloomInput;+ bloomOnHover?: boolean;+ defaultSelectedDataKey?: string | null;+ onSelectionChange?: (key: string | null) => void;+}): PolarChartContextValue {+ // This object becomes the PolarChartContext value, so its identity — and the+ // identity of every function/object it carries — must stay stable across+ // renders that don't change the inputs; otherwise every consumer (legend,+ // tooltip, slices, axes) re-renders on every parent render. The expensive+ // derivations, exposed callbacks, and returned value are memoized below;+ // cheap scalars (radii, ready) are left bare as plain recomputed reads.++ // Memoized: drives `pie`/`radar`/`common` — a fresh array would bust them.+ const configKeys = useMemo(() => Object.keys(config), [config]);+ const revision = useRevision(data, replayToken);++ const [selectedDataKey, setSelectedDataKey] = useState<string | null>(defaultSelectedDataKey);+ const [focusDataKey, setFocusDataKey] = useState<string | null>(null);+ const [hoverIndex, setHoverIndex] = useState<number | null>(null);+ const [cursorX, setCursorX] = useState(0);+ const [cursorY, setCursorY] = useState(0);+ const [isMouseInChart, setMouseInChart] = useState(false);+ // Stable (only wraps two useState setters) so the value keeps its identity.+ const setCursor = useCallback((px: number, py: number) => {+ setCursorX(px);+ setCursorY(py);+ }, []);+ const [variants, setVariants] = useState<Record<string, AreaVariant>>({});++ // useCallback for the same reason as registerSeries in chart-context.tsx:+ // pie.tsx/radar.tsx list these as effect deps, so without stable identities+ // the unregister/register effect re-fires and its setState pair loops.+ const registerVariant = useCallback((key: string, variant: AreaVariant) => {+ setVariants((prev) => (prev[key] === variant ? prev : { ...prev, [key]: variant }));+ }, []);+ const unregisterVariant = useCallback((key: string) => {+ setVariants((prev) => {+ if (!(key in prev)) return prev;+ const next = { ...prev };+ delete next[key];+ return next;+ });+ }, []);++ // Stable so the value keeps its identity; re-created only on config change.+ const selectDataKey = useCallback(+ (key: string | null) => {+ setSelectedDataKey(key);+ onSelectionChange?.(key);+ },+ [onSelectionChange],+ );++ // The root spreads margins fresh every render; pin a stable object off the+ // four numbers so it doesn't, on its own, invalidate the value.+ const { top: mTop, right: mRight, bottom: mBottom, left: mLeft } = margins;+ const stableMargins = useMemo(+ () => ({ top: mTop, right: mRight, bottom: mBottom, left: mLeft }),+ [mTop, mRight, mBottom, mLeft],+ );++ const plotWidth = Math.max(0, dimensions.width - mLeft - mRight);+ const plotHeight = Math.max(0, dimensions.height - mTop - mBottom);+ const ready = plotWidth > 0 && plotHeight > 0;+ const pad = chartType === "radar" ? 20 : 6;+ const outerRadius = Math.max(0, Math.min(plotWidth, plotHeight) / 2 - pad);+ const innerRadius = chartType === "pie" ? outerRadius * innerRadiusRatio : 0;+ const centerX = plotWidth / 2;+ const centerY = plotHeight / 2;++ // Stable so `common` and the value stay stable; re-created only on config.+ const seedOf = useCallback((key: string) => seedOfColor(config[key]?.color ?? "grey"), [config]);+ // "*" is the pie-wide variant set by <Pie>; radar registers per series key.+ const variantOf = useCallback(+ (key: string) => variants[key] ?? variants["*"] ?? "gradient",+ [variants],+ );++ // Memoized: slice geometry — recomputing it on every hover/cursor tick would+ // rebuild the pie layout needlessly.+ const pie = useMemo(+ () => (chartType === "pie" ? pieSlices(data, dataKey, nameKey) : null),+ [chartType, data, dataKey, nameKey],+ );++ // Memoized: walks every row × series for the axis max, then builds the axes.+ const radar = useMemo(() => {+ if (chartType !== "radar") return null;+ let max = 0;+ for (const row of data) {+ for (const key of configKeys) {+ const v = Number(row[key]) || 0;+ if (v > max) max = v;+ }+ }+ return { axes: radarAxes(data, nameKey), max: max || 1 };+ }, [chartType, data, configKeys, nameKey]);++ // Memoized: this is the value handed to CommonChartContext (Legend/Tooltip),+ // so it needs its own stable identity independent of the parent value.+ const common: CommonChart = useMemo<CommonChart>(() => {+ const tooltipLeft = Math.max(48, Math.min(plotWidth + mLeft - 48, cursorX));+ const tooltipTop = Math.max(mTop + 44, cursorY);+ const emphasis = selectedDataKey ?? focusDataKey;+ if (chartType === "pie" && pie) {+ const names = pie.map((s) => s.name);+ return {+ names,+ tooltipTop,+ labelOf: (n) => config[n]?.label ?? n,+ seedOf,+ selectedDataKey,+ selectDataKey,+ focusDataKey,+ setFocusDataKey,+ hoverIndex,+ ready,+ tooltipLeft,+ heading: (i) => pie[i]?.name ?? null,+ itemsAt: (i) => {+ const s = pie[i];+ if (!s) return [];+ return [+ {+ name: s.name,+ label: config[s.name]?.label ?? s.name,+ value: s.value,+ seed: seedOf(s.name),+ dimmed: emphasis !== null && emphasis !== s.name,+ },+ ];+ },+ };+ }+ // radar+ return {+ names: configKeys,+ tooltipTop,+ labelOf: (n) => config[n]?.label ?? n,+ seedOf,+ selectedDataKey,+ selectDataKey,+ focusDataKey,+ setFocusDataKey,+ hoverIndex,+ ready,+ tooltipLeft,+ heading: (i) => radar?.axes[i]?.label ?? null,+ itemsAt: (i) =>+ configKeys.map((name) => {+ const raw = data[i]?.[name];+ return {+ name,+ label: config[name]?.label ?? name,+ value: typeof raw === "number" ? raw : 0,+ seed: seedOf(name),+ dimmed: emphasis !== null && emphasis !== name,+ };+ }),+ };+ }, [+ chartType,+ config,+ configKeys,+ data,+ pie,+ radar,+ seedOf,+ selectedDataKey,+ selectDataKey,+ focusDataKey,+ setFocusDataKey,+ hoverIndex,+ ready,+ plotWidth,+ mLeft,+ mTop,+ cursorX,+ cursorY,+ ]);++ // Memoized: this is the PolarChartContext value. A fresh object here would+ // re-render every consumer on every parent render — the reason the pieces+ // above are stabilized. Rebuilds only when a listed input changes. The+ // useState setters are listed but never change identity.+ return useMemo<PolarChartContextValue>(+ () => ({+ chartType,+ config,+ configKeys,+ data,+ dataLength: data.length,+ ready,+ plot: { width: plotWidth, height: plotHeight },+ margins: stableMargins,+ center: { x: centerX, y: centerY },+ outerRadius,+ innerRadius,+ animate,+ animationDuration,+ revision,+ bloom,+ bloomOnHover,+ seedOf,+ variantOf,+ registerVariant,+ unregisterVariant,+ selectedDataKey,+ selectDataKey,+ focusDataKey,+ setFocusDataKey,+ hoverIndex,+ setHoverIndex,+ setCursor,+ isMouseInChart,+ setMouseInChart,+ pie,+ radar,+ common,+ }),+ [+ chartType,+ config,+ configKeys,+ data,+ ready,+ plotWidth,+ plotHeight,+ stableMargins,+ centerX,+ centerY,+ outerRadius,+ innerRadius,+ animate,+ animationDuration,+ revision,+ bloom,+ bloomOnHover,+ seedOf,+ variantOf,+ registerVariant,+ unregisterVariant,+ selectedDataKey,+ selectDataKey,+ focusDataKey,+ setFocusDataKey,+ hoverIndex,+ setHoverIndex,+ setCursor,+ isMouseInChart,+ setMouseInChart,+ pie,+ radar,+ common,+ ],+ );+}diff --git a/apps/web/src/components/dither-kit/polar-root.tsx b/apps/web/src/components/dither-kit/polar-root.tsxnew file mode 100644index 000000000..8f95a919b--- /dev/null+++ b/apps/web/src/components/dither-kit/polar-root.tsx@@ -0,0 +1,167 @@+// @ts-nocheck+"use client";++import { Children, type ComponentType, isValidElement, type ReactNode } from "react";+import type { ChartConfig, Margins } from "./chart-context";+import { CommonChartContext } from "./common-context";+import type { BloomInput } from "./dither-paint";+import { cn } from "./lib";+import { axisAtAngle, sliceAtAngle } from "./polar";+import { PolarChartContext, usePolarController } from "./polar-context";+import { useChartDimensions } from "./use-chart-dimensions";++// `object` rather than `Record<string, unknown>`: interfaces don't get an+// implicit index signature, so interface-typed rows failed to satisfy the+// generic. Internal layers still index rows through their own Row type.+type Row = object;++const DEFAULT_POLAR_MARGINS: Margins = {+ top: 22,+ right: 14,+ bottom: 14,+ left: 14,+};++function layerOf(node: ReactNode): "back" | "dom" | "svg" {+ if (!isValidElement(node) || typeof node.type === "string") return "svg";+ return (node.type as { chartLayer?: "back" | "dom" }).chartLayer ?? "svg";+}++export type PolarRootProps<TData extends Row> = {+ chartType: "pie" | "radar";+ /** Family painter — `PieCanvas` or `RadarCanvas`; ships with each chart. */+ Canvas: ComponentType;+ /** Extra back-layer SVG content (e.g. the radar frame). */+ backDecoration?: ReactNode;+ data: TData[];+ config: ChartConfig;+ children: ReactNode;+ dataKey: string;+ nameKey: string;+ innerRadius?: number; // 0–1 ratio (donut); pie only+ margins?: Partial<Margins>;+ className?: string;+ animate?: boolean;+ animationDuration?: number;+ replayToken?: number;+ bloom?: BloomInput;+ bloomOnHover?: boolean;+ defaultSelectedDataKey?: string | null;+ onSelectionChange?: (key: string | null) => void;+};++export function PolarRoot<TData extends Row>({+ chartType,+ Canvas,+ backDecoration,+ data,+ config,+ children,+ dataKey,+ nameKey,+ innerRadius = 0,+ margins: marginsProp,+ className,+ animate = true,+ animationDuration = 900,+ replayToken = 0,+ bloom = "off",+ bloomOnHover = false,+ defaultSelectedDataKey = null,+ onSelectionChange,+}: PolarRootProps<TData>) {+ const { ref, size } = useChartDimensions<HTMLDivElement>();+ const margins = { ...DEFAULT_POLAR_MARGINS, ...marginsProp };++ const ctx = usePolarController({+ chartType,+ // Safe: the controller only reads row[key] for the configured keys.+ data: data as Record<string, unknown>[],+ config,+ dataKey,+ nameKey,+ innerRadiusRatio: innerRadius,+ dimensions: size,+ margins,+ animate,+ animationDuration,+ replayToken,+ bloom,+ bloomOnHover,+ defaultSelectedDataKey,+ onSelectionChange,+ });++ const backChildren: ReactNode[] = [];+ const svgChildren: ReactNode[] = [];+ const domChildren: ReactNode[] = [];+ Children.forEach(children, (child) => {+ const layer = layerOf(child);+ if (layer === "back") backChildren.push(child);+ else if (layer === "dom") domChildren.push(child);+ else svgChildren.push(child);+ });++ const onMove = (clientX: number, clientY: number) => {+ const el = ref.current;+ if (!el) return;+ const rect = el.getBoundingClientRect();+ const dx = clientX - rect.left - margins.left - ctx.center.x;+ const dy = clientY - rect.top - margins.top - ctx.center.y;+ const angle = Math.atan2(dy, dx);+ const r = Math.hypot(dx, dy);+ if (chartType === "pie" && ctx.pie) {+ const inside = r <= ctx.outerRadius && r >= ctx.innerRadius;+ const i = inside ? sliceAtAngle(ctx.pie, angle) : -1;+ ctx.setHoverIndex(i >= 0 ? i : null);+ } else if (ctx.radar) {+ ctx.setHoverIndex(axisAtAngle(ctx.radar.axes, angle));+ }+ ctx.setCursor(clientX - rect.left, clientY - rect.top);+ };++ return (+ <PolarChartContext value={ctx}>+ <CommonChartContext value={ctx.common}>+ <div+ ref={ref}+ className={cn("relative h-full w-full", className)}+ onPointerEnter={() => ctx.setMouseInChart(true)}+ onPointerMove={(e) => onMove(e.clientX, e.clientY)}+ onPointerLeave={() => {+ ctx.setMouseInChart(false);+ ctx.setHoverIndex(null);+ }}+ >+ {ctx.ready && (+ <svg+ width={size.width}+ height={size.height}+ className="absolute inset-0 overflow-visible"+ aria-hidden+ role="presentation"+ >+ <g transform={`translate(${margins.left},${margins.top})`}>+ {backDecoration}+ {backChildren}+ </g>+ </svg>+ )}+ <Canvas />+ {ctx.ready && (+ <svg+ width={size.width}+ height={size.height}+ className="absolute inset-0 overflow-visible"+ role="img"+ aria-label="Chart"+ >+ <g transform={`translate(${margins.left},${margins.top})`}>{svgChildren}</g>+ </svg>+ )}+ {domChildren}+ </div>+ </CommonChartContext>+ </PolarChartContext>+ );+}diff --git a/apps/web/src/components/dither-kit/polar.ts b/apps/web/src/components/dither-kit/polar.tsnew file mode 100644index 000000000..4f51d173f--- /dev/null+++ b/apps/web/src/components/dither-kit/polar.ts@@ -0,0 +1,109 @@+// @ts-nocheck+type Row = Record<string, unknown>;++const TOP = -Math.PI / 2;+const TAU = Math.PI * 2;++export type PieSlice = {+ name: string;+ value: number;+ start: number; // radians+ end: number;+ mid: number;+};++/** Slice angles from each data row's value under `dataKey`, named by `nameKey`. */+export function pieSlices(data: Row[], dataKey: string, nameKey: string): PieSlice[] {+ const vals = data.map((r) => Math.max(0, Number(r[dataKey]) || 0));+ const total = vals.reduce((a, b) => a + b, 0) || 1;+ let a = TOP;+ return data.map((r, i) => {+ const span = (vals[i] / total) * TAU;+ const slice = {+ name: String(r[nameKey] ?? i),+ value: vals[i],+ start: a,+ end: a + span,+ mid: a + span / 2,+ };+ a += span;+ return slice;+ });+}++/** Which slice a pointer angle falls in (or -1). */+export function sliceAtAngle(slices: PieSlice[], angle: number): number {+ // Normalize so comparisons against [start, end) (which begin at TOP) work.+ let a = angle;+ while (a < TOP) a += TAU;+ while (a >= TOP + TAU) a -= TAU;+ return slices.findIndex((s) => a >= s.start && a < s.end);+}++export type RadarAxis = { label: string; angle: number };++/** Evenly-spaced spokes, one per data row, labelled by `nameKey`. */+export function radarAxes(data: Row[], nameKey: string): RadarAxis[] {+ const n = Math.max(data.length, 1);+ return data.map((r, i) => ({+ label: String(r[nameKey] ?? i),+ angle: TOP + (i / n) * TAU,+ }));+}++/** Nearest radar spoke to a pointer angle. */+export function axisAtAngle(axes: RadarAxis[], angle: number): number {+ let best = 0;+ let bestD = Infinity;+ axes.forEach((ax, i) => {+ let d = Math.abs(((angle - ax.angle + Math.PI * 3) % TAU) - Math.PI);+ d = Math.abs(d);+ if (d < bestD) {+ bestD = d;+ best = i;+ }+ });+ return best;+}++export const polarX = (cx: number, r: number, angle: number) => cx + Math.cos(angle) * r;+export const polarY = (cy: number, r: number, angle: number) => cy + Math.sin(angle) * r;++/** Even-odd point-in-polygon test (polygon as flat [x0,y0,x1,y1,…]). */+export function pointInPolygon(px: number, py: number, poly: number[]): boolean {+ let inside = false;+ const n = poly.length / 2;+ for (let i = 0, j = n - 1; i < n; j = i++) {+ const xi = poly[i * 2];+ const yi = poly[i * 2 + 1];+ const xj = poly[j * 2];+ const yj = poly[j * 2 + 1];+ if (yi > py !== yj > py && px < ((xj - xi) * (py - yi)) / (yj - yi) + xi) {+ inside = !inside;+ }+ }+ return inside;+}++/** Distance from a point to the nearest edge of a polygon — drives the radial+ * dither density (dense near the edge, thinning to the centre). */+export function distToPolygonEdge(px: number, py: number, poly: number[]): number {+ let best = Infinity;+ const n = poly.length / 2;+ for (let i = 0, j = n - 1; i < n; j = i++) {+ const xi = poly[i * 2];+ const yi = poly[i * 2 + 1];+ const xj = poly[j * 2];+ const yj = poly[j * 2 + 1];+ const dx = xj - xi;+ const dy = yj - yi;+ const len2 = dx * dx + dy * dy || 1;+ let t = ((px - xi) * dx + (py - yi) * dy) / len2;+ t = Math.max(0, Math.min(1, t));+ const ex = xi + t * dx - px;+ const ey = yi + t * dy - py;+ const d = Math.hypot(ex, ey);+ if (d < best) best = d;+ }+ return best;+}diff --git a/apps/web/src/components/dither-kit/reference-line.tsx b/apps/web/src/components/dither-kit/reference-line.tsxnew file mode 100644index 000000000..136614f80--- /dev/null+++ b/apps/web/src/components/dither-kit/reference-line.tsx@@ -0,0 +1,51 @@+// @ts-nocheck+"use client";++import { useChartPart } from "./chart-context";++/**+ * A horizontal marker line at a value on the y-axis — most useful as the zero+ * baseline for diverging data (`<ReferenceLine y={0} />`), or to mark a target+ * / threshold. Renders in the front SVG layer so it stays visible over the+ * dither fill; pass an optional `label` to annotate it at the right edge.+ */+export function ReferenceLine({+ y = 0,+ label,+ strokeDasharray = "4 4",+ className = "stroke-muted-foreground/60",+}: {+ y?: number;+ label?: string;+ strokeDasharray?: string;+ className?: string;+}) {+ const ctx = useChartPart("ReferenceLine");+ if (!ctx.ready) return null;++ const { width } = ctx.plot;+ const py = ctx.y(y);++ return (+ <g>+ <line+ x1={0}+ x2={width}+ y1={py}+ y2={py}+ className={className}+ strokeDasharray={strokeDasharray}+ />+ {label ? (+ <text+ x={width - 2}+ y={py - 3}+ textAnchor="end"+ className="fill-muted-foreground font-mono text-[10px]"+ >+ {label}+ </text>+ ) : null}+ </g>+ );+}diff --git a/apps/web/src/components/dither-kit/scales.ts b/apps/web/src/components/dither-kit/scales.tsnew file mode 100644index 000000000..c798b410d--- /dev/null+++ b/apps/web/src/components/dither-kit/scales.ts@@ -0,0 +1,107 @@+// @ts-nocheck+import { scaleBand, scaleLinear, scalePoint } from "d3-scale";+import { stack as d3Stack, stackOffsetExpand } from "d3-shape";++export type StackType = "default" | "stacked" | "percent";++type Row = Record<string, unknown>;++const num = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0);++/**+ * Per-series [y0, y1] bands for every row. For `default` every series sits on+ * the zero baseline (y0 = 0), so a negative value yields `[0, v]` with `v < 0`+ * and draws below the baseline; for `stacked`/`percent` they pile on top of+ * each other via d3's stack layout (which splits negatives below zero). The+ * shape `bands[key][i] = [y0, y1]` is what both the SVG area paths and the+ * canvas overlay read from. `max`/`min` bound the value range so the y-scale+ * can span a diverging (below-zero) domain.+ */+export function computeBands(+ data: Row[],+ keys: string[],+ stackType: StackType,+): { bands: Record<string, [number, number][]>; max: number; min: number } {+ if (stackType === "default") {+ const bands: Record<string, [number, number][]> = {};+ let max = 0;+ let min = 0;+ for (const key of keys) {+ bands[key] = data.map((row) => {+ const v = num(row[key]);+ if (v > max) max = v;+ if (v < min) min = v;+ return [0, v];+ });+ }+ // Only fall back to a unit span when there's no range at all (empty /+ // all-zero) — a purely negative series keeps max = 0 so the baseline+ // stays pinned to the top of the plot.+ const flat = max === 0 && min === 0;+ return { bands, max: flat ? 1 : max, min };+ }++ const series = d3Stack<Row>()+ .keys(keys)+ .value((row, key) => num(row[key]))+ .offset(stackType === "percent" ? stackOffsetExpand : (undefined as never))(data);++ const bands: Record<string, [number, number][]> = {};+ let max = 0;+ let min = 0;+ series.forEach((layer) => {+ bands[layer.key] = layer.map((point) => {+ if (point[1] > max) max = point[1];+ if (point[0] < min) min = point[0];+ return [point[0], point[1]];+ });+ });+ const flat = max === 0 && min === 0;+ return { bands, max: flat ? 1 : max, min };+}++/** x positions for each row index, evenly spread across the plot width. */+export function buildXScale(length: number, plotWidth: number) {+ return scalePoint<number>()+ .domain(Array.from({ length }, (_, i) => i))+ .range([0, plotWidth]);+}++/** Banded x for bar categories — each index owns a slot of `bandwidth` width. */+export function buildBandScale(length: number, plotWidth: number) {+ return scaleBand<number>()+ .domain(Array.from({ length }, (_, i) => i))+ .range([0, plotWidth])+ .paddingInner(0.28)+ .paddingOuter(0.18);+}++/** Index of the category whose band a horizontal pixel offset falls in. */+export function indexAtBand(px: number, length: number, plotWidth: number) {+ if (length <= 0 || plotWidth <= 0) return 0;+ const t = Math.max(0, Math.min(0.999, px / plotWidth));+ return Math.min(length - 1, Math.floor(t * length));+}++/**+ * value → vertical pixel. The domain always includes zero, so charts with only+ * positive values keep a floor at the plot bottom, while diverging data (values+ * below zero) draws below a zero baseline that sits somewhere inside the plot.+ */+export function buildYScale(min: number, max: number, plotHeight: number) {+ const lo = Math.min(0, min);+ const hi = Math.max(0, max);+ // Guard a degenerate (zero-width) domain so `nice()` and the range map stay+ // finite even when every value is exactly zero.+ return scaleLinear()+ .domain([lo, hi === lo ? lo + 1 : hi])+ .nice()+ .range([plotHeight, 0]);+}++/** Index of the row nearest a horizontal pixel offset within the plot. */+export function nearestIndex(px: number, length: number, plotWidth: number) {+ if (length <= 1 || plotWidth <= 0) return 0;+ const t = Math.max(0, Math.min(1, px / plotWidth));+ return Math.round(t * (length - 1));+}diff --git a/apps/web/src/components/dither-kit/series-context.tsx b/apps/web/src/components/dither-kit/series-context.tsxnew file mode 100644index 000000000..301ec5a1f--- /dev/null+++ b/apps/web/src/components/dither-kit/series-context.tsx@@ -0,0 +1,20 @@+// @ts-nocheck+import { createContext, use } from "react";+import type { Seed } from "./palette";++export type SeriesContextValue = {+ dataKey: string;+ seed: Seed;+ dimmed: boolean;+};++export const SeriesContext = createContext<SeriesContextValue | null>(null);++/** Boundary guard for series-scoped markers (`<Dot>`, `<ActiveDot>`). */+export function useSeries(part: string) {+ const ctx = use(SeriesContext);+ if (!ctx) {+ throw new Error(`<${part} /> must be rendered inside a series (e.g. <Area />).`);+ }+ return ctx;+}diff --git a/apps/web/src/components/dither-kit/sparkline.tsx b/apps/web/src/components/dither-kit/sparkline.tsxnew file mode 100644index 000000000..894795cb6--- /dev/null+++ b/apps/web/src/components/dither-kit/sparkline.tsx@@ -0,0 +1,67 @@+// @ts-nocheck+"use client";++import { useMemo } from "react";+import { Area } from "./area";+import { AreaChart } from "./area-chart";+import type { AreaVariant } from "./chart-context";+import type { BloomInput } from "./dither-paint";+import type { DitherColor } from "./palette";++export type SparklineProps = {+ /** Plain numeric series — the common sparkline case. */+ data: number[];+ color: DitherColor;+ variant?: AreaVariant;+ /** Controlled crosshair position (e.g. a committed point). */+ markerIndex?: number | null;+ /** Parent-driven hover (e.g. the whole card/row) — lifts the fill. */+ hovered?: boolean;+ /** Glow on the dither fill. */+ bloom?: BloomInput;+ /** Only bloom while hovered. */+ bloomOnHover?: boolean;+ /** Play the entrance sweep — off by default for a calm spark. */+ animate?: boolean;+ className?: string;+};++/**+ * Thin wrapper over {@link AreaChart} for the decorative-sparkline case: a+ * single `number[]` series, no axes/grid/tooltip, no scrub crosshair (unless a+ * `markerIndex` is supplied). Keeps the hover brightness lift.+ */+export function Sparkline({+ data,+ color,+ variant = "gradient",+ markerIndex = null,+ hovered = false,+ bloom = "off",+ bloomOnHover = false,+ animate = false,+ className,+}: SparklineProps) {+ // Memoized explicitly so the chart works without React Compiler: `rows`+ // identity drives the entrance-replay revision, so a fresh array every+ // render would re-trigger the revision's state adjustment each pass.+ const rows = useMemo(() => data.map((v) => ({ v })), [data]);+ const config = useMemo(() => ({ v: { color } }), [color]);++ return (+ <AreaChart+ data={rows}+ config={config}+ interactive={false}+ animate={animate}+ markerIndex={markerIndex}+ hovered={hovered}+ bloom={bloom}+ bloomOnHover={bloomOnHover}+ margins={{ top: 0, right: 0, bottom: 0, left: 0 }}+ className={className}+ >+ <Area dataKey="v" variant={variant} />+ </AreaChart>+ );+}diff --git a/apps/web/src/components/dither-kit/tooltip.tsx b/apps/web/src/components/dither-kit/tooltip.tsxnew file mode 100644index 000000000..8cee3a47b--- /dev/null+++ b/apps/web/src/components/dither-kit/tooltip.tsx@@ -0,0 +1,105 @@+// @ts-nocheck+"use client";++import { AnimatePresence, motion } from "motion/react";+import { useState } from "react";+import { useCommonChart } from "./common-context";+import { cn } from "./lib";+import { rgb } from "./palette";++export type TooltipVariant = "default" | "frosted-glass";++const VARIANT: Record<TooltipVariant, string> = {+ default: "bg-popover",+ "frosted-glass": "bg-popover/70 backdrop-blur-sm",+};++/**+ * Floating hover tooltip. Reads the shared common context so it works in every+ * chart family. It glides between points and fades in/out (instead of snapping),+ * and dims unselected series/slices.+ */+export function Tooltip({+ labelKey,+ valueFormatter,+ variant = "default",+}: {+ labelKey?: string;+ valueFormatter?: (value: number, name: string) => string;+ variant?: TooltipVariant;+}) {+ const chart = useCommonChart();+ const show = chart.ready && chart.hoverIndex != null;++ // Retain the last hovered index so the card keeps its content while fading+ // out — adjust-state-during-render (no refs in render).+ const [lastIndex, setLastIndex] = useState(0);+ if (chart.hoverIndex != null && chart.hoverIndex !== lastIndex) {+ setLastIndex(chart.hoverIndex);+ }+ const index = chart.hoverIndex ?? lastIndex;++ const heading = chart.heading(index, labelKey);+ const items = chart.itemsAt(index);++ return (+ <AnimatePresence>+ {show && items.length > 0 && (+ <motion.div+ key="dither-tooltip"+ initial={{+ opacity: 0,+ x: "-50%",+ y: "-115%",+ top: chart.tooltipTop,+ left: chart.tooltipLeft,+ }}+ animate={{+ opacity: 1,+ x: "-50%",+ y: "-115%",+ top: chart.tooltipTop,+ left: chart.tooltipLeft,+ }}+ exit={{ opacity: 0 }}+ transition={{+ type: "spring",+ stiffness: 520,+ damping: 38,+ mass: 0.6,+ }}+ className={cn(+ "pointer-events-none absolute z-10 rounded-md border px-2 py-1 shadow-sm",+ VARIANT[variant],+ )}+ >+ {heading && (+ <div className="mb-0.5 font-mono text-[10px] text-muted-foreground">{heading}</div>+ )}+ <div className="flex flex-col gap-0.5">+ {items.map((item) => (+ <div+ key={item.name}+ className="flex items-center gap-1.5 font-mono text-[11px] text-popover-foreground tabular-nums"+ style={{ opacity: item.dimmed ? 0.4 : 1 }}+ >+ <span+ className="size-2 rounded-[1px]"+ style={{ backgroundColor: rgb(item.seed.fill) }}+ />+ <span className="text-muted-foreground">{item.label}</span>+ <span className="ml-auto pl-2 text-foreground">+ {valueFormatter+ ? valueFormatter(item.value, item.name)+ : item.value.toLocaleString()}+ </span>+ </div>+ ))}+ </div>+ </motion.div>+ )}+ </AnimatePresence>+ );+}++Tooltip.chartLayer = "dom" as const;diff --git a/apps/web/src/components/dither-kit/use-chart-dimensions.ts b/apps/web/src/components/dither-kit/use-chart-dimensions.tsnew file mode 100644index 000000000..51ddb81cf--- /dev/null+++ b/apps/web/src/components/dither-kit/use-chart-dimensions.ts@@ -0,0 +1,38 @@+// @ts-nocheck+import { useLayoutEffect, useRef, useState } from "react";++export type Dimensions = { width: number; height: number };++/**+ * Tracks an element's CSS pixel size via {@link ResizeObserver}. Uses+ * `clientWidth`/`clientHeight` (the layout size) rather than+ * `getBoundingClientRect()` so a parent `layoutId` morph — which scales the+ * element via a transform — can't trick the chart into measuring a scaled size+ * and locking its canvas to it.+ */+export function useChartDimensions<T extends HTMLElement>() {+ const ref = useRef<T>(null);+ const [size, setSize] = useState<Dimensions>({ width: 0, height: 0 });++ useLayoutEffect(() => {+ const el = ref.current;+ if (!el) return;++ const measure = () => {+ const width = Math.max(0, el.clientWidth);+ const height = Math.max(0, el.clientHeight);+ setSize((prev) =>+ prev.width === width && prev.height === height+ ? prev // guard against repeat fires+ : { width, height },+ );+ };++ const ro = new ResizeObserver(measure);+ ro.observe(el);+ measure();+ return () => ro.disconnect();+ }, []);++ return { ref, size };+}diff --git a/apps/web/src/components/dither-kit/x-axis.tsx b/apps/web/src/components/dither-kit/x-axis.tsxnew file mode 100644index 000000000..a8201b17f--- /dev/null+++ b/apps/web/src/components/dither-kit/x-axis.tsx@@ -0,0 +1,43 @@+// @ts-nocheck+import { useChartPart } from "./chart-context";++export function XAxis({+ dataKey,+ tickFormatter,+ tickMargin = 8,+ maxTicks = 8,+}: {+ dataKey?: string;+ tickFormatter?: (value: unknown, index: number) => string;+ tickMargin?: number;+ maxTicks?: number;+}) {+ const ctx = useChartPart("XAxis");+ if (!ctx.ready) return null;++ const step = Math.max(1, Math.ceil(ctx.dataLength / maxTicks));+ const y = ctx.plot.height + tickMargin;++ return (+ <g className="fill-current font-mono text-[10px] text-muted-foreground">+ {ctx.data.map((row, i) => {+ if (i % step !== 0) return null;+ const raw = dataKey ? row[dataKey] : i;+ const label = tickFormatter ? tickFormatter(raw, i) : String(raw ?? "");+ return (+ <text+ // biome-ignore lint/suspicious/noArrayIndexKey: index is the stable x position+ key={i}+ x={ctx.xCenter(i) ?? 0}+ y={y}+ textAnchor="middle"+ dominantBaseline="hanging"+ fill="currentColor"+ >+ {label}+ </text>+ );+ })}+ </g>+ );+}diff --git a/apps/web/src/components/dither-kit/y-axis.tsx b/apps/web/src/components/dither-kit/y-axis.tsxnew file mode 100644index 000000000..4bf23e52e--- /dev/null+++ b/apps/web/src/components/dither-kit/y-axis.tsx@@ -0,0 +1,34 @@+// @ts-nocheck+"use client";++import { useChartPart } from "./chart-context";++export function YAxis({+ tickFormatter,+ tickCount = 4,+ tickMargin = 8,+}: {+ tickFormatter?: (value: number) => string;+ tickCount?: number;+ tickMargin?: number;+}) {+ const ctx = useChartPart("YAxis");+ if (!ctx.ready) return null;++ return (+ <g className="fill-current font-mono text-[10px] text-muted-foreground">+ {ctx.y.ticks(tickCount).map((t) => (+ <text+ key={t}+ x={-tickMargin}+ y={ctx.y(t)}+ textAnchor="end"+ dominantBaseline="central"+ fill="currentColor"+ >+ {tickFormatter ? tickFormatter(t) : t}+ </text>+ ))}+ </g>+ );+}diff --git a/apps/web/src/components/plugins/PluginDetails.tsx b/apps/web/src/components/plugins/PluginDetails.tsxnew file mode 100644index 000000000..a04678664--- /dev/null+++ b/apps/web/src/components/plugins/PluginDetails.tsx@@ -0,0 +1,163 @@+import { ArrowUpRightIcon, CheckIcon, ChevronLeftIcon, LinkIcon } from "lucide-react";+import type { PluginDefinition, PluginSkill } from "../../../../../plugins";+import { Button } from "../ui/button";+import { DialogHeader, DialogPanel, DialogTitle } from "../ui/dialog";+import { PluginLogoImage } from "./PluginsCatalog";++function connectorAccess(plugin: PluginDefinition): string {+ if (plugin.kind !== "mcp-url") return "Local";+ if (plugin.authentication === "oauth") return "OAuth";+ if (plugin.authentication === "optional-oauth") return "Optional OAuth";+ return "Public";+}++interface PluginDetailsContentProps {+ readonly plugin: PluginDefinition;+ readonly installed: boolean;+ readonly pending: boolean;+ readonly onToggle: (enabled: boolean) => void;+ readonly onCopySource: () => void;+ readonly onViewSource: () => void;+ readonly onOpenSkill: (skill: PluginSkill) => void;+}++export function PluginDetailsContent({+ plugin,+ installed,+ pending,+ onToggle,+ onCopySource,+ onViewSource,+ onOpenSkill,+}: PluginDetailsContentProps) {+ return (+ <DialogPanel className="px-6 pt-6! pb-6 sm:px-8">+ <div className="mx-auto max-w-3xl space-y-6">+ <section className="rounded-2xl border bg-card/50 p-5">+ <div className="flex items-start gap-4">+ <PluginLogoImage className="size-14 rounded-xl" plugin={plugin} />+ <div className="min-w-0 flex-1 pt-0.5">+ <div className="flex flex-wrap items-center gap-2">+ <h2 className="truncate text-lg font-semibold">{plugin.title}</h2>+ <span className="rounded-full bg-muted px-2 py-0.5 text-[11px] text-muted-foreground">+ {plugin.category}+ </span>+ </div>+ <p className="mt-2 max-w-2xl text-sm leading-6 text-muted-foreground">+ {plugin.description}+ </p>+ </div>+ <Button+ aria-label={`${installed ? "Remove" : "Add"} ${plugin.title}`}+ className="h-8 min-w-16 rounded-full px-3 text-xs"+ size="sm"+ variant={installed ? "secondary" : "default"}+ disabled={pending}+ onClick={() => onToggle(!installed)}+ >+ {installed ? <CheckIcon className="size-3.5" /> : null}+ {installed ? "Added" : "Add"}+ </Button>+ </div>+ {plugin.docsUrl ? (+ <div className="mt-4 flex items-center gap-1 border-t pt-3">+ <Button size="sm" variant="ghost-muted" onClick={onViewSource}>+ Documentation+ <ArrowUpRightIcon className="size-3.5" />+ </Button>+ <Button+ aria-label={`Copy ${plugin.title} source link`}+ size="sm"+ variant="ghost-muted"+ onClick={onCopySource}+ >+ <LinkIcon className="size-3.5" />+ Copy link+ </Button>+ </div>+ ) : null}+ </section>++ <section aria-labelledby="plugin-connectors-title">+ <div className="mb-2 flex items-center justify-between px-1">+ <h3 className="text-xs font-medium text-muted-foreground" id="plugin-connectors-title">+ Connector+ </h3>+ <span className="text-[11px] text-muted-foreground">1 available</span>+ </div>+ <div className="flex items-center justify-between gap-4 rounded-xl border bg-muted/35 px-4 py-3.5">+ <div className="min-w-0">+ <p className="truncate text-sm font-medium">{plugin.title}</p>+ <p className="mt-0.5 text-xs text-muted-foreground">MCP connector</p>+ </div>+ <span className="shrink-0 rounded-full bg-muted px-2.5 py-1 text-xs text-muted-foreground">+ {connectorAccess(plugin)}+ </span>+ </div>+ </section>++ {plugin.skills?.length ? (+ <section aria-labelledby="plugin-skills-title">+ <div className="mb-2 flex items-center justify-between px-1">+ <h3 className="text-xs font-medium text-muted-foreground" id="plugin-skills-title">+ Skills+ </h3>+ <span className="text-[11px] text-muted-foreground">Installed separately</span>+ </div>+ <div className="overflow-hidden rounded-xl border bg-muted/35">+ {plugin.skills.map((skill) => (+ <button+ className="group flex w-full cursor-pointer items-center justify-between gap-4 border-b px-4 py-3.5 text-start outline-hidden transition-colors last:border-b-0 hover:bg-muted/55 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"+ key={skill.url}+ type="button"+ onClick={() => onOpenSkill(skill)}+ >+ <div className="min-w-0">+ <p className="truncate text-sm font-medium">{skill.title}</p>+ <p className="mt-0.5 truncate text-xs text-muted-foreground">+ {skill.description}+ </p>+ </div>+ <ArrowUpRightIcon className="size-4 shrink-0 text-muted-foreground transition-colors group-hover:text-foreground" />+ </button>+ ))}+ </div>+ </section>+ ) : null}+ </div>+ </DialogPanel>+ );+}++export function PluginDetails({+ plugin,+ installed,+ pending,+ onBack,+ onToggle,+ onCopySource,+ onViewSource,+ onOpenSkill,+}: PluginDetailsContentProps & { readonly onBack: () => void }) {+ return (+ <div className="flex h-full min-h-0 flex-1 flex-col" data-plugin-details="">+ <DialogHeader className="border-b px-5 py-4">+ <div className="flex items-center gap-2 pe-8">+ <Button aria-label="Back to plugins" size="icon-sm" variant="ghost" onClick={onBack}>+ <ChevronLeftIcon className="size-4" />+ </Button>+ <DialogTitle className="text-base">Plugin details</DialogTitle>+ </div>+ </DialogHeader>+ <PluginDetailsContent+ plugin={plugin}+ installed={installed}+ pending={pending}+ onToggle={onToggle}+ onCopySource={onCopySource}+ onViewSource={onViewSource}+ onOpenSkill={onOpenSkill}+ />+ </div>+ );+}diff --git a/apps/web/src/components/plugins/PluginsCatalog.tsx b/apps/web/src/components/plugins/PluginsCatalog.tsxnew file mode 100644index 000000000..381880953--- /dev/null+++ b/apps/web/src/components/plugins/PluginsCatalog.tsx@@ -0,0 +1,248 @@+import type { McpServer } from "@t3tools/contracts";+import { CheckIcon, ChevronRightIcon, PencilIcon, Trash2Icon } from "lucide-react";+import type { PluginDefinition } from "../../../../../plugins";+import { Button } from "../ui/button";+import { findPluginServer, pluginMcpServerId } from "./pluginRegistry";+import type { PluginFilter, PluginSection } from "./pluginPresentation";++export function PluginLogoImage({+ plugin,+ className = "size-10",+}: {+ readonly plugin: PluginDefinition;+ readonly className?: string;+}) {+ return (+ <span+ aria-hidden="true"+ className={`${className} flex shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted p-2`}+ >+ <img+ alt=""+ className={`size-full object-contain ${plugin.logo.darkSrc ? "dark:hidden" : ""}`}+ src={plugin.logo.src}+ />+ {plugin.logo.darkSrc ? (+ <img+ alt=""+ className="hidden size-full object-contain dark:block"+ src={plugin.logo.darkSrc}+ />+ ) : null}+ </span>+ );+}++interface PluginsCatalogProps {+ readonly sections: readonly PluginSection[];+ readonly servers: readonly McpServer[];+ readonly pendingServerId: string | null;+ readonly onToggle: (plugin: PluginDefinition, enabled: boolean) => void;+ readonly onOpen: (plugin: PluginDefinition) => void;+ readonly onViewAll: (filter: PluginFilter) => void;+}++function PluginRow({+ plugin,+ server,+ pending,+ onToggle,+ onOpen,+ showCategory,+}: {+ readonly plugin: PluginDefinition;+ readonly server: McpServer | undefined;+ readonly pending: boolean;+ readonly onToggle: (enabled: boolean) => void;+ readonly onOpen: () => void;+ readonly showCategory: boolean;+}) {+ const installed = server?.enabled ?? false;+ return (+ <article+ className="group flex min-w-0 items-center rounded-xl pe-2.5 transition-colors hover:bg-muted/45"+ data-plugin-id={plugin.id}+ >+ <button+ aria-label={`Open ${plugin.title}`}+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-3 rounded-xl px-2.5 py-2.5 text-start outline-hidden focus-visible:ring-2 focus-visible:ring-ring"+ type="button"+ onClick={onOpen}+ >+ <PluginLogoImage plugin={plugin} />+ <div className="min-w-0 flex-1">+ <div className="flex min-w-0 items-center gap-2">+ <h3 className="truncate text-sm font-medium leading-5">{plugin.title}</h3>+ {showCategory ? (+ <span className="shrink-0 text-[11px] text-muted-foreground">{plugin.category}</span>+ ) : null}+ </div>+ <p className="truncate text-xs leading-5 text-muted-foreground">{plugin.description}</p>+ </div>+ <ChevronRightIcon+ aria-hidden="true"+ className="size-4 shrink-0 text-muted-foreground/60 transition-transform group-hover:translate-x-0.5 group-hover:text-foreground"+ />+ </button>+ <Button+ aria-label={`${installed ? "Remove" : "Add"} ${plugin.title}`}+ className="h-7 min-w-14 rounded-full px-3 text-xs"+ size="sm"+ variant="secondary"+ disabled={pending}+ onClick={() => onToggle(!installed)}+ >+ {installed ? <CheckIcon className="size-3.5" /> : null}+ {installed ? "Added" : "Add"}+ </Button>+ </article>+ );+}++export function PluginsCatalog({+ sections,+ servers,+ pendingServerId,+ onToggle,+ onOpen,+ onViewAll,+}: PluginsCatalogProps) {+ const resultCount = sections.reduce((count, section) => count + section.plugins.length, 0);+ if (resultCount === 0) {+ return <p className="py-14 text-center text-sm text-muted-foreground">No plugins match.</p>;+ }+ return (+ <div className="space-y-7">+ {sections.map((section) => (+ <section aria-label={section.title} key={section.title}>+ <div className="mb-2 flex items-center justify-between px-2">+ <h2 className="text-xs font-medium text-muted-foreground">{section.title}</h2>+ {section.showViewAll ? (+ <button+ className="cursor-pointer rounded text-xs text-muted-foreground outline-hidden hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"+ type="button"+ onClick={() => onViewAll(section.filter)}+ >+ View all+ </button>+ ) : null}+ </div>+ <div className="grid grid-cols-1 gap-x-7 md:grid-cols-2">+ {section.plugins.map((plugin) => {+ const server = findPluginServer(plugin, servers);+ return (+ <PluginRow+ key={`${section.title}:${plugin.id}`}+ plugin={plugin}+ server={server}+ pending={pendingServerId === pluginMcpServerId(plugin)}+ onToggle={(enabled) => onToggle(plugin, enabled)}+ onOpen={() => onOpen(plugin)}+ showCategory={section.title === "Search results"}+ />+ );+ })}+ </div>+ </section>+ ))}+ </div>+ );+}++function serverDescription(server: McpServer): string {+ return server.transport === "url"+ ? server.url+ : [server.command, ...(server.args ?? [])].join(" ");+}++interface CustomMcpServersProps {+ readonly servers: readonly McpServer[];+ readonly pendingServerId: string | null;+ readonly onToggle: (server: McpServer, enabled: boolean) => void;+ readonly onEdit: (server: McpServer) => void;+ readonly onDelete: (server: McpServer) => void;+}++export function CustomMcpServers({+ servers,+ pendingServerId,+ onToggle,+ onEdit,+ onDelete,+}: CustomMcpServersProps) {+ if (servers.length === 0) return null;+ return (+ <section aria-labelledby="custom-mcp-title">+ <div className="mb-2 flex items-center justify-between px-2">+ <h2 className="text-xs font-medium text-muted-foreground" id="custom-mcp-title">+ Custom MCP servers+ </h2>+ <span className="text-xs text-muted-foreground">{servers.length}</span>+ </div>+ <div className="grid grid-cols-1 gap-x-7 md:grid-cols-2">+ {servers.map((server) => {+ const pending = pendingServerId === server.id;+ return (+ <div+ className="group flex min-w-0 items-center gap-3 rounded-xl px-2.5 py-2.5 transition-colors hover:bg-muted/45"+ key={server.id}+ >+ <span+ aria-hidden="true"+ className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted p-2"+ >+ <img+ alt=""+ className="size-full object-contain dark:hidden"+ src="/plugin-logos/mcp.svg"+ />+ <img+ alt=""+ className="hidden size-full object-contain dark:block"+ src="/plugin-logos/mcp-dark.svg"+ />+ </span>+ <div className="min-w-0 flex-1">+ <p className="truncate text-sm font-medium">{server.name}</p>+ <p className="truncate text-xs leading-5 text-muted-foreground">+ {serverDescription(server)}+ </p>+ </div>+ <Button+ aria-label={`Edit ${server.name}`}+ className="opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100 max-sm:opacity-100"+ size="icon-sm"+ variant="ghost-muted"+ disabled={pending}+ onClick={() => onEdit(server)}+ >+ <PencilIcon className="size-3.5" />+ </Button>+ <Button+ aria-label={`Delete ${server.name}`}+ className="opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100 max-sm:opacity-100"+ size="icon-sm"+ variant="ghost-muted"+ disabled={pending}+ onClick={() => onDelete(server)}+ >+ <Trash2Icon className="size-3.5" />+ </Button>+ <Button+ aria-label={`${server.enabled ? "Disable" : "Enable"} ${server.name}`}+ className="h-7 min-w-14 rounded-full px-3 text-xs"+ size="sm"+ variant="secondary"+ disabled={pending}+ onClick={() => onToggle(server, !server.enabled)}+ >+ {server.enabled ? <CheckIcon className="size-3.5" /> : null}+ {server.enabled ? "Added" : "Add"}+ </Button>+ </div>+ );+ })}+ </div>+ </section>+ );+}diff --git a/apps/web/src/components/plugins/PluginsDialog.test.tsx b/apps/web/src/components/plugins/PluginsDialog.test.tsxnew file mode 100644index 000000000..7b9cab4fc--- /dev/null+++ b/apps/web/src/components/plugins/PluginsDialog.test.tsx@@ -0,0 +1,143 @@+import { McpServerId, type McpServer } from "@t3tools/contracts";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vite-plus/test";+import { loadCatalog } from "../../../../../plugins";+import { PluginDetailsContent } from "./PluginDetails";+import {+ EMPTY_MCP_SERVER_DRAFT,+ PLUGIN_DIALOG_CLASS_NAME,+ PLUGIN_DIRECTORY_HEADER_CLASS_NAME,+ PLUGIN_DIRECTORY_PANEL_CLASS_NAME,+ validateMcpServerDraft,+} from "./PluginsDialog";+import { CustomMcpServers, PluginsCatalog } from "./PluginsCatalog";+import { buildPluginSections } from "./pluginPresentation";+import { planPluginToggle, pluginMcpServerId } from "./pluginRegistry";++const catalog = loadCatalog();+const firecrawl = catalog.find((plugin) => plugin.id === "firecrawl");+if (!firecrawl) throw new TypeError("Firecrawl is missing from the plugin catalog.");++const rawServer: McpServer = {+ id: McpServerId.make("raw-filesystem"),+ name: "Raw filesystem",+ transport: "stdio",+ command: "bunx",+ args: ["@modelcontextprotocol/server-filesystem", "."],+ enabled: true,+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z",+};++describe("Plugins dialog content", () => {+ it("keeps the marketplace and plugin details at one fixed size", () => {+ expect(PLUGIN_DIALOG_CLASS_NAME).toContain("h-[min(48rem,90dvh)]");+ expect(PLUGIN_DIALOG_CLASS_NAME).not.toContain("has-");+ });++ it("keeps section labels clear of the directory header", () => {+ expect(PLUGIN_DIRECTORY_HEADER_CLASS_NAME).not.toContain("border-b");+ expect(PLUGIN_DIRECTORY_PANEL_CLASS_NAME).toContain("pt-5!");+ });++ it("renders a categorized directory with compact add and configure controls", () => {+ const markup = renderToStaticMarkup(+ <PluginsCatalog+ sections={buildPluginSections({ plugins: catalog, query: "", filter: "All" })}+ servers={[]}+ pendingServerId={null}+ onToggle={() => undefined}+ onOpen={() => undefined}+ onViewAll={() => undefined}+ />,+ );+ expect(markup).toContain("Featured");+ expect(markup).toContain("Data Extraction");+ expect(markup).toContain("Search");+ expect(markup).toContain("Add Firecrawl");+ expect(markup).toContain("Open Firecrawl");+ expect(markup).toContain("cursor-pointer");+ expect(markup).not.toContain("Configure Firecrawl");+ expect(markup).toContain("/plugin-logos/context.png");+ expect(markup).toContain("/plugin-logos/firecrawl.svg");+ expect(markup).toContain("/plugin-logos/exa.svg");+ expect(markup).toContain("/plugin-logos/parallel.svg");+ for (const plugin of catalog) expect(markup).toContain(`data-plugin-id="${plugin.id}"`);+ });++ it("shows plugin information instead of transport configuration", () => {+ const markup = renderToStaticMarkup(+ <PluginDetailsContent+ plugin={firecrawl}+ installed={false}+ pending={false}+ onToggle={() => undefined}+ onCopySource={() => undefined}+ onViewSource={() => undefined}+ onOpenSkill={() => undefined}+ />,+ );+ expect(markup).toContain("Documentation");+ expect(markup).toContain("Copy link");+ expect(markup).toContain("Connector");+ expect(markup).toContain("1 available");+ expect(markup).toContain("MCP connector");+ expect(markup).toContain("pt-6!");+ expect(markup).not.toContain("Transport");+ expect(markup).not.toContain("Arguments, one per line");+ });++ it("shows official skills as separate installs", () => {+ const markup = renderToStaticMarkup(+ <PluginDetailsContent+ plugin={firecrawl}+ installed={false}+ pending={false}+ onToggle={() => undefined}+ onCopySource={() => undefined}+ onViewSource={() => undefined}+ onOpenSkill={() => undefined}+ />,+ );+ expect(markup).toContain("Skills");+ expect(markup).toContain("Installed separately");+ expect(markup).toContain("Firecrawl CLI");+ });++ it("plans the Firecrawl switch through the MCP registry", () => {+ expect(planPluginToggle(firecrawl, [], true)).toEqual({+ action: "create",+ mcpServerId: pluginMcpServerId(firecrawl),+ configuration: {+ name: "Firecrawl",+ transport: "url",+ url: "https://mcp.firecrawl.dev/v2/mcp-oauth",+ },+ });+ });++ it("keeps existing custom MCP controls and validates editor input", () => {+ const markup = renderToStaticMarkup(+ <CustomMcpServers+ servers={[rawServer]}+ pendingServerId={null}+ onToggle={() => undefined}+ onEdit={() => undefined}+ onDelete={() => undefined}+ />,+ );+ expect(markup).toContain("Raw filesystem");+ expect(markup).toContain("Disable Raw filesystem");+ expect(markup).toContain("Edit Raw filesystem");+ expect(markup).toContain("Delete Raw filesystem");+ expect(validateMcpServerDraft(EMPTY_MCP_SERVER_DRAFT)).toBe("Name is required.");+ expect(+ validateMcpServerDraft({+ ...EMPTY_MCP_SERVER_DRAFT,+ name: "Remote tools",+ transport: "url",+ url: "https://mcp.example.com",+ }),+ ).toBeNull();+ });+});diff --git a/apps/web/src/components/plugins/PluginsDialog.tsx b/apps/web/src/components/plugins/PluginsDialog.tsxnew file mode 100644index 000000000..a3990431a--- /dev/null+++ b/apps/web/src/components/plugins/PluginsDialog.tsx@@ -0,0 +1,487 @@+import { useAtomValue } from "@effect/atom-react";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import type { EnvironmentId, McpServer } from "@t3tools/contracts";+import { ChevronLeftIcon, ChevronRightIcon, SearchIcon } from "lucide-react";+import { useMemo, useState } from "react";+import { loadCatalog, type PluginDefinition, type PluginSkill } from "../../../../../plugins";+import { ensureLocalApi } from "../../localApi";+import { cn } from "../../lib/utils";+import { closePlugins, usePluginsDialogStore } from "../../pluginsDialogStore";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { environmentMcpServersAtom, mcpServerEnvironment } from "../../state/mcpServers";+import { useAtomCommand } from "../../state/use-atom-command";+import { Button } from "../ui/button";+import {+ Dialog,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogPanel,+ DialogPopup,+ DialogTitle,+} from "../ui/dialog";+import { Field, FieldLabel } from "../ui/field";+import { Input } from "../ui/input";+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";+import { Textarea } from "../ui/textarea";+import { toastManager } from "../ui/toast";+import { CustomMcpServers, PluginLogoImage, PluginsCatalog } from "./PluginsCatalog";+import { PluginDetails } from "./PluginDetails";+import {+ findPluginServer,+ isBuiltinMcpServer,+ planPluginToggle,+ pluginMcpServerId,+} from "./pluginRegistry";+import {+ buildInstalledPluginSection,+ buildPluginSections,+ PLUGIN_FILTERS,+ type PluginFilter,+} from "./pluginPresentation";++const CATALOG = loadCatalog();++export const PLUGIN_DIALOG_CLASS_NAME = "h-[min(48rem,90dvh)] max-w-5xl flex-col overflow-hidden";+export const PLUGIN_DIRECTORY_HEADER_CLASS_NAME =+ "max-h-[45%] min-h-0 gap-3 overflow-y-auto overscroll-contain px-6 py-5";+export const PLUGIN_DIRECTORY_PANEL_CLASS_NAME = "space-y-8 px-5 pt-5! pb-5 sm:px-6";++export interface McpServerDraft {+ readonly name: string;+ readonly transport: "stdio" | "url";+ readonly command: string;+ readonly args: string;+ readonly url: string;+}++export const EMPTY_MCP_SERVER_DRAFT: McpServerDraft = {+ name: "",+ transport: "stdio",+ command: "",+ args: "",+ url: "",+};++type EditorTarget = { readonly server: McpServer };++type DirectoryView =+ | { readonly kind: "catalog" }+ | { readonly kind: "installed" }+ | {+ readonly kind: "plugin";+ readonly plugin: PluginDefinition;+ readonly back: "catalog" | "installed";+ };++function draftFromServer(server: McpServer): McpServerDraft {+ return server.transport === "stdio"+ ? {+ name: server.name,+ transport: "stdio",+ command: server.command,+ args: server.args?.join("\n") ?? "",+ url: "",+ }+ : {+ name: server.name,+ transport: "url",+ command: "",+ args: "",+ url: server.url,+ };+}++export function validateMcpServerDraft(draft: McpServerDraft): string | null {+ if (!draft.name.trim()) return "Name is required.";+ if (draft.transport === "stdio") {+ return draft.command.trim() ? null : "Command is required.";+ }+ try {+ const url = new URL(draft.url.trim());+ return url.protocol === "http:" || url.protocol === "https:"+ ? null+ : "URL must start with http:// or https://.";+ } catch {+ return "Enter a valid HTTP or HTTPS URL.";+ }+}++function PluginsDialogForEnvironment({ environmentId }: { readonly environmentId: EnvironmentId }) {+ const servers = useAtomValue(environmentMcpServersAtom(environmentId));+ const createServer = useAtomCommand(mcpServerEnvironment.create, { reportFailure: false });+ const updateServer = useAtomCommand(mcpServerEnvironment.update, { reportFailure: false });+ const deleteServer = useAtomCommand(mcpServerEnvironment.delete, { reportFailure: false });+ const enableServer = useAtomCommand(mcpServerEnvironment.enable, { reportFailure: false });+ const disableServer = useAtomCommand(mcpServerEnvironment.disable, { reportFailure: false });+ const [query, setQuery] = useState("");+ const [filter, setFilter] = useState<PluginFilter>("All");+ const [view, setView] = useState<DirectoryView>({ kind: "catalog" });+ const [editorTarget, setEditorTarget] = useState<EditorTarget | null>(null);+ const [draft, setDraft] = useState(EMPTY_MCP_SERVER_DRAFT);+ const [submitAttempted, setSubmitAttempted] = useState(false);+ const [pendingServerId, setPendingServerId] = useState<string | null>(null);+ const sections = useMemo(+ () => buildPluginSections({ plugins: CATALOG, query, filter }),+ [filter, query],+ );+ const customServers = servers.filter((server) => !isBuiltinMcpServer(server));+ const installedPlugins = CATALOG.filter((plugin) => findPluginServer(plugin, servers)?.enabled);+ const installedSections = buildInstalledPluginSection({ plugins: installedPlugins, query });+ const validationError = validateMcpServerDraft(draft);++ const reportFailure = (+ title: string,+ result: Awaited<ReturnType<typeof createServer>>,+ ): boolean => {+ if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return false;+ const error = squashAtomCommandFailure(result);+ toastManager.add({+ type: "error",+ title,+ description: error instanceof Error ? error.message : "The command failed.",+ });+ return true;+ };++ const openCustomEditor = (server: McpServer) => {+ setEditorTarget({ server });+ setDraft(draftFromServer(server));+ setSubmitAttempted(false);+ };++ const closeEditor = () => {+ setEditorTarget(null);+ setSubmitAttempted(false);+ };++ const togglePlugin = async (plugin: PluginDefinition, enabled: boolean) => {+ const plan = planPluginToggle(plugin, servers, enabled);+ setPendingServerId(plan.mcpServerId);+ if (plan.action === "refresh-and-enable") {+ const updateResult = await updateServer({+ environmentId,+ input: { mcpServerId: plan.mcpServerId, ...plan.configuration },+ });+ if (reportFailure(`Could not update ${plugin.title}`, updateResult)) {+ setPendingServerId(null);+ return;+ }+ }+ const result =+ plan.action === "create"+ ? await createServer({+ environmentId,+ input: { mcpServerId: plan.mcpServerId, ...plan.configuration },+ })+ : await (plan.action === "refresh-and-enable" ? enableServer : disableServer)({+ environmentId,+ input: { mcpServerId: plan.mcpServerId },+ });+ setPendingServerId(null);+ reportFailure(+ enabled ? `Could not enable ${plugin.title}` : `Could not disable ${plugin.title}`,+ result,+ );+ };++ const toggleCustom = async (server: McpServer, enabled: boolean) => {+ setPendingServerId(server.id);+ const result = await (enabled ? enableServer : disableServer)({+ environmentId,+ input: { mcpServerId: server.id },+ });+ setPendingServerId(null);+ reportFailure(enabled ? "Could not enable MCP server" : "Could not disable MCP server", result);+ };++ const saveEditor = async () => {+ setSubmitAttempted(true);+ if (!editorTarget || validationError) return;+ const mcpServerId = editorTarget.server.id;+ const configuration =+ draft.transport === "stdio"+ ? {+ name: draft.name.trim(),+ transport: "stdio" as const,+ command: draft.command.trim(),+ args: draft.args+ .split("\n")+ .map((argument) => argument.trim())+ .filter(Boolean),+ }+ : { name: draft.name.trim(), transport: "url" as const, url: draft.url.trim() };+ setPendingServerId(mcpServerId);+ const result = await updateServer({+ environmentId,+ input: { mcpServerId, ...configuration },+ });+ setPendingServerId(null);+ if (!reportFailure("Could not update MCP server", result)) closeEditor();+ };++ const openPlugin = (plugin: PluginDefinition) => {+ setView({+ kind: "plugin",+ plugin,+ back: view.kind === "installed" ? "installed" : "catalog",+ });+ };++ const openCatalog = () => {+ setQuery("");+ setFilter("All");+ setView({ kind: "catalog" });+ };++ const openInstalled = () => {+ setQuery("");+ setView({ kind: "installed" });+ };++ const copyPluginSource = async (plugin: PluginDefinition) => {+ if (!plugin.docsUrl) return;+ try {+ await navigator.clipboard.writeText(plugin.docsUrl);+ toastManager.add({ type: "success", title: "Source link copied" });+ } catch {+ toastManager.add({ type: "error", title: "Could not copy source link" });+ }+ };++ const openExternal = (url: string, failureTitle: string) => {+ void ensureLocalApi()+ .shell.openExternal(url)+ .catch(() => toastManager.add({ type: "error", title: failureTitle }));+ };++ const viewPluginSource = (plugin: PluginDefinition) => {+ if (plugin.docsUrl) openExternal(plugin.docsUrl, "Could not open documentation");+ };++ const openPluginSkill = (skill: PluginSkill) => {+ openExternal(skill.url, "Could not open skill");+ };++ const removeCustom = async (server: McpServer) => {+ const confirmed = await ensureLocalApi().dialogs.confirm(+ `Delete the MCP server '${server.name}'?`,+ { variant: "destructive" },+ );+ if (!confirmed) return;+ setPendingServerId(server.id);+ const result = await deleteServer({ environmentId, input: { mcpServerId: server.id } });+ setPendingServerId(null);+ reportFailure("Could not delete MCP server", result);+ };++ return (+ <>+ {view.kind === "plugin" ? (+ <PluginDetails+ plugin={view.plugin}+ installed={findPluginServer(view.plugin, servers)?.enabled ?? false}+ pending={pendingServerId === pluginMcpServerId(view.plugin)}+ onBack={() => setView({ kind: view.back })}+ onToggle={(enabled) => void togglePlugin(view.plugin, enabled)}+ onCopySource={() => void copyPluginSource(view.plugin)}+ onViewSource={() => viewPluginSource(view.plugin)}+ onOpenSkill={openPluginSkill}+ />+ ) : (+ <>+ <DialogHeader className={PLUGIN_DIRECTORY_HEADER_CLASS_NAME}>+ <div className="flex items-start justify-between gap-4 pe-8">+ <div className="min-w-0">+ <DialogTitle>Plugins</DialogTitle>+ {view.kind === "catalog" ? (+ <button+ className="group -ms-2 mt-2 flex min-h-11 cursor-pointer items-center gap-2.5 rounded-xl px-2 py-1.5 text-start outline-hidden transition-colors hover:bg-muted/50 focus-visible:ring-2 focus-visible:ring-ring"+ type="button"+ onClick={openInstalled}+ >+ {installedPlugins.length > 0 ? (+ <span className="flex -space-x-2" aria-hidden="true">+ {installedPlugins.slice(0, 3).map((plugin) => (+ <PluginLogoImage className="size-9" key={plugin.id} plugin={plugin} />+ ))}+ </span>+ ) : null}+ <span className="min-w-0">+ <span className="block text-sm font-medium text-foreground">+ {installedPlugins.length} installed+ </span>+ <span className="block text-xs text-muted-foreground">+ {customServers.length} custom{" "}+ {customServers.length === 1 ? "server" : "servers"}+ </span>+ </span>+ <ChevronRightIcon className="size-4 text-muted-foreground transition-transform group-hover:translate-x-0.5 group-hover:text-foreground" />+ </button>+ ) : (+ <Button className="mt-3 -ms-2" size="sm" variant="ghost" onClick={openCatalog}>+ <ChevronLeftIcon className="size-4" />+ Back to marketplace+ </Button>+ )}+ </div>+ </div>+ <div className="relative">+ <SearchIcon+ aria-hidden="true"+ className="pointer-events-none absolute start-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground"+ />+ <Input+ aria-label={+ view.kind === "installed" ? "Search installed plugins" : "Search plugins"+ }+ value={query}+ onChange={(event) => setQuery(event.currentTarget.value)}+ placeholder={view.kind === "installed" ? "Search installed" : "Search plugins"}+ className="h-9 ps-9"+ />+ </div>+ {view.kind === "catalog" ? (+ <div className="flex flex-wrap gap-1.5" aria-label="Plugin categories">+ {PLUGIN_FILTERS.map((item) => (+ <button+ aria-pressed={filter === item}+ className={cn(+ "cursor-pointer rounded-md border px-2.5 py-1 text-xs outline-hidden transition-colors focus-visible:ring-2 focus-visible:ring-ring",+ filter === item+ ? "border-transparent bg-accent text-accent-foreground"+ : "border-border/70 text-muted-foreground hover:bg-muted/60 hover:text-foreground",+ )}+ key={item}+ type="button"+ onClick={() => setFilter(item)}+ >+ {item}+ </button>+ ))}+ </div>+ ) : null}+ </DialogHeader>+ <DialogPanel className={PLUGIN_DIRECTORY_PANEL_CLASS_NAME}>+ <PluginsCatalog+ sections={view.kind === "installed" ? installedSections : sections}+ servers={servers}+ pendingServerId={pendingServerId}+ onToggle={(plugin, enabled) => void togglePlugin(plugin, enabled)}+ onOpen={openPlugin}+ onViewAll={setFilter}+ />+ {view.kind === "installed" ? (+ <CustomMcpServers+ servers={customServers}+ pendingServerId={pendingServerId}+ onToggle={(server, enabled) => void toggleCustom(server, enabled)}+ onEdit={openCustomEditor}+ onDelete={(server) => void removeCustom(server)}+ />+ ) : null}+ </DialogPanel>+ </>+ )}+ <Dialog open={editorTarget !== null} onOpenChange={(open) => !open && closeEditor()}>+ <DialogPopup className="max-h-[min(36rem,90dvh)] max-w-lg flex-col overflow-hidden">+ <DialogHeader className="shrink-0 border-b px-6 py-5">+ <DialogTitle>Edit MCP server</DialogTitle>+ </DialogHeader>+ <DialogPanel className="space-y-4 px-6 py-5">+ <Field>+ <FieldLabel>Name</FieldLabel>+ <Input+ autoFocus+ value={draft.name}+ onChange={(event) => setDraft({ ...draft, name: event.currentTarget.value })}+ />+ </Field>+ <Field>+ <FieldLabel>Transport</FieldLabel>+ <Select+ value={draft.transport}+ onValueChange={(transport) => {+ if (transport === "stdio" || transport === "url")+ setDraft({ ...draft, transport });+ }}+ >+ <SelectTrigger className="w-full" aria-label="MCP transport">+ <SelectValue>+ {draft.transport === "stdio" ? "Local command" : "Remote URL"}+ </SelectValue>+ </SelectTrigger>+ <SelectPopup>+ <SelectItem value="stdio">Local command</SelectItem>+ <SelectItem value="url">Remote URL</SelectItem>+ </SelectPopup>+ </Select>+ </Field>+ {draft.transport === "stdio" ? (+ <>+ <Field>+ <FieldLabel>Command</FieldLabel>+ <Input+ value={draft.command}+ onChange={(event) => setDraft({ ...draft, command: event.currentTarget.value })}+ placeholder="bunx"+ />+ </Field>+ <Field>+ <FieldLabel>Arguments, one per line</FieldLabel>+ <Textarea+ rows={4}+ value={draft.args}+ onChange={(event) => setDraft({ ...draft, args: event.currentTarget.value })}+ />+ </Field>+ </>+ ) : (+ <Field>+ <FieldLabel>URL</FieldLabel>+ <Input+ value={draft.url}+ onChange={(event) => setDraft({ ...draft, url: event.currentTarget.value })}+ placeholder="https://mcp.example.com"+ />+ </Field>+ )}+ {submitAttempted && validationError ? (+ <p className="text-xs text-destructive-foreground">{validationError}</p>+ ) : null}+ </DialogPanel>+ <DialogFooter className="shrink-0">+ <Button variant="ghost" onClick={closeEditor}>+ Cancel+ </Button>+ <Button disabled={pendingServerId !== null} onClick={() => void saveEditor()}>+ Save+ </Button>+ </DialogFooter>+ </DialogPopup>+ </Dialog>+ </>+ );+}++export function PluginsDialog() {+ const open = usePluginsDialogStore((state) => state.open);+ const environmentId = usePrimaryEnvironmentId();+ return (+ <Dialog open={open} onOpenChange={(nextOpen) => !nextOpen && closePlugins()}>+ <DialogPopup bottomStickOnMobile={false} className={PLUGIN_DIALOG_CLASS_NAME}>+ {environmentId ? (+ <PluginsDialogForEnvironment environmentId={environmentId} />+ ) : (+ <DialogHeader>+ <DialogTitle>Plugins</DialogTitle>+ <DialogDescription>Connect an environment to manage plugins.</DialogDescription>+ </DialogHeader>+ )}+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/web/src/components/plugins/pluginPresentation.test.ts b/apps/web/src/components/plugins/pluginPresentation.test.tsnew file mode 100644index 000000000..2736564b7--- /dev/null+++ b/apps/web/src/components/plugins/pluginPresentation.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vite-plus/test";+import { loadCatalog } from "../../../../../plugins";+import {+ buildInstalledPluginSection,+ buildPluginSections,+ PLUGIN_FILTERS,+} from "./pluginPresentation";++const catalog = loadCatalog();++describe("plugin presentation", () => {+ it("builds a featured directory with the two focused categories", () => {+ const sections = buildPluginSections({ plugins: catalog, query: "", filter: "All" });+ expect(sections[0]?.title).toBe("Featured");+ expect(sections[0]?.plugins.map((plugin) => plugin.id)).toEqual([+ "context",+ "exa",+ "firecrawl",+ "parallel-search",+ ]);+ expect(sections.some((section) => section.title === "Data Extraction")).toBe(true);+ expect(sections.some((section) => section.title === "Search")).toBe(true);+ expect(PLUGIN_FILTERS).toEqual(["All", "Featured", "Data Extraction", "Search"]);+ });++ it("builds a single searchable installed section", () => {+ const installed = catalog.filter((plugin) => plugin.id === "firecrawl" || plugin.id === "exa");+ const sections = buildInstalledPluginSection({ plugins: installed, query: "Exa" });+ expect(sections).toHaveLength(1);+ expect(sections[0]?.title).toBe("Installed");+ expect(sections[0]?.plugins.map((plugin) => plugin.id)).toEqual(["exa"]);+ });++ it("filters by category and search text", () => {+ const searchPlugins = buildPluginSections({+ plugins: catalog,+ query: "",+ filter: "Search",+ });+ expect(searchPlugins[0]?.plugins.map((plugin) => plugin.id)).toEqual([+ "exa",+ "parallel-search",+ ]);++ const extraction = buildPluginSections({+ plugins: catalog,+ query: "data extraction",+ filter: "All",+ });+ expect(extraction[0]?.plugins.map((plugin) => plugin.id)).toEqual(["context", "firecrawl"]);+ });+});diff --git a/apps/web/src/components/plugins/pluginPresentation.ts b/apps/web/src/components/plugins/pluginPresentation.tsnew file mode 100644index 000000000..221416141--- /dev/null+++ b/apps/web/src/components/plugins/pluginPresentation.ts@@ -0,0 +1,94 @@+import {+ PLUGIN_CATEGORIES,+ type PluginCategory,+ type PluginDefinition,+} from "../../../../../plugins";++export type PluginFilter = "All" | "Featured" | PluginCategory;++export const PLUGIN_FILTERS: readonly PluginFilter[] = ["All", "Featured", ...PLUGIN_CATEGORIES];++export interface PluginSection {+ readonly title: string;+ readonly filter: PluginFilter;+ readonly plugins: readonly PluginDefinition[];+ readonly showViewAll: boolean;+}++export function buildInstalledPluginSection(input: {+ readonly plugins: readonly PluginDefinition[];+ readonly query: string;+}): readonly PluginSection[] {+ const query = input.query.trim().toLocaleLowerCase();+ const plugins = input.plugins.filter((plugin) =>+ `${plugin.title}\n${plugin.description}\n${plugin.category}`+ .toLocaleLowerCase()+ .includes(query),+ );+ return [{ title: "Installed", filter: "All", plugins, showViewAll: false }];+}++export function buildPluginSections(input: {+ readonly plugins: readonly PluginDefinition[];+ readonly query: string;+ readonly filter: PluginFilter;+}): readonly PluginSection[] {+ const query = input.query.trim().toLocaleLowerCase();+ const matching = input.plugins.filter((plugin) =>+ `${plugin.title}\n${plugin.description}\n${plugin.category}`+ .toLocaleLowerCase()+ .includes(query),+ );++ if (query) {+ const filtered =+ input.filter === "All"+ ? matching+ : matching.filter((plugin) =>+ input.filter === "Featured"+ ? plugin.featured === true+ : plugin.category === input.filter,+ );+ return [+ { title: "Search results", filter: input.filter, plugins: filtered, showViewAll: false },+ ];+ }++ if (input.filter === "Featured") {+ return [+ {+ title: "Featured",+ filter: "Featured",+ plugins: matching.filter((plugin) => plugin.featured === true),+ showViewAll: false,+ },+ ];+ }++ if (input.filter !== "All") {+ return [+ {+ title: input.filter,+ filter: input.filter,+ plugins: matching.filter((plugin) => plugin.category === input.filter),+ showViewAll: false,+ },+ ];+ }++ const sections: PluginSection[] = [+ {+ title: "Featured",+ filter: "Featured",+ plugins: matching.filter((plugin) => plugin.featured === true),+ showViewAll: true,+ },+ ];+ for (const category of PLUGIN_CATEGORIES) {+ const plugins = matching.filter((plugin) => plugin.category === category);+ if (plugins.length > 0) {+ sections.push({ title: category, filter: category, plugins, showViewAll: true });+ }+ }+ return sections;+}diff --git a/apps/web/src/components/plugins/pluginRegistry.test.ts b/apps/web/src/components/plugins/pluginRegistry.test.tsnew file mode 100644index 000000000..9ea8bb3d2--- /dev/null+++ b/apps/web/src/components/plugins/pluginRegistry.test.ts@@ -0,0 +1,61 @@+import { McpServerId, type McpServer } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";+import { loadCatalog } from "../../../../../plugins";+import {+ findPluginServer,+ isBuiltinMcpServer,+ planPluginToggle,+ pluginMcpConfiguration,+ pluginMcpServerId,+} from "./pluginRegistry";++const catalog = loadCatalog();+const exa = catalog.find((plugin) => plugin.id === "exa");+const firecrawl = catalog.find((plugin) => plugin.id === "firecrawl");+if (!exa || !firecrawl) throw new TypeError("Required catalog plugins are missing.");++const exaServer: McpServer = {+ id: pluginMcpServerId(exa),+ name: "Exa",+ transport: "url",+ url: "https://mcp.exa.ai/mcp",+ enabled: false,+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z",+};+const rawServer: McpServer = {+ id: McpServerId.make("raw-filesystem"),+ name: "Raw filesystem",+ transport: "stdio",+ command: "bunx",+ enabled: true,+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z",+};++describe("plugin registry mapping", () => {+ it("maps hosted plugins to their verified URLs", () => {+ expect(pluginMcpConfiguration(exa)).toEqual({+ name: "Exa",+ transport: "url",+ url: "https://mcp.exa.ai/mcp",+ });+ });++ it("creates, refreshes, enables, and disables through the existing registry", () => {+ expect(planPluginToggle(firecrawl, [exaServer], true).action).toBe("create");+ expect(planPluginToggle(exa, [exaServer], true)).toEqual({+ action: "refresh-and-enable",+ mcpServerId: exaServer.id,+ configuration: pluginMcpConfiguration(exa),+ });+ expect(planPluginToggle(exa, [exaServer], false).action).toBe("disable");+ });++ it("keeps custom MCP servers independent of builtin plugins", () => {+ expect(exaServer.enabled).toBe(false);+ expect(rawServer.enabled).toBe(true);+ expect(isBuiltinMcpServer(rawServer)).toBe(false);+ expect(findPluginServer(firecrawl, [exaServer, rawServer])).toBeUndefined();+ });+});diff --git a/apps/web/src/components/plugins/pluginRegistry.ts b/apps/web/src/components/plugins/pluginRegistry.tsnew file mode 100644index 000000000..4e84c6c4d--- /dev/null+++ b/apps/web/src/components/plugins/pluginRegistry.ts@@ -0,0 +1,58 @@+import { McpServerId, type McpServer, type McpServerConfiguration } from "@t3tools/contracts";+import type { PluginDefinition } from "../../../../../plugins";++const BUILTIN_PREFIX = "builtin-";++export function pluginMcpServerId(plugin: PluginDefinition): McpServerId {+ return McpServerId.make(`${BUILTIN_PREFIX}${plugin.id}`);+}++export function isBuiltinMcpServer(server: McpServer): boolean {+ return server.id.startsWith(BUILTIN_PREFIX);+}++export function findPluginServer(+ plugin: PluginDefinition,+ servers: readonly McpServer[],+): McpServer | undefined {+ const id = pluginMcpServerId(plugin);+ return servers.find((server) => server.id === id);+}++export function pluginMcpConfiguration(plugin: PluginDefinition): McpServerConfiguration {+ if (plugin.kind === "mcp-url") {+ return { name: plugin.title, transport: "url", url: plugin.url };+ }+ return {+ name: plugin.title,+ transport: "stdio",+ command: plugin.command,+ ...(plugin.args ? { args: [...plugin.args] } : {}),+ };+}++export type PluginTogglePlan =+ | {+ readonly action: "create" | "refresh-and-enable";+ readonly mcpServerId: McpServerId;+ readonly configuration: McpServerConfiguration;+ }+ | { readonly action: "disable"; readonly mcpServerId: McpServerId };++export function planPluginToggle(+ plugin: PluginDefinition,+ servers: readonly McpServer[],+ enabled: boolean,+): PluginTogglePlan {+ const mcpServerId = pluginMcpServerId(plugin);+ if (!findPluginServer(plugin, servers)) {+ return { action: "create", mcpServerId, configuration: pluginMcpConfiguration(plugin) };+ }+ return enabled+ ? {+ action: "refresh-and-enable",+ mcpServerId,+ configuration: pluginMcpConfiguration(plugin),+ }+ : { action: "disable", mcpServerId };+}diff --git a/apps/web/src/components/preview/PreviewPanel.tsx b/apps/web/src/components/preview/PreviewPanel.tsxindex eb3912fb5..d02261253 100644--- a/apps/web/src/components/preview/PreviewPanel.tsx+++ b/apps/web/src/components/preview/PreviewPanel.tsx@@ -33,7 +33,7 @@ export function PreviewPanel({<PreviewPanelShell mode={mode}><div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 p-8 text-center"><p className="max-w-sm text-sm text-muted-foreground">- Preview is only available in the T3 Code desktop app.+ Preview is only available in the Akeru Bot desktop app.</p></div></PreviewPanelShell>diff --git a/apps/web/src/components/roster/ActiveBotHeaderChip.tsx b/apps/web/src/components/roster/ActiveBotHeaderChip.tsxnew file mode 100644index 000000000..10ee627ec--- /dev/null+++ b/apps/web/src/components/roster/ActiveBotHeaderChip.tsx@@ -0,0 +1,30 @@+import { useState } from "react";++import { AvatarPickerDialog } from "./AvatarPickerDialog";+import { BotAvatarView } from "./BotAvatarView";+import { useSelectedBot } from "./rosterStore";++/**+ * The active bot's avatar and name, leading the chat header. Clicking the+ * avatar opens the avatar picker for that bot.+ */+export function ActiveBotHeaderChip() {+ const bot = useSelectedBot();+ const [pickerOpen, setPickerOpen] = useState(false);+ if (bot === null) return null;+ return (+ <div className="flex shrink-0 items-center gap-1.5">+ <button+ type="button"+ aria-label={`Change avatar for ${bot.name}`}+ data-bot-hover+ onClick={() => setPickerOpen(true)}+ className="cursor-pointer rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <BotAvatarView avatar={bot.avatar} name={bot.name} className="size-6" />+ </button>+ <span className="max-w-32 truncate text-sm font-medium text-foreground">{bot.name}</span>+ {pickerOpen ? <AvatarPickerDialog bot={bot} open onOpenChange={setPickerOpen} /> : null}+ </div>+ );+}diff --git a/apps/web/src/components/roster/AvatarPickerDialog.tsx b/apps/web/src/components/roster/AvatarPickerDialog.tsxnew file mode 100644index 000000000..51a449320--- /dev/null+++ b/apps/web/src/components/roster/AvatarPickerDialog.tsx@@ -0,0 +1,281 @@+import { useRef, useState } from "react";++import { cn } from "../../lib/utils";+import { Button } from "../ui/button";+import {+ Dialog,+ DialogFooter,+ DialogHeader,+ DialogPanel,+ DialogPopup,+ DialogTitle,+} from "../ui/dialog";+import { Switch } from "../ui/switch";+import { Toggle, ToggleGroup } from "../ui/toggle-group";+import { BotAvatarView } from "./BotAvatarView";+import {+ ditherSeedForName,+ orderedDitherRgba,+ rerollDitherSeed,+ resolveUploadAvatar,+ type UploadRendering,+} from "./dither.logic";+import { BLOB_COLORS, BLOB_SHAPES, resolveBlobRendering } from "./roster.logic";+import type { Bot, BotAvatar, BotBlobShape } from "./types";+import { useSaveBotAvatar } from "./useServerRoster";++type PickerTab = "bot" | "generate" | "upload";++// Uploads become small square data URLs so an oversized photo can neither+// bloat the persisted roster nor blow the localStorage quota.+const AVATAR_UPLOAD_SIZE = 128;+const AVATAR_UPLOAD_MAX_FILE_BYTES = 8 * 1024 * 1024;++async function downscaleAvatarImage(file: File): Promise<UploadRendering> {+ const bitmap = await createImageBitmap(file);+ try {+ const canvas = document.createElement("canvas");+ canvas.width = AVATAR_UPLOAD_SIZE;+ canvas.height = AVATAR_UPLOAD_SIZE;+ const context = canvas.getContext("2d");+ if (context === null) throw new Error("Canvas 2D is unavailable.");+ const side = Math.min(bitmap.width, bitmap.height);+ context.drawImage(+ bitmap,+ (bitmap.width - side) / 2,+ (bitmap.height - side) / 2,+ side,+ side,+ 0,+ 0,+ AVATAR_UPLOAD_SIZE,+ AVATAR_UPLOAD_SIZE,+ );+ const plainUrl = canvas.toDataURL("image/jpeg", 0.85);+ // Both renderings up front, so the dither toggle previews instantly. The+ // dithered image is near-1-bit, so PNG stays well under the JPEG's size.+ const imageData = context.getImageData(0, 0, AVATAR_UPLOAD_SIZE, AVATAR_UPLOAD_SIZE);+ orderedDitherRgba(imageData.data, imageData.width, imageData.height);+ context.putImageData(imageData, 0, 0);+ return { plainUrl, ditheredUrl: canvas.toDataURL("image/png") };+ } finally {+ bitmap.close();+ }+}++const TAB_LABELS: Record<PickerTab, string> = {+ bot: "Blob",+ generate: "Generate",+ upload: "Upload",+};++/**+ * Avatar picker for one bot. The Blob tab picks a blob shape and color;+ * Generate seeds a Dither Kit identicon from the bot's name with a reroll;+ * Upload previews a local image, optionally dithered, and applies it as a+ * data URL until server assets exist.+ */+export function AvatarPickerDialog({+ bot,+ open,+ onOpenChange,+}: {+ bot: Bot;+ open: boolean;+ onOpenChange: (open: boolean) => void;+}) {+ const saveBotAvatar = useSaveBotAvatar();+ const initialBlob = resolveBlobRendering(bot.avatar);+ const [tab, setTab] = useState<PickerTab>("bot");+ const [shape, setShape] = useState<BotBlobShape>(initialBlob.shape);+ const [color, setColor] = useState(initialBlob.color);+ const [seed, setSeed] = useState(+ bot.avatar.kind === "dither" ? bot.avatar.seed : ditherSeedForName(bot.name),+ );+ const [upload, setUpload] = useState<UploadRendering | null>(null);+ const uploadSequence = useRef(0);+ const [ditherUpload, setDitherUpload] = useState(false);+ const [failure, setFailure] = useState<"save" | "upload" | "too-large" | null>(null);+ const [saving, setSaving] = useState(false);++ const draftAvatar: BotAvatar | null =+ tab === "bot"+ ? { kind: "blob", shape, color }+ : tab === "generate"+ ? { kind: "dither", seed }+ : resolveUploadAvatar(upload, ditherUpload);++ const handleUpload = (file: File | undefined) => {+ if (!file) return;+ const sequence = ++uploadSequence.current;+ // A new selection invalidates both the prior preview and its in-flight+ // decode. Save stays disabled until the latest selection finishes.+ setUpload(null);+ setFailure(null);+ if (file.size > AVATAR_UPLOAD_MAX_FILE_BYTES) {+ setFailure("too-large");+ return;+ }+ void downscaleAvatarImage(file).then(+ (rendering) => {+ if (sequence === uploadSequence.current) setUpload(rendering);+ },+ (error: unknown) => {+ if (sequence !== uploadSequence.current) return;+ console.error("Could not read avatar image.", error);+ setFailure("upload");+ },+ );+ };++ const handleSave = async () => {+ if (draftAvatar === null || saving) return;+ setSaving(true);+ const saved = await saveBotAvatar(bot.id, draftAvatar);+ setSaving(false);+ if (!saved) {+ setFailure("save");+ return;+ }+ onOpenChange(false);+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogPopup className="max-w-sm">+ <DialogHeader>+ <DialogTitle>Avatar</DialogTitle>+ </DialogHeader>+ <DialogPanel className="flex flex-col gap-4">+ <ToggleGroup+ aria-label="Avatar source"+ variant="segmented"+ className="w-full *:flex-1"+ value={[tab]}+ onValueChange={(next) => {+ const value = next[0];+ if (value === "bot" || value === "generate" || value === "upload") {+ setFailure(null);+ setTab(value);+ }+ }}+ >+ {(["bot", "generate", "upload"] as const).map((option) => (+ <Toggle key={option} value={option}>+ {TAB_LABELS[option]}+ </Toggle>+ ))}+ </ToggleGroup>+ {tab === "bot" ? (+ <>+ <div className="flex justify-center">+ <BotAvatarView+ avatar={{ kind: "blob", shape, color }}+ name={bot.name}+ className="size-20"+ />+ </div>+ <div className="grid grid-cols-4 gap-2">+ {BLOB_SHAPES.map((option) => (+ <button+ key={option}+ type="button"+ aria-label={option}+ aria-pressed={shape === option}+ data-bot-hover+ onClick={() => setShape(option)}+ className={cn(+ "flex cursor-pointer items-center justify-center rounded-md p-1.5 outline-none focus-visible:ring-2 focus-visible:ring-ring",+ shape === option ? "bg-accent" : "hover:bg-accent/50",+ )}+ >+ <BotAvatarView+ avatar={{ kind: "blob", shape: option, color }}+ name=""+ className="size-9"+ />+ </button>+ ))}+ </div>+ <div className="flex flex-wrap justify-center gap-2">+ {BLOB_COLORS.map((option) => (+ <button+ key={option}+ type="button"+ aria-label={option}+ aria-pressed={color === option}+ onClick={() => setColor(option)}+ style={{ backgroundColor: option }}+ className={cn(+ "size-7 cursor-pointer rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring",+ color === option && "ring-2 ring-ring ring-offset-2 ring-offset-background",+ )}+ />+ ))}+ </div>+ </>+ ) : tab === "generate" ? (+ <div className="flex h-40 flex-col items-center justify-center gap-3">+ <BotAvatarView+ avatar={{ kind: "dither", seed }}+ name={bot.name}+ className="size-20"+ />+ <Button variant="outline" onClick={() => setSeed(rerollDitherSeed(bot.name))}>+ Reroll+ </Button>+ </div>+ ) : (+ <div className="flex h-40 flex-col items-center justify-center gap-3">+ {upload !== null ? (+ <img+ src={ditherUpload ? upload.ditheredUrl : upload.plainUrl}+ alt="Avatar preview"+ className="size-20 rounded-full object-cover"+ />+ ) : null}+ <label className="cursor-pointer text-sm font-medium text-foreground underline-offset-4 hover:underline">+ Choose image+ <input+ type="file"+ accept="image/*"+ className="sr-only"+ onChange={(event) => handleUpload(event.currentTarget.files?.[0])}+ />+ </label>+ {upload !== null ? (+ <div className="flex items-center gap-2 text-sm text-muted-foreground">+ <Switch+ id="dither-avatar-upload"+ checked={ditherUpload}+ onCheckedChange={setDitherUpload}+ />+ <label htmlFor="dither-avatar-upload" className="cursor-pointer">+ Dither image+ </label>+ </div>+ ) : null}+ </div>+ )}+ </DialogPanel>+ <DialogFooter>+ {failure !== null ? (+ <p role="alert" className="mr-auto self-center text-sm text-destructive">+ {failure === "save"+ ? "Could not save"+ : failure === "too-large"+ ? "Image too large"+ : "Could not read image"}+ </p>+ ) : null}+ <Button variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button onClick={() => void handleSave()} disabled={draftAvatar === null || saving}>+ {saving ? "Saving" : "Save"}+ </Button>+ </DialogFooter>+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/web/src/components/roster/BotActivityStatus.test.tsx b/apps/web/src/components/roster/BotActivityStatus.test.tsxnew file mode 100644index 000000000..100a9888a--- /dev/null+++ b/apps/web/src/components/roster/BotActivityStatus.test.tsx@@ -0,0 +1,19 @@+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vite-plus/test";++import { BotActivityStatus } from "./BotActivityStatus";++describe("bot activity status", () => {+ it("shows a compact working label without tool details", () => {+ const markup = renderToStaticMarkup(+ <BotActivityStatus+ avatar={{ kind: "blob", shape: "circle", color: "#5B7FD4" }}+ name="Akeru"+ />,+ );++ expect(markup).toContain("Akeru is working");+ expect(markup).toContain("bot-status-shimmer");+ expect(markup).not.toContain("tool");+ });+});diff --git a/apps/web/src/components/roster/BotActivityStatus.tsx b/apps/web/src/components/roster/BotActivityStatus.tsxnew file mode 100644index 000000000..1467f57f0--- /dev/null+++ b/apps/web/src/components/roster/BotActivityStatus.tsx@@ -0,0 +1,21 @@+import { BotAvatarView } from "./BotAvatarView";+import type { BotAvatar } from "./types";++export function BotActivityStatus({+ avatar,+ name,+}: {+ readonly avatar: BotAvatar;+ readonly name: string;+}) {+ return (+ <div+ aria-live="polite"+ className="flex items-center gap-2.5 text-sm"+ data-testid="bot-activity-status"+ >+ <BotAvatarView avatar={avatar} name={name} className="size-7 shrink-0" state="working" />+ <span className="bot-status-shimmer font-medium">{name} is working</span>+ </div>+ );+}diff --git a/apps/web/src/components/roster/BotAvatarView.test.tsx b/apps/web/src/components/roster/BotAvatarView.test.tsxnew file mode 100644index 000000000..9d3f36cf4--- /dev/null+++ b/apps/web/src/components/roster/BotAvatarView.test.tsx@@ -0,0 +1,47 @@+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vite-plus/test";++import { BotAvatarView } from "./BotAvatarView";++describe("BotAvatarView", () => {+ it("renders ink-bar eyes on a blob instead of an initial", () => {+ const markup = renderToStaticMarkup(+ <BotAvatarView name="Theo" avatar={{ kind: "blob", shape: "circle", color: "#E0645C" }} />,+ );++ expect(markup).toContain('class="bot-eyes"');+ expect(markup).toContain('viewBox="-22 -18 44 36"');+ expect(markup).toContain('data-bot-state="idle"');+ expect(markup).not.toContain("</text>");+ expect(markup).not.toContain(">T</text>");+ });++ it("shortens the eyes while working", () => {+ const idle = renderToStaticMarkup(+ <BotAvatarView+ name="Akeru"+ state="idle"+ avatar={{ kind: "blob", shape: "square", color: "#5B7FD4" }}+ />,+ );+ const working = renderToStaticMarkup(+ <BotAvatarView+ name="Akeru"+ state="working"+ avatar={{ kind: "blob", shape: "square", color: "#5B7FD4" }}+ />,+ );++ expect(working).toContain('data-bot-state="working"');+ expect(working).not.toBe(idle);+ });++ it("renders a dither identicon without a face", () => {+ const markup = renderToStaticMarkup(+ <BotAvatarView name="Akeru" avatar={{ kind: "dither", seed: "akeru-seed" }} />,+ );++ expect(markup).toContain('data-avatar-dither="akeru-seed"');+ expect(markup).not.toContain("bot-eyes");+ });+});diff --git a/apps/web/src/components/roster/BotAvatarView.tsx b/apps/web/src/components/roster/BotAvatarView.tsxnew file mode 100644index 000000000..b5e83177b--- /dev/null+++ b/apps/web/src/components/roster/BotAvatarView.tsx@@ -0,0 +1,270 @@+import { useMemo, type CSSProperties } from "react";++import { cn } from "~/lib/utils";+import { generateDitherIdenticon, identiconPathData } from "./dither.logic";+import { blinkDelayMs, resolveBlobRendering } from "./roster.logic";+import type { BotAvatar, BotBlobShape } from "./types";++/**+ * Animation states a bot avatar can play. `idle` blinks; `working` loops+ * while a turn runs; `needs-you` calls the user over; `success` runs once on+ * a clean finish. The matching keyframes live in index.css under "Bot+ * avatars".+ */+export type BotAnimationState = "idle" | "working" | "needs-you" | "success";++/** Eyes are always near-black, ink on the body. */+const INK = "#0A0A0A";++/**+ * Where the face sits on the 100×100 viewBox. Bottom-heavy shapes (triangle,+ * drop) carry the face lower; small bodies (pill, cloud) shrink it a touch.+ */+const FACE_LAYOUT: Record<BotBlobShape, { y: number; scale: number }> = {+ circle: { y: 50, scale: 1 },+ squircle: { y: 50, scale: 1 },+ square: { y: 50, scale: 1 },+ pill: { y: 50, scale: 0.88 },+ triangle: { y: 63, scale: 0.85 },+ hex: { y: 51, scale: 0.95 },+ cloud: { y: 57, scale: 0.88 },+ drop: { y: 63, scale: 0.85 },+};++/**+ * Blob geometry on a 100×100 viewBox. Soft corners come from a round-joined+ * stroke in the fill color, so every shape reads as one solid blob.+ */+function BlobShape({ shape, color }: { shape: BotBlobShape; color: string }) {+ const soft = { fill: color, stroke: color, strokeWidth: 10, strokeLinejoin: "round" } as const;+ switch (shape) {+ case "circle":+ // Hand-wobbled circle so the body reads organic, not geometric.+ return (+ <path+ d="M96 51 C96 64 92.6 74.4 84.6 82.2 C76.6 90 64 96 51 96 C38 96 26.2 91 18.2 83 C10.2 75 4 63 4 50 C4 37 9.4 25.4 18.4 17.6 C27.4 9.8 39 4 52 4 C65 4 76.4 10 84.4 18 C92.4 26 96 38 96 51 Z"+ fill={color}+ />+ );+ case "squircle":+ return (+ <path+ d="M50 2 C86 2 98 14 98 50 C98 86 86 98 50 98 C14 98 2 86 2 50 C2 14 14 2 50 2 Z"+ fill={color}+ />+ );+ case "square":+ return <rect x="5" y="5" width="90" height="90" rx="16" fill={color} />;+ case "pill":+ return <rect x="2" y="22" width="96" height="56" rx="28" fill={color} />;+ case "triangle":+ return <path d="M50 10 L92 88 L8 88 Z" {...soft} />;+ case "hex":+ return <path d="M50 4 L90 27 L90 73 L50 96 L10 73 L10 27 Z" {...soft} />;+ case "cloud":+ return (+ <path d="M30 82 A17 17 0 0 1 26 49 A22 22 0 0 1 66 35 A19 19 0 0 1 74 82 Z" {...soft} />+ );+ case "drop":+ return (+ <path d="M50 6 C50 6 86 46 86 64 A36 36 0 1 1 14 64 C14 46 50 6 50 6 Z" fill={color} />+ );+ }+}++/**+ * Two slanted ink-bar eyes, swapped per state. Working shortens the bars into+ * a focused face. Needs-you raises and spreads them. Success closes them into+ * happy arcs.+ */+function Eyes({ state }: { state: BotAnimationState }) {+ switch (state) {+ case "working":+ return (+ <>+ <rect+ x="-13.5"+ y="0"+ width="9"+ height="10"+ rx="4.5"+ transform="rotate(14 -9 5)"+ fill={INK}+ />+ <rect+ x="4.5"+ y="0"+ width="9"+ height="10"+ rx="4.5"+ transform="rotate(14 9 5)"+ fill={INK}+ />+ </>+ );+ case "needs-you":+ return (+ <>+ <rect+ x="-15.5"+ y="-14"+ width="9"+ height="26"+ rx="4.5"+ transform="rotate(10 -11 0)"+ fill={INK}+ />+ <rect+ x="6.5"+ y="-14"+ width="9"+ height="26"+ rx="4.5"+ transform="rotate(10 11 0)"+ fill={INK}+ />+ </>+ );+ case "success":+ return (+ <>+ <path+ d="M-17 1 Q-11 -9 -5 1"+ stroke={INK}+ strokeWidth="4"+ strokeLinecap="round"+ fill="none"+ />+ <path+ d="M5 1 Q11 -9 17 1"+ stroke={INK}+ strokeWidth="4"+ strokeLinecap="round"+ fill="none"+ />+ </>+ );+ case "idle":+ return (+ <>+ <rect+ x="-14"+ y="-10"+ width="9"+ height="20"+ rx="4.5"+ transform="rotate(14 -9.5 0)"+ fill={INK}+ />+ <rect+ x="5"+ y="-10"+ width="9"+ height="20"+ rx="4.5"+ transform="rotate(14 9.5 0)"+ fill={INK}+ />+ </>+ );+ }+}++/**+ * The face. A nested svg owns the blink so scaleY uses that svg's viewBox,+ * not a <g> fill-box that collapses as the eyes close and strobes the avatar.+ */+function Face({ shape, state }: { shape: BotBlobShape; state: BotAnimationState }) {+ const { y, scale } = FACE_LAYOUT[shape];+ return (+ <g transform={`translate(50 ${y}) scale(${scale})`}>+ <svg+ className="bot-eyes"+ x="-22"+ y="-18"+ width="44"+ height="36"+ viewBox="-22 -18 44 36"+ overflow="visible"+ aria-hidden+ >+ <Eyes state={state} />+ </svg>+ </g>+ );+}++/**+ * Dither Kit identicon rendered from the seed alone: no stored bitmap, the+ * generator is deterministic. One background rect and one path keep it a+ * two-element SVG at every size.+ */+function DitherAvatar({ seed, className }: { seed: string; className?: string | undefined }) {+ const identicon = useMemo(() => generateDitherIdenticon(seed), [seed]);+ return (+ <svg+ viewBox={`0 0 ${identicon.size} ${identicon.size}`}+ aria-hidden+ className={cn("shrink-0 select-none rounded-full", className)}+ data-avatar-dither={seed}+ >+ <rect width={identicon.size} height={identicon.size} fill={identicon.background} />+ <path+ d={identiconPathData(identicon)}+ fill={identicon.foreground}+ shapeRendering="crispEdges"+ />+ </svg>+ );+}++/**+ * Renders any bot avatar at a caller-supplied size. Image avatars paint the+ * asset; dither avatars render their seeded identicon; blob avatars get a+ * face. Malformed data falls back to the default blob. `name` seeds the blink+ * phase so bots blink out of sync; `state` picks the animation the CSS plays.+ */+export function BotAvatarView({+ avatar,+ name,+ state = "idle",+ className,+}: {+ avatar: BotAvatar;+ name: string;+ state?: BotAnimationState;+ className?: string;+}) {+ if (avatar.kind === "dither") {+ return <DitherAvatar seed={avatar.seed} className={className} />;+ }++ if (avatar.kind === "image" && avatar.assetPath.length > 0) {+ return (+ <img+ src={avatar.assetPath}+ alt=""+ aria-hidden+ className={cn("shrink-0 rounded-full object-cover", className)}+ />+ );+ }++ const { shape, color } = resolveBlobRendering(avatar);+ return (+ <svg+ viewBox="0 0 100 100"+ aria-hidden+ overflow="visible"+ className={cn("bot-avatar shrink-0 select-none", className)}+ data-avatar-shape={shape}+ data-bot-state={state}+ style={{ "--bot-blink-delay": `${blinkDelayMs(name)}ms` } as CSSProperties}+ >+ <g className="bot-body">+ <BlobShape shape={shape} color={color} />+ <Face shape={shape} state={state} />+ </g>+ </svg>+ );+}diff --git a/apps/web/src/components/roster/BotConversationScrollArea.tsx b/apps/web/src/components/roster/BotConversationScrollArea.tsxnew file mode 100644index 000000000..cda8f826e--- /dev/null+++ b/apps/web/src/components/roster/BotConversationScrollArea.tsx@@ -0,0 +1,97 @@+import { ArrowDownIcon } from "lucide-react";+import { useEffect, useRef, useState, type ReactNode } from "react";++import { Button } from "../ui/button";+import {+ isConversationAtEnd,+ reduceConversationFollowState,+ type ConversationFollowState,+} from "./botConversationScroll.logic";++export function BotConversationScrollArea({ children }: { readonly children: ReactNode }) {+ const viewportRef = useRef<HTMLDivElement>(null);+ const contentRef = useRef<HTMLDivElement>(null);+ const followStateRef = useRef<ConversationFollowState>({+ followingEnd: true,+ programmaticScroll: false,+ });+ const [isAtEnd, setIsAtEnd] = useState(true);++ useEffect(() => {+ const viewport = viewportRef.current;+ const content = contentRef.current;+ if (!viewport || !content) return;++ const updateScrollState = () => {+ const nextIsAtEnd = isConversationAtEnd(viewport);+ setIsAtEnd(nextIsAtEnd);+ followStateRef.current = reduceConversationFollowState(followStateRef.current, {+ type: "scroll",+ isAtEnd: nextIsAtEnd,+ });+ };++ const followContentGrowth = () => {+ if (followStateRef.current.followingEnd) {+ viewport.scrollTop = viewport.scrollHeight;+ }+ updateScrollState();+ };++ viewport.scrollTop = viewport.scrollHeight;+ updateScrollState();+ const observer = new ResizeObserver(followContentGrowth);+ observer.observe(content);+ viewport.addEventListener("scroll", updateScrollState, { passive: true });++ return () => {+ observer.disconnect();+ viewport.removeEventListener("scroll", updateScrollState);+ };+ }, []);++ const stopFollowingEnd = () => {+ followStateRef.current = reduceConversationFollowState(followStateRef.current, {+ type: "user-navigation",+ });+ };++ const scrollToEnd = () => {+ const viewport = viewportRef.current;+ if (!viewport) return;+ followStateRef.current = reduceConversationFollowState(followStateRef.current, {+ type: "scroll-to-end",+ });+ viewport.scrollTo({ top: viewport.scrollHeight, behavior: "smooth" });+ };++ return (+ <div className="relative min-h-0 flex-1" data-testid="bot-conversation-scroll-area">+ <div+ ref={viewportRef}+ className="h-full overflow-y-auto overscroll-contain px-4 py-6 sm:px-6"+ onTouchMove={stopFollowingEnd}+ onWheel={(event) => {+ if (event.deltaY < 0) stopFollowingEnd();+ }}+ >+ <div ref={contentRef} className="flex min-h-full w-full flex-col">+ <div className="mt-auto flex w-full flex-col gap-4">{children}</div>+ </div>+ </div>++ {!isAtEnd ? (+ <Button+ type="button"+ variant="outline"+ size="icon"+ aria-label="Scroll to latest message"+ className="absolute bottom-3 start-1/2 z-10 -translate-x-1/2 rounded-full bg-popover shadow-lg"+ onClick={scrollToEnd}+ >+ <ArrowDownIcon className="size-4" />+ </Button>+ ) : null}+ </div>+ );+}diff --git a/apps/web/src/components/roster/BotDetailsPanel.test.tsx b/apps/web/src/components/roster/BotDetailsPanel.test.tsxnew file mode 100644index 000000000..82922fdd6--- /dev/null+++ b/apps/web/src/components/roster/BotDetailsPanel.test.tsx@@ -0,0 +1,107 @@+// @effect-diagnostics nodeBuiltinImport:off - The route contract reads its source.+import * as NodeFS from "node:fs";++import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vite-plus/test";++import { BotDetailsPanel, reduceBotDetailsPanelState } from "./BotDetailsPanel";+import type { Bot } from "./types";++const bot: Bot = {+ id: "bot-akeru",+ name: "Akeru",+ title: "Generalist",+ label: "Research",+ description: "Finds evidence and explains what matters.",+ disabledMcpServerIds: [],+ avatar: { kind: "blob", shape: "circle", color: "#5B7FD4" },+ engine: null,+ sandbox: null,+ runtimeMode: "full-access",+ usageCap: null,+ groupId: null,+ pinned: false,+ archivedAt: null,+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z",+};++describe("BotDetailsPanel", () => {+ it("shows the per-bot profile editor with simple panel chrome", () => {+ const markup = renderToStaticMarkup(<BotDetailsPanel bot={bot} />);+ expect(markup).toContain(">Settings</h2>");+ expect(markup).toContain('aria-label="Change bot avatar"');+ expect(markup).toContain('aria-label="Bot name"');+ expect(markup).toContain('aria-label="Bot label"');+ expect(markup).toContain('aria-label="Bot description"');+ expect(markup).toContain("Connect a provider");+ expect(markup).toContain(">Sandbox</div>");+ expect(markup).toContain('aria-label="Sandbox provider"');+ expect(markup).toContain(">Tools</div>");+ expect(markup).toContain("No workspace tools");+ expect(markup).toContain(">Manage</span>");+ expect(markup).toContain('aria-label="Collapse Akeru bot sidebar"');+ expect(markup).toContain('aria-label="Open Akeru bot sidebar"');+ expect(markup).not.toContain("Routines");+ expect(markup).not.toContain("mock data");+ expect(markup).not.toContain("border-b border-border");+ expect(markup).not.toContain("border-t border-border");+ });++ it("uses the configured right-panel shortcut while open or closed", () => {+ const source = NodeFS.readFileSync(new URL("./BotDetailsPanel.tsx", import.meta.url), "utf8");++ expect(source).toContain('resolveShortcutCommand(event, keybindings) !== "rightPanel.toggle"');+ expect(source).toContain('shortcutLabelForCommand(keybindings, "rightPanel.toggle")');+ expect(source).toContain('window.addEventListener("keydown", onKeyDown, true)');+ expect(source).toContain("RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY");+ });++ it("collapses and reopens desktop without changing the mobile sheet", () => {+ const collapsed = reduceBotDetailsPanelState(+ { desktopOpen: true, mobileOpen: false },+ { type: "toggle-desktop" },+ );+ expect(collapsed).toEqual({ desktopOpen: false, mobileOpen: false });++ expect(reduceBotDetailsPanelState(collapsed, { type: "toggle-desktop" })).toEqual({+ desktopOpen: true,+ mobileOpen: false,+ });+ });++ it("toggles the mobile sheet without changing desktop", () => {+ const opened = reduceBotDetailsPanelState(+ { desktopOpen: false, mobileOpen: false },+ { type: "toggle-mobile" },+ );+ expect(opened).toEqual({ desktopOpen: false, mobileOpen: true });+ expect(reduceBotDetailsPanelState(opened, { type: "toggle-mobile" })).toEqual({+ desktopOpen: false,+ mobileOpen: false,+ });+ });++ it("sets the mobile sheet state without changing desktop", () => {+ expect(+ reduceBotDetailsPanelState(+ { desktopOpen: true, mobileOpen: true },+ { type: "set-mobile", open: false },+ ),+ ).toEqual({ desktopOpen: true, mobileOpen: false });+ });++ it("mounts from the bot route instead of the generic panel", () => {+ const source = NodeFS.readFileSync(+ new URL("../../routes/_chat.bots.$botId.tsx", import.meta.url),+ "utf8",+ );+ expect(source).toContain("<BotDetailsPanel");+ expect(source).toContain("onSaveBot=");+ expect(source).toContain("label, description, engine, sandbox, disabledMcpServerIds");+ expect(source).toContain("sandbox,");+ expect(source).toContain("disabledMcpServerIds,");+ expect(source).not.toContain("RightPanelTabs");+ expect(source).not.toContain("ThreadTerminalDrawer");+ });+});diff --git a/apps/web/src/components/roster/BotDetailsPanel.tsx b/apps/web/src/components/roster/BotDetailsPanel.tsxnew file mode 100644index 000000000..a2d5385a4--- /dev/null+++ b/apps/web/src/components/roster/BotDetailsPanel.tsx@@ -0,0 +1,470 @@+import { useAtomValue } from "@effect/atom-react";+import {+ ProviderInstanceId,+ type BotEngine,+ type EnvironmentId,+ type McpServerId,+} from "@t3tools/contracts";+import {+ Cancel01Icon,+ Edit02Icon,+ PanelRightCloseIcon,+ PanelRightIcon,+ WrenchIcon,+} from "@hugeicons/core-free-icons";+import { useEffect, useMemo, useReducer, useState, type ReactNode } from "react";++import { usePrimarySettings } from "../../hooks/useSettings";+import { resolveShortcutCommand, shortcutLabelForCommand } from "../../keybindings";+import { RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY } from "../../rightPanelLayout";+import {+ getCustomModelOptionsByInstance,+ resolveAppModelSelectionForInstance,+ resolveAppModelSelectionState,+} from "../../modelSelection";+import {+ applyProviderInstanceSettings,+ deriveProviderInstanceEntries,+ resolveSelectableProviderInstanceEntry,+ sortProviderInstanceEntries,+} from "../../providerInstances";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { environmentMcpServersAtom } from "../../state/mcpServers";+import { primaryServerKeybindingsAtom, primaryServerProvidersAtom } from "../../state/server";+import { AppIcon } from "../ui/app-icon";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";+import { Sheet, SheetClose, SheetPopup, SheetTitle } from "../ui/sheet";+import { Textarea } from "../ui/textarea";+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";+import { AvatarPickerDialog } from "./AvatarPickerDialog";+import { BotAvatarView } from "./BotAvatarView";+import { BotModelPicker } from "./BotModelPicker";+import {+ BOT_SANDBOX_OPTIONS,+ botSandboxChoice,+ botSandboxLabel,+ type BotSandboxChoice,+} from "./botSandbox";+import { BotToolsSheet, buildBotToolItems } from "./BotToolsSheet";+import type { Bot } from "./types";++const NO_ENVIRONMENT = "" as EnvironmentId;++type BotDetailsPanelState = {+ readonly desktopOpen: boolean;+ readonly mobileOpen: boolean;+};++type BotDetailsPanelAction =+ | { readonly type: "toggle-desktop" }+ | { readonly type: "toggle-mobile" }+ | { readonly type: "set-mobile"; readonly open: boolean };++export function reduceBotDetailsPanelState(+ state: BotDetailsPanelState,+ action: BotDetailsPanelAction,+): BotDetailsPanelState {+ if (action.type === "toggle-desktop") {+ return { ...state, desktopOpen: !state.desktopOpen };+ }+ if (action.type === "toggle-mobile") {+ return { ...state, mobileOpen: !state.mobileOpen };+ }+ return { ...state, mobileOpen: action.open };+}++export interface BotProfileUpdate {+ readonly name: string;+ readonly label: string | null;+ readonly description: string | null;+ readonly engine: BotEngine | null;+ readonly sandbox: Bot["sandbox"];+ readonly disabledMcpServerIds: readonly McpServerId[];+}++function BotProfileEditor({+ bot,+ onSave,+}: {+ readonly bot: Bot;+ readonly onSave?: (input: BotProfileUpdate) => Promise<boolean>;+}) {+ const providers = useAtomValue(primaryServerProvidersAtom);+ const environmentId = usePrimaryEnvironmentId();+ const mcpServers = useAtomValue(environmentMcpServersAtom(environmentId ?? NO_ENVIRONMENT));+ const settings = usePrimarySettings();+ const [name, setName] = useState(bot.name);+ const [label, setLabel] = useState(bot.label ?? "");+ const [description, setDescription] = useState(bot.description ?? "");+ const [avatarOpen, setAvatarOpen] = useState(false);+ const [saving, setSaving] = useState(false);+ const [saved, setSaved] = useState(false);+ const [engineChanged, setEngineChanged] = useState(false);+ const [toolsOpen, setToolsOpen] = useState(false);+ const [sandbox, setSandbox] = useState<BotSandboxChoice>(() => botSandboxChoice(bot.sandbox));+ const [disabledMcpServerIds, setDisabledMcpServerIds] = useState<readonly McpServerId[]>(+ bot.disabledMcpServerIds,+ );++ const instanceEntries = useMemo(+ () =>+ sortProviderInstanceEntries(+ applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),+ ),+ [providers, settings],+ );+ const defaultSelection = useMemo(+ () => resolveAppModelSelectionState(settings, providers),+ [providers, settings],+ );+ const [provider, setProvider] = useState(bot.engine?.provider ?? defaultSelection.instanceId);+ const activeEntry = useMemo(+ () =>+ resolveSelectableProviderInstanceEntry(instanceEntries, ProviderInstanceId.make(provider)),+ [instanceEntries, provider],+ );+ const [model, setModel] = useState<string>(+ () =>+ bot.engine?.model ??+ (activeEntry+ ? resolveAppModelSelectionForInstance(activeEntry.instanceId, settings, providers, null)+ : null) ??+ defaultSelection.model,+ );+ const modelOptionsByInstance = useMemo(+ () => getCustomModelOptionsByInstance(settings, providers),+ [providers, settings],+ );++ useEffect(() => {+ if (engineChanged) return;+ setProvider(bot.engine?.provider ?? defaultSelection.instanceId);+ if (bot.engine?.model) setModel(bot.engine.model);+ }, [bot.engine, defaultSelection.instanceId, engineChanged]);++ const normalizedLabel = label.trim() || null;+ const normalizedDescription = description.trim() || null;+ const nextEngine: Bot["engine"] = engineChanged && model ? { provider, model } : bot.engine;+ const nextSandbox: Bot["sandbox"] = sandbox;+ const tools = useMemo(() => buildBotToolItems(mcpServers), [mcpServers]);+ const enabledToolCount = tools.filter(+ (tool) => tool.workspaceEnabled && !disabledMcpServerIds.includes(tool.id),+ ).length;+ const toolOverridesDirty =+ [...disabledMcpServerIds].sort().join("\u0000") !==+ [...bot.disabledMcpServerIds].sort().join("\u0000");+ const sandboxDirty = sandbox !== botSandboxChoice(bot.sandbox);+ const dirty =+ name.trim() !== bot.name ||+ normalizedLabel !== bot.label ||+ normalizedDescription !== bot.description ||+ engineChanged ||+ sandboxDirty ||+ toolOverridesDirty;++ const markChanged = () => setSaved(false);++ return (+ <div className="min-h-0 flex-1 overflow-y-auto px-5 pb-6">+ <div className="flex flex-col items-center pb-7 pt-6">+ <button+ type="button"+ aria-label="Change bot avatar"+ onClick={() => setAvatarOpen(true)}+ className="group relative rounded-2xl outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <BotAvatarView avatar={bot.avatar} name={name || bot.name} className="size-20" />+ <span className="absolute -bottom-1 -right-1 flex size-7 items-center justify-center rounded-full border border-border bg-background text-muted-foreground shadow-sm transition-colors group-hover:text-foreground">+ <AppIcon className="size-3.5" icon={Edit02Icon} />+ </span>+ </button>+ </div>++ <div className="space-y-5">+ <label className="block space-y-2 text-sm font-medium">+ Name+ <Input+ aria-label="Bot name"+ value={name}+ onChange={(event) => {+ setName(event.currentTarget.value);+ markChanged();+ }}+ />+ </label>++ <label className="block space-y-2 text-sm font-medium">+ <span>+ Label <span className="font-normal text-muted-foreground">(optional)</span>+ </span>+ <Input+ aria-label="Bot label"+ value={label}+ placeholder="Research, marketing, admin"+ onChange={(event) => {+ setLabel(event.currentTarget.value);+ markChanged();+ }}+ />+ </label>++ <label className="block space-y-2 text-sm font-medium">+ Description+ <Textarea+ aria-label="Bot description"+ value={description}+ placeholder="What this bot is for"+ rows={5}+ className="min-h-28 resize-none"+ onChange={(event) => {+ setDescription(event.currentTarget.value);+ markChanged();+ }}+ />+ </label>++ <div className="space-y-2">+ <div className="text-sm font-medium">Model</div>+ <div className="flex min-h-10 items-center rounded-lg border border-border bg-muted/20 px-2">+ {activeEntry && model ? (+ <BotModelPicker+ activeInstanceId={activeEntry.instanceId}+ model={model}+ instanceEntries={instanceEntries}+ modelOptionsByInstance={modelOptionsByInstance}+ onChange={(instanceId, nextModel) => {+ setProvider(instanceId);+ setModel(nextModel);+ setEngineChanged(true);+ markChanged();+ }}+ />+ ) : (+ <span className="px-1 text-sm text-muted-foreground">Connect a provider</span>+ )}+ </div>+ </div>++ <div className="space-y-2">+ <div className="text-sm font-medium">Sandbox</div>+ <Select+ value={sandbox}+ onValueChange={(value) => {+ if (value === null) return;+ if (!BOT_SANDBOX_OPTIONS.some((option) => option.value === value)) return;+ setSandbox(value as BotSandboxChoice);+ markChanged();+ }}+ >+ <SelectTrigger className="w-full bg-muted/20" aria-label="Sandbox provider">+ <SelectValue>{botSandboxLabel(sandbox)}</SelectValue>+ </SelectTrigger>+ <SelectPopup>+ {BOT_SANDBOX_OPTIONS.map((option) => (+ <SelectItem key={option.value} value={option.value}>+ {option.label}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ </div>++ <div className="space-y-2">+ <div className="text-sm font-medium">Tools</div>+ <button+ type="button"+ aria-label="Manage bot tools"+ aria-expanded={toolsOpen}+ onClick={() => setToolsOpen(true)}+ className="flex min-h-10 w-full items-center gap-3 rounded-lg border border-border bg-muted/20 px-3 text-left outline-none transition-colors hover:bg-muted/40 focus-visible:ring-2 focus-visible:ring-ring"+ >+ <AppIcon className="size-4 shrink-0 text-muted-foreground" icon={WrenchIcon} />+ <span className="min-w-0 flex-1 text-sm">+ {tools.length === 0+ ? "No workspace tools"+ : `${enabledToolCount} of ${tools.length} enabled`}+ </span>+ <span className="text-xs text-muted-foreground">Manage</span>+ </button>+ </div>+ </div>++ <div className="mt-7 flex items-center justify-end gap-3">+ {saved ? <span className="mr-auto text-xs text-success">Saved</span> : null}+ <Button+ size="sm"+ disabled={saving || !dirty || !name.trim() || !onSave}+ onClick={() => {+ if (!onSave) return;+ setSaving(true);+ void onSave({+ name: name.trim(),+ label: normalizedLabel,+ description: normalizedDescription,+ engine: nextEngine,+ sandbox: nextSandbox,+ disabledMcpServerIds,+ }).then((success) => {+ setSaving(false);+ setSaved(success);+ if (success) setEngineChanged(false);+ });+ }}+ >+ {saving ? "Saving" : "Save"}+ </Button>+ </div>++ <AvatarPickerDialog bot={bot} open={avatarOpen} onOpenChange={setAvatarOpen} />+ <BotToolsSheet+ open={toolsOpen}+ onOpenChange={setToolsOpen}+ servers={mcpServers}+ disabledIds={disabledMcpServerIds}+ onDisabledIdsChange={(ids) => {+ setDisabledMcpServerIds(ids);+ markChanged();+ }}+ />+ </div>+ );+}++export function BotDetailsPanel({+ bot,+ onSaveBot,+}: {+ readonly bot: Bot;+ readonly onSaveBot?: (input: BotProfileUpdate) => Promise<boolean>;+}) {+ const keybindings = useAtomValue(primaryServerKeybindingsAtom);+ const [panelState, dispatchPanel] = useReducer(reduceBotDetailsPanelState, {+ desktopOpen: true,+ mobileOpen: false,+ });+ const shortcutLabel = shortcutLabelForCommand(keybindings, "rightPanel.toggle");++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.defaultPrevented || event.repeat) return;+ if (+ event.target instanceof HTMLElement &&+ event.target.closest("[data-keybinding-capture]")+ ) {+ return;+ }+ if (resolveShortcutCommand(event, keybindings) !== "rightPanel.toggle") return;++ event.preventDefault();+ event.stopPropagation();+ dispatchPanel({+ type: window.matchMedia(RIGHT_PANEL_INLINE_LAYOUT_MEDIA_QUERY).matches+ ? "toggle-mobile"+ : "toggle-desktop",+ });+ };++ window.addEventListener("keydown", onKeyDown, true);+ return () => window.removeEventListener("keydown", onKeyDown, true);+ }, [keybindings]);++ const content = (closeButton?: ReactNode) => (+ <>+ <header className="relative flex h-[var(--workspace-topbar-height)] shrink-0 items-center justify-center px-4">+ <h2 className="text-sm font-medium">Settings</h2>+ <div className="absolute right-3 flex items-center">{closeButton}</div>+ </header>+ <BotProfileEditor bot={bot} {...(onSaveBot ? { onSave: onSaveBot } : {})} />+ </>+ );++ return (+ <>+ <aside+ aria-hidden={!panelState.desktopOpen}+ aria-label={`${bot.name} bot sidebar`}+ data-testid="bot-details-panel"+ className={+ panelState.desktopOpen+ ? "hidden h-full w-88 shrink-0 flex-col border-l border-border bg-background min-[981px]:flex"+ : "hidden"+ }+ >+ {content(+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ aria-expanded="true"+ aria-label={`Collapse ${bot.name} bot sidebar`}+ size="icon-sm"+ variant="ghost"+ onClick={() => dispatchPanel({ type: "toggle-desktop" })}+ >+ <AppIcon icon={PanelRightCloseIcon} />+ </Button>+ }+ />+ <TooltipPopup side="left">+ Collapse{shortcutLabel ? ` (${shortcutLabel})` : ""}+ </TooltipPopup>+ </Tooltip>,+ )}+ </aside>+ {!panelState.desktopOpen ? (+ <div className="fixed right-[var(--workspace-controls-right)] top-[var(--workspace-controls-top)] z-40 hidden h-[var(--workspace-topbar-height)] items-center min-[981px]:flex">+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ aria-expanded="false"+ aria-label={`Open ${bot.name} bot sidebar`}+ size="icon-sm"+ variant="ghost"+ onClick={() => dispatchPanel({ type: "toggle-desktop" })}+ >+ <AppIcon icon={PanelRightIcon} />+ </Button>+ }+ />+ <TooltipPopup side="left">+ Open sidebar{shortcutLabel ? ` (${shortcutLabel})` : ""}+ </TooltipPopup>+ </Tooltip>+ </div>+ ) : null}+ <div className="fixed right-[var(--workspace-controls-right)] top-[var(--workspace-controls-top)] z-40 flex h-[var(--workspace-topbar-height)] items-center min-[981px]:hidden">+ <Button+ aria-label={`Open ${bot.name} bot sidebar`}+ size="icon-sm"+ variant="ghost"+ onClick={() => dispatchPanel({ type: "set-mobile", open: true })}+ >+ <AppIcon icon={PanelRightIcon} />+ </Button>+ </div>+ <Sheet+ open={panelState.mobileOpen}+ onOpenChange={(open) => dispatchPanel({ type: "set-mobile", open })}+ >+ <SheetPopup+ className="w-[min(92vw,24rem)] pb-safe pt-safe p-0"+ showCloseButton={false}+ side="right"+ >+ <SheetTitle className="sr-only">Edit {bot.name}</SheetTitle>+ {content(+ <SheetClose+ aria-label="Close bot sidebar"+ render={<Button size="icon-sm" variant="ghost" />}+ >+ <AppIcon icon={Cancel01Icon} />+ </SheetClose>,+ )}+ </SheetPopup>+ </Sheet>+ </>+ );+}diff --git a/apps/web/src/components/roster/BotModelPicker.test.ts b/apps/web/src/components/roster/BotModelPicker.test.tsnew file mode 100644index 000000000..186dc22a8--- /dev/null+++ b/apps/web/src/components/roster/BotModelPicker.test.ts@@ -0,0 +1,43 @@+import { ProviderDriverKind, ProviderInstanceId, type ServerProvider } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { deriveProviderInstanceEntries } from "../../providerInstances";+import { makeComposerTestProvider } from "../../test/chatComposerProps";+import { buildBotModelChoices } from "./BotModelPicker";++const codex = ProviderInstanceId.make("codex");+const claude = ProviderInstanceId.make("claude-work");++function makeClaudeProvider(): ServerProvider {+ return {+ ...makeComposerTestProvider(),+ instanceId: claude,+ driver: ProviderDriverKind.make("claudeAgent"),+ models: [+ {+ slug: "claude-fable-5",+ name: "Claude Fable 5",+ isCustom: false,+ isDefault: true,+ capabilities: {},+ },+ ],+ };+}++describe("bot model picker", () => {+ it("flattens subscription instances into model choices without provider rows", () => {+ const choices = buildBotModelChoices(+ deriveProviderInstanceEntries([makeComposerTestProvider(), makeClaudeProvider()]),+ new Map([+ [codex, [{ slug: "gpt-5.6", name: "GPT 5.6" }]],+ [claude, [{ slug: "claude-fable-5", name: "Claude Fable 5" }]],+ ]),+ );++ expect(choices).toEqual([+ { instanceId: codex, model: "gpt-5.6", label: "GPT 5.6" },+ { instanceId: claude, model: "claude-fable-5", label: "Claude Fable 5" },+ ]);+ });+});diff --git a/apps/web/src/components/roster/BotModelPicker.tsx b/apps/web/src/components/roster/BotModelPicker.tsxnew file mode 100644index 000000000..719d5a1d5--- /dev/null+++ b/apps/web/src/components/roster/BotModelPicker.tsx@@ -0,0 +1,57 @@+import { type ProviderInstanceId } from "@t3tools/contracts";++import type { ProviderInstanceEntry } from "../../providerInstances";+import { ProviderModelPicker } from "../chat/ProviderModelPicker";+import { getTriggerDisplayModelName, type ModelEsque } from "../chat/providerIconUtils";++export interface BotModelChoice {+ readonly instanceId: ProviderInstanceId;+ readonly model: string;+ readonly label: string;+}++export function buildBotModelChoices(+ instanceEntries: ReadonlyArray<ProviderInstanceEntry>,+ modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>,+): ReadonlyArray<BotModelChoice> {+ return instanceEntries.flatMap((entry) =>+ (modelOptionsByInstance.get(entry.instanceId) ?? []).map((model) => ({+ instanceId: entry.instanceId,+ model: model.slug,+ label: getTriggerDisplayModelName(model),+ })),+ );+}++/** The established T3 model menu, scoped to model selection for one bot. */+export function BotModelPicker({+ activeInstanceId,+ model,+ instanceEntries,+ modelOptionsByInstance,+ disabled = false,+ onChange,+}: {+ readonly activeInstanceId: ProviderInstanceId;+ readonly model: string;+ readonly instanceEntries: ReadonlyArray<ProviderInstanceEntry>;+ readonly modelOptionsByInstance: ReadonlyMap<ProviderInstanceId, ReadonlyArray<ModelEsque>>;+ readonly disabled?: boolean;+ readonly onChange: (instanceId: ProviderInstanceId, model: string) => void;+}) {+ return (+ <ProviderModelPicker+ activeInstanceId={activeInstanceId}+ model={model}+ lockedProvider={null}+ lockedContinuationGroupKey={null}+ instanceEntries={instanceEntries}+ modelOptionsByInstance={modelOptionsByInstance}+ compact+ disabled={disabled}+ triggerAriaLabel="Change model"+ triggerClassName="max-w-52"+ onInstanceModelChange={onChange}+ />+ );+}diff --git a/apps/web/src/components/roster/BotPromptComposer.test.tsx b/apps/web/src/components/roster/BotPromptComposer.test.tsxnew file mode 100644index 000000000..b1d0d7294--- /dev/null+++ b/apps/web/src/components/roster/BotPromptComposer.test.tsx@@ -0,0 +1,85 @@+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vite-plus/test";++import { deriveProviderInstanceEntries } from "../../providerInstances";+import { composerTestInstanceId, makeComposerTestProvider } from "../../test/chatComposerProps";+import {+ BotPromptComposer,+ findMentionedBotId,+ isBotPromptExpanded,+ shouldFocusBotPromptForKey,+} from "./BotPromptComposer";++describe("bot prompt composer", () => {+ it("expands for long or multiline prompts", () => {+ expect(isBotPromptExpanded("Short prompt")).toBe(false);+ expect(isBotPromptExpanded("Line one\nLine two")).toBe(true);+ expect(isBotPromptExpanded("x".repeat(81))).toBe(true);+ });++ it("routes the latest complete group mention to its bot", () => {+ expect(+ findMentionedBotId("Ask @Mori then @Path Finder ", [+ { id: "mori", name: "Mori" },+ { id: "pathfinder", name: "Path Finder" },+ ]),+ ).toBe("pathfinder");+ expect(findMentionedBotId("Email [email protected]", [{ id: "mori", name: "Mori" }])).toBeUndefined();+ });++ it("focuses the prompt for unmodified printable typing outside an editor", () => {+ const baseInput = {+ altKey: false,+ ctrlKey: false,+ defaultPrevented: false,+ editableTarget: false,+ isComposing: false,+ key: "a",+ metaKey: false,+ };++ expect(shouldFocusBotPromptForKey(baseInput)).toBe(true);+ expect(shouldFocusBotPromptForKey({ ...baseInput, key: "Enter" })).toBe(false);+ expect(shouldFocusBotPromptForKey({ ...baseInput, metaKey: true })).toBe(false);+ expect(shouldFocusBotPromptForKey({ ...baseInput, editableTarget: true })).toBe(false);+ expect(shouldFocusBotPromptForKey({ ...baseInput, isComposing: true })).toBe(false);+ });++ it("uses the available chat width", () => {+ const markup = renderToStaticMarkup(+ <BotPromptComposer+ botName="Akeru"+ disabled={false}+ modelPicker={null}+ onSubmit={vi.fn(async () => true)}+ />,+ );++ expect(markup).toContain('<form class="w-full ');+ expect(markup).not.toContain("max-w-4xl");+ });++ it("shows the active model and keeps it changeable", () => {+ const instanceEntries = deriveProviderInstanceEntries([makeComposerTestProvider()]);+ const markup = renderToStaticMarkup(+ <BotPromptComposer+ botName="Akeru"+ disabled={false}+ modelPicker={{+ activeInstanceId: composerTestInstanceId,+ model: "gpt-5-codex",+ instanceEntries,+ modelOptionsByInstance: new Map([+ [composerTestInstanceId, [{ slug: "gpt-5-codex", name: "Launchbar Model" }]],+ ]),+ onChange: vi.fn(),+ }}+ onSubmit={vi.fn(async () => true)}+ />,+ );++ expect(markup).toContain("Launchbar Model");+ expect(markup).toContain('aria-label="Change model"');+ expect(markup).toContain("data-chat-provider-model-picker");+ });+});diff --git a/apps/web/src/components/roster/BotPromptComposer.tsx b/apps/web/src/components/roster/BotPromptComposer.tsxnew file mode 100644index 000000000..558fc60a3--- /dev/null+++ b/apps/web/src/components/roster/BotPromptComposer.tsx@@ -0,0 +1,267 @@+import { ArrowUpIcon, AtSignIcon, PaperclipIcon, PlusIcon, XIcon } from "lucide-react";+import { type ComponentProps, useEffect, useRef, useState } from "react";++import { cn } from "../../lib/utils";+import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";+import { clearBotDraft, readBotDraft, writeBotDraft } from "./botDraftStore";+import { BotModelPicker } from "./BotModelPicker";++type BotModelPickerProps = Pick<+ ComponentProps<typeof BotModelPicker>,+ "activeInstanceId" | "model" | "instanceEntries" | "modelOptionsByInstance" | "onChange"+>;++export function isBotPromptExpanded(prompt: string): boolean {+ return prompt.includes("\n") || prompt.length > 80;+}++export function shouldFocusBotPromptForKey(input: {+ readonly altKey: boolean;+ readonly ctrlKey: boolean;+ readonly defaultPrevented: boolean;+ readonly editableTarget: boolean;+ readonly isComposing: boolean;+ readonly key: string;+ readonly metaKey: boolean;+}): boolean {+ return (+ !input.altKey &&+ !input.ctrlKey &&+ !input.defaultPrevented &&+ !input.editableTarget &&+ !input.isComposing &&+ !input.metaKey &&+ input.key.length === 1+ );+}++export interface MentionBot {+ readonly id: string;+ readonly name: string;+}++const EMPTY_MENTION_BOTS: ReadonlyArray<MentionBot> = [];++export function findMentionedBotId(+ prompt: string,+ bots: ReadonlyArray<MentionBot>,+): string | undefined {+ const mentions = bots.flatMap((bot) => {+ const token = `@${bot.name}`;+ const index = prompt.lastIndexOf(token);+ if (index < 0) return [];+ const before = prompt[index - 1];+ const after = prompt[index + token.length];+ return (before === undefined || /\s/.test(before)) && (after === undefined || /\s/.test(after))+ ? [{ id: bot.id, index }]+ : [];+ });+ return mentions.toSorted((left, right) => right.index - left.index)[0]?.id;+}++export function BotPromptComposer({+ botName,+ draftKey,+ disabled,+ mentionBots = EMPTY_MENTION_BOTS,+ modelPicker,+ onSubmit,+}: {+ botName: string;+ draftKey?: string;+ disabled: boolean;+ mentionBots?: ReadonlyArray<MentionBot>;+ modelPicker: BotModelPickerProps | null;+ onSubmit: (prompt: string, files: readonly File[], respondingBotId?: string) => Promise<boolean>;+}) {+ const [draft, setDraft] = useState(() => (draftKey ? readBotDraft(draftKey) : ""));+ const [files, setFiles] = useState<File[]>([]);+ const fileInputRef = useRef<HTMLInputElement>(null);+ const promptInputRef = useRef<HTMLTextAreaElement>(null);+ const persistDraft = (next: string) => {+ setDraft(next);+ if (draftKey) writeBotDraft(draftKey, next);+ };+ const persistDraftRef = useRef(persistDraft);+ persistDraftRef.current = persistDraft;++ useEffect(() => {+ setDraft(draftKey ? readBotDraft(draftKey) : "");+ }, [draftKey]);+ const expanded = modelPicker !== null || files.length > 0 || isBotPromptExpanded(draft);+ const addFiles = (next: FileList | readonly File[]) =>+ setFiles((current) => [...current, ...Array.from(next)]);++ useEffect(() => {+ const onKeyDown = (event: KeyboardEvent) => {+ const target = event.target;+ const editableTarget =+ target instanceof Element &&+ target.closest(+ 'input, textarea, select, [contenteditable]:not([contenteditable="false"]), [role="textbox"], [role="combobox"]',+ ) !== null;++ if (+ !shouldFocusBotPromptForKey({+ altKey: event.altKey,+ ctrlKey: event.ctrlKey,+ defaultPrevented: event.defaultPrevented,+ editableTarget,+ isComposing: event.isComposing,+ key: event.key,+ metaKey: event.metaKey,+ })+ ) {+ return;+ }++ event.preventDefault();+ persistDraftRef.current(`${promptInputRef.current?.value ?? ""}${event.key}`);+ promptInputRef.current?.focus();+ };++ window.addEventListener("keydown", onKeyDown);+ return () => window.removeEventListener("keydown", onKeyDown);+ }, []);++ return (+ <form+ className="w-full px-4 pb-4 pt-2 sm:px-6 sm:pb-6"+ onSubmit={(event) => {+ event.preventDefault();+ const prompt = draft.trim();+ void onSubmit(prompt, files, findMentionedBotId(prompt, mentionBots)).then((sent) => {+ if (sent) {+ persistDraft("");+ if (draftKey) clearBotDraft(draftKey);+ setFiles([]);+ }+ });+ }}+ >+ <div+ data-testid="bot-prompt-composer"+ data-expanded={expanded || undefined}+ className={cn(+ "relative flex min-h-13 flex-col overflow-hidden rounded-[1.65rem] border border-white/10 bg-foreground/[0.12] shadow-[0_12px_36px_-24px_rgb(0_0_0/80%)] transition-[min-height,border-radius,background-color,box-shadow] duration-200 ease-out dark:bg-white/[0.16]",+ expanded && "min-h-28",+ )}+ >+ {files.length > 0 ? (+ <div className="flex flex-wrap gap-1.5 px-3 pt-3">+ {files.map((file, index) => (+ <span+ key={`${file.name}:${file.size}:${file.lastModified}`}+ className="flex max-w-48 items-center gap-1.5 rounded-full bg-background/65 py-1 pe-1 ps-2.5 text-xs"+ >+ <PaperclipIcon className="size-3" />+ <span className="truncate">{file.name}</span>+ <button+ type="button"+ aria-label={`Remove ${file.name}`}+ onClick={() => setFiles((current) => current.filter((_, item) => item !== index))}+ className="flex size-5 items-center justify-center rounded-full text-muted-foreground hover:bg-foreground/10"+ >+ <XIcon className="size-3" />+ </button>+ </span>+ ))}+ </div>+ ) : null}+ <textarea+ ref={promptInputRef}+ aria-label={`Message ${botName}`}+ data-testid="bot-prompt-input"+ placeholder={`Message ${botName}`}+ rows={1}+ value={draft}+ className={cn(+ "field-sizing-content max-h-56 w-full resize-none bg-transparent text-[15px] leading-6 outline-none placeholder:text-muted-foreground/70",+ expanded ? "min-h-16 px-4 pb-2 pt-3" : "min-h-13 px-14 py-[0.9rem]",+ )}+ onChange={(event) => persistDraft(event.currentTarget.value)}+ onKeyDown={(event) => {+ if (event.key === "Enter" && !event.shiftKey && !event.nativeEvent.isComposing) {+ event.preventDefault();+ event.currentTarget.form?.requestSubmit();+ }+ }}+ onPaste={(event) => {+ if (event.clipboardData.files.length > 0) addFiles(event.clipboardData.files);+ }}+ />+ <div+ data-testid="bot-prompt-controls"+ className={cn(+ "pointer-events-none flex items-center justify-between",+ expanded ? "px-2 pb-2" : "absolute inset-x-2 bottom-2",+ )}+ >+ <div className="pointer-events-auto flex min-w-0 items-center gap-1">+ <Menu>+ <MenuTrigger+ render={+ <button+ type="button"+ aria-label="Add to prompt"+ className="flex size-9 shrink-0 items-center justify-center rounded-full bg-foreground/8"+ />+ }+ >+ <PlusIcon className="size-5" />+ </MenuTrigger>+ <MenuPopup align="start" side="top" sideOffset={8}>+ <MenuItem onClick={() => fileInputRef.current?.click()}>+ <PaperclipIcon />+ Attach image+ </MenuItem>+ {mentionBots.map((bot) => (+ <MenuItem+ key={bot.id}+ onClick={() =>+ setDraft(+ (current) =>+ `${current}${current && !/\s$/.test(current) ? " " : ""}@${bot.name} `,+ )+ }+ >+ <AtSignIcon />+ Mention {bot.name}+ </MenuItem>+ ))}+ </MenuPopup>+ </Menu>+ {modelPicker ? (+ <BotModelPicker+ activeInstanceId={modelPicker.activeInstanceId}+ model={modelPicker.model}+ instanceEntries={modelPicker.instanceEntries}+ modelOptionsByInstance={modelPicker.modelOptionsByInstance}+ onChange={modelPicker.onChange}+ />+ ) : null}+ </div>+ <button+ type="submit"+ aria-label="Send message"+ disabled={disabled || (draft.trim().length === 0 && files.length === 0)}+ className="pointer-events-auto flex size-9 items-center justify-center rounded-full bg-foreground text-background disabled:opacity-25"+ >+ <ArrowUpIcon className="size-5" />+ </button>+ </div>+ </div>+ <input+ ref={fileInputRef}+ type="file"+ accept="image/*"+ multiple+ className="sr-only"+ onChange={(event) => {+ if (event.currentTarget.files) addFiles(event.currentTarget.files);+ event.currentTarget.value = "";+ }}+ />+ </form>+ );+}diff --git a/apps/web/src/components/roster/BotRosterSidebar.tsx b/apps/web/src/components/roster/BotRosterSidebar.tsxnew file mode 100644index 000000000..79ad73c7f--- /dev/null+++ b/apps/web/src/components/roster/BotRosterSidebar.tsx@@ -0,0 +1,657 @@+import {+ DndContext,+ DragOverlay,+ PointerSensor,+ closestCenter,+ useDroppable,+ useSensor,+ useSensors,+ type DragEndEvent,+ type DragOverEvent,+ type DragStartEvent,+} from "@dnd-kit/core";+import { restrictToFirstScrollableAncestor, snapCenterToCursor } from "@dnd-kit/modifiers";+import {+ SortableContext,+ rectSortingStrategy,+ useSortable,+ verticalListSortingStrategy,+} from "@dnd-kit/sortable";+import { CSS } from "@dnd-kit/utilities";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { BotId, EnvironmentId, ThreadId } from "@t3tools/contracts";+import { Link, useLocation, useNavigate } from "@tanstack/react-router";+import { PlusIcon, SearchIcon } from "lucide-react";+import { memo, useEffect, useMemo, useRef, useState, type ReactNode } from "react";+import { useShallow } from "zustand/react/shallow";++import { isElectron } from "../../env";+import { useClientSettings } from "../../hooks/useSettings";+import { cn, randomUUID } from "../../lib/utils";+import { botEnvironment } from "../../state/bots";+import { useThreadMessages, useThreadShells } from "../../state/entities";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { useAtomCommand } from "../../state/use-atom-command";+import { SidebarChromeFooter } from "../sidebar/SidebarChrome";+import { Button } from "../ui/button";+import { SidebarContent, SidebarGroup, SidebarHeader, SidebarTrigger } from "../ui/sidebar";+import { toastManager } from "../ui/toast";+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";+import { BotAvatarView } from "./BotAvatarView";+import { visibleBotChatMessages } from "./botConversationPresentation";+import { useBotPresence } from "./botPresence";+import { findLatestBotThreadTarget } from "./botThreadRuntime.logic";+import { NewBotDialog } from "./NewBotDialog";+import {+ buildGroupedRosterSections,+ buildRosterStrip,+ filterRosterBots,+ formatRosterTimestamp,+ isRecordableChatPath,+ parseChatPath,+ resolveLatestRosterMessage,+ resolveRosterIndicator,+ type RosterLastMessage,+ type RosterPresence,+} from "./roster.logic";+import { moveRosterBot, useRosterStore } from "./rosterStore";+import type { Bot, BotAvatar } from "./types";+import { useServerRosterSync } from "./useServerRoster";++/** Avatar with a yellow needs-you light and a green working light. */+function RosterAvatar({+ bot,+ presence,+ className,+ dotClassName,+}: {+ bot: Bot;+ presence: RosterPresence;+ className: string;+ dotClassName?: string;+}) {+ const indicator = resolveRosterIndicator(presence);+ return (+ <span className="relative shrink-0">+ <BotAvatarView avatar={bot.avatar} name={bot.name} state={presence} className={className} />+ {indicator !== null ? (+ <span+ data-testid="bot-presence-dot"+ data-status={indicator}+ className={cn(+ "absolute -bottom-px -right-px rounded-full ring-1 ring-sidebar",+ indicator === "working" ? "bg-success" : "bg-warning",+ dotClassName ?? "size-2",+ )}+ />+ ) : null}+ </span>+ );+}++/**+ * Minimal roster chrome: traffic-light drag space, an optional environment+ * pill, and the new-bot button. No brand row and no stage artwork. The+ * fixed SidebarControl trigger overlays the left edge on desktop, so content+ * starts at the titlebar inset. Icon-collapsed mode empties the row and the+ * rail supplies its own new-bot button.+ */+const RosterSidebarHeader = memo(function RosterSidebarHeader({+ onNewBot,+}: {+ onNewBot: () => void;+}) {+ return (+ <SidebarHeader+ className={cn(+ "h-[var(--workspace-topbar-height)] shrink-0 flex-row items-center gap-1 px-3 py-0 md:px-2",+ isElectron && "drag-region",+ )}+ >+ <div className="grid min-w-0 flex-1 grid-cols-[1fr_auto_1fr] items-center group-data-[collapsible=icon]:hidden">+ <div className="flex items-center justify-start">+ <SidebarTrigger className="md:hidden" />+ </div>+ <Link+ to="/"+ className="flex items-center justify-center rounded-md text-sidebar-foreground outline-none ring-ring focus-visible:ring-2 [-webkit-app-region:no-drag]"+ >+ <span className="truncate text-xl leading-none tracking-tight [font-family:var(--font-brand-serif)]">+ akeru+ </span>+ </Link>+ <div className="flex items-center justify-end">+ <Tooltip>+ <TooltipTrigger+ render={+ <Button+ aria-label="New bot"+ data-testid="roster-new-bot"+ className="size-[var(--workspace-titlebar-control-size)]! [-webkit-app-region:no-drag]"+ onClick={onNewBot}+ size="icon"+ variant="ghost"+ >+ <PlusIcon />+ </Button>+ }+ />+ <TooltipPopup side="bottom">New bot</TooltipPopup>+ </Tooltip>+ </div>+ </div>+ </SidebarHeader>+ );+});++const BotStripTile = memo(function BotStripTile({+ bot,+ isActive,+ onSelect,+}: {+ bot: Bot;+ isActive: boolean;+ onSelect: (bot: Bot) => void;+}) {+ const presence = useBotPresence(bot.id);+ const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: bot.id });+ return (+ <li+ ref={setNodeRef}+ className={cn("list-none touch-pan-y", isDragging && "opacity-0")}+ style={{ transform: CSS.Transform.toString(transform), transition }}+ {...listeners}+ >+ <button+ type="button"+ data-testid="roster-strip-tile"+ data-bot-hover+ aria-current={isActive || undefined}+ onClick={() => onSelect(bot)}+ className={cn(+ "flex w-20 cursor-grab flex-col items-center gap-2 rounded-xl px-1 pb-2 pt-3 outline-none select-none focus-visible:ring-2 focus-visible:ring-ring active:cursor-grabbing",+ isActive ? "bg-sidebar-row-active" : "bg-transparent hover:bg-sidebar-row-hover",+ )}+ >+ <RosterAvatar bot={bot} presence={presence} className="size-14" />+ <span className="w-full truncate text-center text-xs text-sidebar-foreground">+ {bot.name}+ </span>+ </button>+ </li>+ );+});++function useLatestBotMessage(+ botId: string,+ fallback: RosterLastMessage | null,+ working: boolean,+): RosterLastMessage | null {+ const rememberedPath = useRosterStore((state) => state.chatPathByBotId[botId]);+ const environmentId = usePrimaryEnvironmentId();+ const threadShells = useThreadShells();+ const threadRef = useMemo(() => {+ const durableTarget = environmentId+ ? findLatestBotThreadTarget(botId, environmentId, threadShells)+ : null;+ const target = durableTarget ?? (rememberedPath ? parseChatPath(rememberedPath) : null);+ return target+ ? scopeThreadRef(EnvironmentId.make(target.environmentId), ThreadId.make(target.threadId))+ : null;+ }, [botId, environmentId, rememberedPath, threadShells]);+ const messages = useThreadMessages(threadRef);+ const visibleMessages = useMemo(+ () => visibleBotChatMessages(messages, working),+ [messages, working],+ );+ return useMemo(+ () => resolveLatestRosterMessage(fallback, visibleMessages),+ [fallback, visibleMessages],+ );+}++const BotRosterRow = memo(function BotRosterRow({+ bot,+ lastMessage,+ isActive,+ onSelect,+}: {+ bot: Bot;+ lastMessage: RosterLastMessage | null;+ isActive: boolean;+ onSelect: (bot: Bot) => void;+}) {+ const timestampFormat = useClientSettings((s) => s.timestampFormat);+ const presence = useBotPresence(bot.id);+ const latestMessage = useLatestBotMessage(bot.id, lastMessage, presence === "working");+ const { listeners, setNodeRef, transform, transition, isDragging } = useSortable({ id: bot.id });+ return (+ <li+ ref={setNodeRef}+ className={cn("list-none touch-pan-y", isDragging && "opacity-0")}+ style={{ transform: CSS.Transform.toString(transform), transition }}+ {...listeners}+ >+ <div+ data-testid="roster-bot-row"+ data-bot-hover+ className={cn(+ "flex w-full items-center rounded-lg outline-none select-none",+ isActive+ ? "bg-sidebar-row-active text-sidebar-foreground"+ : "bg-transparent text-sidebar-foreground hover:bg-sidebar-row-hover",+ )}+ >+ <button+ type="button"+ aria-current={isActive || undefined}+ onClick={() => onSelect(bot)}+ className="flex min-w-0 flex-1 cursor-pointer items-center gap-2.5 rounded-lg px-2 py-1.5 text-left outline-none focus-visible:ring-2 focus-visible:ring-ring"+ >+ <RosterAvatar bot={bot} presence={presence} className="size-10" />+ <span className="flex min-w-0 flex-1 flex-col">+ <span className="flex items-baseline gap-2">+ <span className="min-w-0 flex-1 truncate text-sm font-semibold">{bot.name}</span>+ {latestMessage ? (+ <span className="shrink-0 text-xs tabular-nums text-sidebar-muted-foreground">+ {formatRosterTimestamp(latestMessage.at, timestampFormat)}+ </span>+ ) : null}+ </span>+ {latestMessage ? (+ <span className="truncate text-[13px] text-sidebar-muted-foreground">+ {latestMessage.text}+ </span>+ ) : null}+ </span>+ </button>+ </div>+ </li>+ );+});++/** One avatar in the icon-collapsed rail, with a name tooltip. */+function RailBotButton({+ bot,+ isActive,+ onSelect,+}: {+ bot: Bot;+ isActive: boolean;+ onSelect: (bot: Bot) => void;+}) {+ const presence = useBotPresence(bot.id);+ return (+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ data-bot-hover+ aria-current={isActive || undefined}+ onClick={() => onSelect(bot)}+ className={cn(+ "flex size-9 cursor-pointer items-center justify-center rounded-lg outline-none select-none focus-visible:ring-2 focus-visible:ring-ring",+ isActive ? "bg-sidebar-row-active" : "bg-transparent hover:bg-sidebar-row-hover",+ )}+ >+ <RosterAvatar+ bot={bot}+ presence={presence}+ className="size-7"+ dotClassName="size-1.5"+ />+ </button>+ }+ />+ <TooltipPopup side="right">{bot.name}</TooltipPopup>+ </Tooltip>+ );+}++function RosterDropZone({+ id,+ className,+ children,+}: {+ id: "pinned-zone" | "unpinned-zone";+ className?: string;+ children: ReactNode;+}) {+ const { isOver, setNodeRef } = useDroppable({ id });+ return (+ <div+ ref={setNodeRef}+ data-drop-zone={id}+ data-drag-over={isOver || undefined}+ className={className}+ >+ {children}+ </div>+ );+}++function BotDragOverlay({ bot }: { bot: Bot }) {+ const presence = useBotPresence(bot.id);+ return (+ <div className="flex w-20 cursor-grabbing flex-col items-center gap-2 rounded-xl bg-sidebar-row-hover px-1 pb-2 pt-3 text-sidebar-foreground shadow-xl select-none">+ <RosterAvatar bot={bot} presence={presence} className="size-14" />+ <span className="w-full truncate text-center text-xs">{bot.name}</span>+ </div>+ );+}++export default function BotRosterSidebar() {+ useServerRosterSync();+ const navigate = useNavigate();+ const environmentId = usePrimaryEnvironmentId();+ const createBotCommand = useAtomCommand(botEnvironment.create, { reportFailure: false });+ const pathname = useLocation({ select: (location) => location.pathname });+ const { bots, groups, lastMessageByBotId, selectedBotId } = useRosterStore(+ useShallow((state) => ({+ bots: state.bots,+ groups: state.groups,+ lastMessageByBotId: state.lastMessageByBotId,+ selectedBotId: state.selectedBotId,+ })),+ );+ const [query, setQuery] = useState("");+ const [dragLayout, setDragLayout] = useState<Bot[] | null>(null);+ const dragLayoutRef = useRef<Bot[] | null>(null);+ const [activeBotId, setActiveBotId] = useState<string | null>(null);+ const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 6 } }));++ const strip = useMemo(+ () => buildRosterStrip(bots, lastMessageByBotId),+ [bots, lastMessageByBotId],+ );+ const visibleBots = useMemo(+ () => filterRosterBots(dragLayout ?? bots, query).filter((bot) => bot.archivedAt === null),+ [bots, dragLayout, query],+ );+ const pinnedBots = visibleBots.filter((bot) => bot.pinned);+ const unpinnedBots = visibleBots.filter((bot) => !bot.pinned);+ const groupSections = useMemo(+ () => buildGroupedRosterSections(visibleBots, groups),+ [groups, visibleBots],+ );+ const activeBot =+ activeBotId === null+ ? null+ : ((dragLayout ?? bots).find((bot) => bot.id === activeBotId) ?? null);++ const resolveDrop = (layout: readonly Bot[], overId: string) => {+ if (overId === "pinned-zone") return { overBotId: null, pinned: true } as const;+ if (overId === "unpinned-zone") return { overBotId: null, pinned: false } as const;+ const overBot = layout.find((bot) => bot.id === overId);+ return overBot ? { overBotId: overBot.id, pinned: overBot.pinned } : null;+ };+ const handleDragStart = ({ active }: DragStartEvent) => {+ dragLayoutRef.current = bots;+ setActiveBotId(String(active.id));+ setDragLayout(bots);+ };+ const handleDragOver = ({ active, over }: DragOverEvent) => {+ if (!over) return;+ setDragLayout((current) => {+ const layout = current ?? bots;+ const drop = resolveDrop(layout, String(over.id));+ if (!drop) return layout;+ const next = moveRosterBot(layout, String(active.id), drop.overBotId, drop.pinned) ?? layout;+ dragLayoutRef.current = next;+ return next;+ });+ };+ const finishDrag = () => {+ dragLayoutRef.current = null;+ setActiveBotId(null);+ setDragLayout(null);+ };+ const handleDragEnd = ({ over }: DragEndEvent) => {+ if (over && dragLayoutRef.current) {+ useRosterStore.getState().commitBotLayout(dragLayoutRef.current);+ }+ finishDrag();+ };++ // Remember the chat route the selected bot lands on, so re-selecting the+ // bot returns to its conversation. The first run after a selection change+ // is skipped: the route still belongs to the previously selected bot.+ const lastSelectedBotIdRef = useRef<string | null>(selectedBotId);+ const pendingClickedBotIdRef = useRef<string | null>(null);+ useEffect(() => {+ const selectionChanged = lastSelectedBotIdRef.current !== selectedBotId;+ const selectionCameFromClick = pendingClickedBotIdRef.current === selectedBotId;+ lastSelectedBotIdRef.current = selectedBotId;+ if (selectionCameFromClick) pendingClickedBotIdRef.current = null;+ if ((selectionChanged && selectionCameFromClick) || selectedBotId === null) return;+ if (!isRecordableChatPath(pathname)) return;+ useRosterStore.getState().recordChatPath(selectedBotId, pathname);+ }, [pathname, selectedBotId]);++ const handleSelect = (bot: Bot) => {+ pendingClickedBotIdRef.current = bot.id;+ useRosterStore.getState().selectBot(bot.id);+ void navigate({ to: "/bots/$botId", params: { botId: bot.id } });+ };++ const [newBotOpen, setNewBotOpen] = useState(false);+ const [pendingCreatedBotId, setPendingCreatedBotId] = useState<string | null>(null);+ const handleNewBot = () => setNewBotOpen(true);+ const handleCreateBot = async ({ name, avatar }: { name: string; avatar: BotAvatar }) => {+ if (environmentId === null) {+ toastManager.add({ type: "error", title: "Connect an environment first" });+ return;+ }+ const botId = BotId.make(`bot-${randomUUID()}`);+ const result = await createBotCommand({+ environmentId,+ input: {+ botId,+ name: name.trim(),+ title: "Assistant",+ label: null,+ description: null,+ avatar,+ engine: null,+ sandbox: null,+ runtimeMode: "full-access",+ usageCap: null,+ groupId: null,+ },+ });+ if (result._tag === "Failure") {+ toastManager.add({ type: "error", title: "Could not create bot" });+ return;+ }+ setNewBotOpen(false);+ setPendingCreatedBotId(botId);+ };++ useEffect(() => {+ if (pendingCreatedBotId === null) return;+ const bot = bots.find((candidate) => candidate.id === pendingCreatedBotId);+ if (!bot) return;+ const store = useRosterStore.getState();+ store.selectBot(bot.id);+ setPendingCreatedBotId(null);+ void navigate({ to: "/", replace: true });+ }, [bots, navigate, pendingCreatedBotId]);++ return (+ <>+ <RosterSidebarHeader onNewBot={handleNewBot} />+ <SidebarContent+ className="gap-0"+ fixedHeader={+ <SidebarGroup className="px-[var(--sidebar-content-inset)] pb-1 pt-1 group-data-[collapsible=icon]:hidden">+ <label className="flex h-9 items-center gap-2 rounded-lg bg-sidebar-row-hover px-2.5 ring-ring focus-within:ring-2">+ <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground" />+ <input+ type="text"+ data-testid="roster-search-input"+ placeholder="Search"+ value={query}+ onChange={(event) => setQuery(event.target.value)}+ onKeyDown={(event) => {+ if (event.key === "Escape" && query.length > 0) {+ event.stopPropagation();+ setQuery("");+ }+ }}+ className="min-w-0 flex-1 bg-transparent text-sm text-sidebar-foreground outline-none placeholder:text-sidebar-muted-foreground"+ />+ </label>+ </SidebarGroup>+ }+ >+ {bots.every((bot) => bot.archivedAt !== null) ? (+ <div className="px-2 py-6 text-center text-sm text-sidebar-muted-foreground">+ No bots yet+ </div>+ ) : (+ <>+ {/* Icon-collapsed rail: every visible bot, recency order. */}+ <SidebarGroup className="hidden items-center gap-1 px-0 pt-1 group-data-[collapsible=icon]:flex">+ <ul data-testid="roster-rail" className="flex flex-col items-center gap-1">+ {strip.map((bot) => (+ <li key={bot.id} className="list-none">+ <RailBotButton+ bot={bot}+ isActive={selectedBotId === bot.id}+ onSelect={handleSelect}+ />+ </li>+ ))}+ </ul>+ </SidebarGroup>+ <DndContext+ collisionDetection={closestCenter}+ sensors={sensors}+ modifiers={[restrictToFirstScrollableAncestor]}+ onDragStart={handleDragStart}+ onDragOver={handleDragOver}+ onDragCancel={finishDrag}+ onDragEnd={handleDragEnd}+ >+ {pinnedBots.length > 0 || activeBotId !== null ? (+ <SidebarGroup className="px-4 pb-3 pt-2 group-data-[collapsible=icon]:hidden">+ <RosterDropZone+ id="pinned-zone"+ className="min-h-24 rounded-xl transition-colors data-[drag-over=true]:bg-sidebar-row-hover"+ >+ <SortableContext+ items={pinnedBots.map((bot) => bot.id)}+ strategy={rectSortingStrategy}+ >+ <ul+ data-testid="roster-strip"+ className={cn(+ "grid min-h-24 place-items-center gap-x-1 gap-y-2",+ pinnedBots.length === 1 ? "grid-cols-1" : "grid-cols-3",+ )}+ >+ {pinnedBots.map((bot) => (+ <BotStripTile+ key={bot.id}+ bot={bot}+ isActive={selectedBotId === bot.id}+ onSelect={handleSelect}+ />+ ))}+ </ul>+ </SortableContext>+ </RosterDropZone>+ </SidebarGroup>+ ) : null}+ <SidebarGroup className="px-[var(--sidebar-content-inset)] pb-1 pt-1 group-data-[collapsible=icon]:hidden">+ <RosterDropZone+ id="unpinned-zone"+ className="min-h-12 rounded-lg transition-colors data-[drag-over=true]:bg-sidebar-row-hover"+ >+ <SortableContext+ items={unpinnedBots.map((bot) => bot.id)}+ strategy={verticalListSortingStrategy}+ >+ <div className="flex flex-col gap-2">+ {groupSections.map((section) => (+ <section key={section.id} aria-label={section.name}>+ <div className="mb-0.5 flex items-baseline gap-2 px-2 py-0.5">+ {section.id === "unassigned" ? (+ <span className="text-[13px] font-medium text-sidebar-muted-foreground">+ {section.name}+ </span>+ ) : (+ <button+ type="button"+ aria-current={pathname === `/groups/${section.id}` || undefined}+ className="rounded text-[13px] font-medium text-sidebar-muted-foreground outline-none hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring"+ onClick={() =>+ void navigate({+ to: "/groups/$groupId",+ params: { groupId: section.id },+ })+ }+ >+ {section.name}+ </button>+ )}+ </div>+ <ul className="flex min-h-12 flex-col gap-px">+ {section.bots.map((bot) => (+ <BotRosterRow+ key={bot.id}+ bot={bot}+ lastMessage={lastMessageByBotId[bot.id] ?? null}+ isActive={selectedBotId === bot.id}+ onSelect={handleSelect}+ />+ ))}+ </ul>+ </section>+ ))}+ </div>+ </SortableContext>+ {unpinnedBots.length === 0 && pinnedBots.length === 0 ? (+ <div className="px-2 py-6 text-center text-sm text-sidebar-muted-foreground">+ No bots match+ </div>+ ) : null}+ </RosterDropZone>+ </SidebarGroup>+ <DragOverlay modifiers={[snapCenterToCursor]}>+ {activeBot ? <BotDragOverlay bot={activeBot} /> : null}+ </DragOverlay>+ </DndContext>+ </>+ )}+ </SidebarContent>+ {/* Rail new-bot sits above the footer, like the expanded header's plus. */}+ <div className="hidden shrink-0 flex-col items-center pb-1 group-data-[collapsible=icon]:flex">+ <Tooltip>+ <TooltipTrigger+ render={+ <button+ type="button"+ aria-label="New bot"+ onClick={handleNewBot}+ className="flex size-9 cursor-pointer items-center justify-center rounded-lg text-sidebar-muted-foreground outline-none select-none hover:bg-sidebar-row-hover hover:text-sidebar-foreground focus-visible:ring-2 focus-visible:ring-ring"+ >+ <PlusIcon className="size-4" />+ </button>+ }+ />+ <TooltipPopup side="right">New bot</TooltipPopup>+ </Tooltip>+ </div>+ {newBotOpen ? (+ <NewBotDialog+ open+ onOpenChange={setNewBotOpen}+ onCreate={(input) => void handleCreateBot(input)}+ />+ ) : null}+ <SidebarChromeFooter />+ </>+ );+}diff --git a/apps/web/src/components/roster/BotThreadLanding.markdown.test.ts b/apps/web/src/components/roster/BotThreadLanding.markdown.test.tsnew file mode 100644index 000000000..ef5cc0dd6--- /dev/null+++ b/apps/web/src/components/roster/BotThreadLanding.markdown.test.ts@@ -0,0 +1,31 @@+// @effect-diagnostics nodeBuiltinImport:off - This integration guard reads its sibling source.+import * as NodeFS from "node:fs";++import { describe, expect, it } from "vite-plus/test";++describe("BotThreadLanding message formatting", () => {+ it("renders assistant messages with the shared rich markdown component", () => {+ const source = NodeFS.readFileSync(new URL("./BotThreadLanding.tsx", import.meta.url), "utf8");++ expect(source).toContain('import ChatMarkdown from "../ChatMarkdown"');+ expect(source).toContain("<ChatMarkdown");+ expect(source).toContain("cwd={runtime.defaultProject?.workspaceRoot}");+ expect(source).toContain("threadRef={runtime.linkedThreadRef ?? undefined}");+ });++ it("uses the free-scrolling conversation area instead of end-justified overflow", () => {+ const botSource = NodeFS.readFileSync(+ new URL("./BotThreadLanding.tsx", import.meta.url),+ "utf8",+ );+ const groupSource = NodeFS.readFileSync(+ new URL("./GroupThreadLanding.tsx", import.meta.url),+ "utf8",+ );++ expect(botSource).toContain("<BotConversationScrollArea>");+ expect(groupSource).toContain("<BotConversationScrollArea>");+ expect(botSource).not.toContain("justify-end gap-4");+ expect(groupSource).not.toContain("justify-end gap-4");+ });+});diff --git a/apps/web/src/components/roster/BotThreadLanding.tsx b/apps/web/src/components/roster/BotThreadLanding.tsxnew file mode 100644index 000000000..a3e8b2384--- /dev/null+++ b/apps/web/src/components/roster/BotThreadLanding.tsx@@ -0,0 +1,234 @@+import { useAtomValue } from "@effect/atom-react";+import { BotId, type BotEngine } from "@t3tools/contracts";+import { useNavigate } from "@tanstack/react-router";+import { useEffect, useMemo, useState } from "react";++import { usePrimarySettings } from "../../hooks/useSettings";+import {+ getCustomModelOptionsByInstance,+ resolveAppModelSelectionState,+} from "../../modelSelection";+import {+ applyProviderInstanceSettings,+ deriveProviderInstanceEntries,+ sortProviderInstanceEntries,+} from "../../providerInstances";+import { botEnvironment } from "../../state/bots";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { primaryServerProvidersAtom } from "../../state/server";+import { useAtomCommand } from "../../state/use-atom-command";+import { SidebarInset } from "../ui/sidebar";+import { toastManager } from "../ui/toast";+import ChatMarkdown from "../ChatMarkdown";+import { WorkspacePageHeader } from "../WorkspacePageHeader";+import { BotActivityStatus } from "./BotActivityStatus";+import { BotAvatarView } from "./BotAvatarView";+import { BotConversationScrollArea } from "./BotConversationScrollArea";+import { visibleBotChatMessages } from "./botConversationPresentation";+import { resolveStickyBotEngine } from "./botEngineSelection";+import { BotPromptComposer } from "./BotPromptComposer";+import { useBotPresence } from "./botPresence";+import { useRosterStore } from "./rosterStore";+import { useBotThreadRuntime } from "./useBotThreadRuntime";++export function BotThreadLanding({ botId }: { readonly botId: string }) {+ const navigate = useNavigate();+ const environmentId = usePrimaryEnvironmentId();+ const settings = usePrimarySettings();+ const providers = useAtomValue(primaryServerProvidersAtom);+ const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });+ const bot = useRosterStore((state) => state.bots.find((candidate) => candidate.id === botId));+ const [pendingEngine, setPendingEngine] = useState<BotEngine | null>(null);+ const [modelUpdatePending, setModelUpdatePending] = useState(false);+ const configuredEngine = pendingEngine ?? bot?.engine ?? null;+ const instanceEntries = useMemo(+ () =>+ sortProviderInstanceEntries(+ applyProviderInstanceSettings(deriveProviderInstanceEntries(providers), settings),+ ),+ [providers, settings],+ );+ const defaultSelection = useMemo(+ () => resolveAppModelSelectionState(settings, providers),+ [providers, settings],+ );+ const stickyEngine = useMemo(+ () =>+ resolveStickyBotEngine({+ engine: configuredEngine,+ instanceEntries,+ settings,+ providers,+ defaultSelection,+ }),+ [configuredEngine, defaultSelection, instanceEntries, providers, settings],+ );+ const activeEntry = useMemo(+ () => instanceEntries.find((entry) => entry.instanceId === stickyEngine?.instanceId) ?? null,+ [instanceEntries, stickyEngine?.instanceId],+ );+ const activeModel = stickyEngine?.model ?? null;+ const modelOptionsByInstance = useMemo(+ () => getCustomModelOptionsByInstance(settings, providers),+ [providers, settings],+ );+ const effectiveModelSelection = stickyEngine;+ const runtime = useBotThreadRuntime(botId, effectiveModelSelection);+ const presence = useBotPresence(botId);++ useEffect(() => {+ if (+ pendingEngine &&+ bot?.engine?.provider === pendingEngine.provider &&+ bot.engine.model === pendingEngine.model+ ) {+ setPendingEngine(null);+ }+ }, [bot?.engine, pendingEngine]);++ useEffect(() => {+ if (!bot || bot.archivedAt !== null) {+ void navigate({ to: "/", replace: true });+ return;+ }+ useRosterStore.getState().selectBot(bot.id);+ }, [bot, navigate]);++ if (!bot || bot.archivedAt !== null) return null;+ const working = runtime.sending || presence === "working";+ const messages = visibleBotChatMessages(runtime.messages, working);++ return (+ <SidebarInset+ aria-label={`${bot.name} thread`}+ className="h-dvh min-h-0 overflow-hidden bg-background text-foreground"+ data-testid="bot-thread-landing"+ >+ <div className="flex min-h-0 min-w-0 flex-1">+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">+ <WorkspacePageHeader className="border-b border-border">+ <div className="flex min-w-0 items-center gap-2">+ <BotAvatarView avatar={bot.avatar} name={bot.name} className="size-6" />+ <span className="truncate text-sm font-medium">{bot.name}</span>+ </div>+ </WorkspacePageHeader>+ <BotConversationScrollArea>+ {messages.length === 0 ? (+ <div className="flex flex-1 flex-col items-center justify-center gap-3 py-12">+ <BotAvatarView avatar={bot.avatar} name={bot.name} className="size-14" />+ <h1 className="text-lg font-medium">Message {bot.name}</h1>+ </div>+ ) : (+ messages.map((message) =>+ message.role === "assistant" ? (+ <div+ key={message.id}+ className="flex items-start gap-3"+ data-testid="bot-provider-message"+ >+ <BotAvatarView+ avatar={bot.avatar}+ name={bot.name}+ className="mt-0.5 size-7 shrink-0"+ />+ <div className="min-w-0 max-w-[85%]">+ <div className="text-sm font-medium">{bot.name}</div>+ <ChatMarkdown+ className="mt-1"+ cwd={runtime.defaultProject?.workspaceRoot}+ text={message.text}+ threadRef={runtime.linkedThreadRef ?? undefined}+ />+ </div>+ </div>+ ) : (+ <div key={message.id} className="flex justify-end" data-testid="bot-user-message">+ <div className="max-w-[78%] rounded-2xl bg-foreground/10 px-3.5 py-2 text-sm leading-6">+ <p className="whitespace-pre-wrap">{message.text}</p>+ {message.attachments?.length ? (+ <div className="mt-1.5 flex flex-wrap justify-end gap-1.5">+ {message.attachments.map((attachment) => (+ <span+ key={attachment.id}+ className="rounded-full bg-background/60 px-2 py-0.5 text-xs text-muted-foreground"+ >+ {attachment.name}+ </span>+ ))}+ </div>+ ) : null}+ </div>+ </div>+ ),+ )+ )}+ {working ? <BotActivityStatus avatar={bot.avatar} name={bot.name} /> : null}+ {runtime.error ? (+ <div+ role="alert"+ data-testid="bot-chat-error"+ className="rounded-lg border border-destructive/30 bg-destructive/8 px-3 py-2 text-sm text-destructive"+ >+ {runtime.error}+ </div>+ ) : null}+ </BotConversationScrollArea>+ <BotPromptComposer+ botName={bot.name}+ draftKey={bot.id}+ disabled={+ runtime.sending ||+ modelUpdatePending ||+ effectiveModelSelection === null ||+ !runtime.botReady ||+ !runtime.bootstrapped ||+ runtime.defaultProject === null+ }+ modelPicker={+ environmentId && activeEntry && activeModel+ ? {+ activeInstanceId: activeEntry.instanceId,+ model: activeModel,+ instanceEntries,+ modelOptionsByInstance,+ onChange: (instanceId, model) => {+ const nextEngine = { provider: instanceId, model };+ setPendingEngine(nextEngine);+ setModelUpdatePending(true);+ void updateBot({+ environmentId,+ input: {+ botId: BotId.make(bot.id),+ engine: nextEngine,+ },+ }).then((result) => {+ setModelUpdatePending(false);+ if (result._tag === "Failure") {+ setPendingEngine(null);+ toastManager.add({ type: "error", title: "Could not change model" });+ }+ });+ },+ }+ : null+ }+ onSubmit={runtime.send}+ />+ {effectiveModelSelection === null ? (+ <p className="px-4 pb-3 text-center text-xs text-muted-foreground">+ Enable a provider before you message this bot.+ </p>+ ) : modelUpdatePending ? (+ <p className="px-4 pb-3 text-center text-xs text-muted-foreground">Changing model…</p>+ ) : !runtime.botReady ? (+ <p className="px-4 pb-3 text-center text-xs text-muted-foreground">Connecting bot…</p>+ ) : runtime.bootstrapped && runtime.defaultProject === null ? (+ <p className="px-4 pb-3 text-center text-xs text-muted-foreground">+ Add a project before you message a bot.+ </p>+ ) : null}+ </div>+ </div>+ </SidebarInset>+ );+}diff --git a/apps/web/src/components/roster/BotToolsSheet.test.ts b/apps/web/src/components/roster/BotToolsSheet.test.tsnew file mode 100644index 000000000..eb30e52d9--- /dev/null+++ b/apps/web/src/components/roster/BotToolsSheet.test.ts@@ -0,0 +1,52 @@+import { McpServerId, type McpServer } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import type { PluginDefinition } from "../../../../../plugins";+import { buildBotToolItems, planBotToolToggle } from "./BotToolsSheet";++const installedPlugin: PluginDefinition = {+ id: "exa",+ title: "Exa",+ description: "Search the web.",+ category: "Search",+ logo: { src: "/plugin-logos/exa.svg" },+ kind: "mcp-url",+ authentication: "optional-oauth",+ url: "https://mcp.exa.ai/mcp",+ builtin: true,+};++const globalServer: McpServer = {+ id: McpServerId.make("builtin-exa"),+ name: "Exa",+ transport: "url",+ url: "https://mcp.exa.ai/mcp",+ enabled: true,+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z",+};++describe("bot plugin exclusions", () => {+ it("shows globally installed plugins to every bot by default", () => {+ expect(buildBotToolItems([globalServer], [installedPlugin])).toMatchObject([+ {+ id: "builtin-exa",+ kind: "plugin",+ name: "Exa",+ workspaceEnabled: true,+ },+ ]);+ });++ it("hides workspace-disabled tools from bot overrides", () => {+ expect(buildBotToolItems([{ ...globalServer, enabled: false }], [installedPlugin])).toEqual([]);+ });++ it("stores only per-bot exclusions when a bot disables a plugin", () => {+ const exaId = McpServerId.make("builtin-exa");+ const otherId = McpServerId.make("custom-other");++ expect(planBotToolToggle([], exaId, false)).toEqual([exaId]);+ expect(planBotToolToggle([exaId, otherId], exaId, true)).toEqual([otherId]);+ });+});diff --git a/apps/web/src/components/roster/BotToolsSheet.tsx b/apps/web/src/components/roster/BotToolsSheet.tsxnew file mode 100644index 000000000..fc42e53ba--- /dev/null+++ b/apps/web/src/components/roster/BotToolsSheet.tsx@@ -0,0 +1,264 @@+import type { McpServer, McpServerId } from "@t3tools/contracts";+import { PuzzleIcon, SearchIcon, ServerIcon, XIcon } from "lucide-react";+import { useEffect, useMemo, useState } from "react";+import { createPortal } from "react-dom";++import { loadCatalog, type PluginDefinition } from "../../../../../plugins";+import { findPluginServer, isBuiltinMcpServer } from "../plugins/pluginRegistry";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { Switch } from "../ui/switch";++const CATALOG = loadCatalog();++export interface BotToolItem {+ readonly id: McpServerId;+ readonly kind: "mcp" | "plugin";+ readonly name: string;+ readonly description: string;+ readonly workspaceEnabled: boolean;+ readonly logo?: PluginDefinition["logo"];+}++export function planBotToolToggle(+ disabledIds: readonly McpServerId[],+ id: McpServerId,+ enabled: boolean,+): readonly McpServerId[] {+ const next = new Set(disabledIds);+ if (enabled) next.delete(id);+ else next.add(id);+ return [...next];+}++function mcpDescription(server: McpServer): string {+ return server.transport === "url"+ ? server.url+ : [server.command, ...(server.args ?? [])].join(" ");+}++export function buildBotToolItems(+ servers: readonly McpServer[],+ catalog: readonly PluginDefinition[] = CATALOG,+): readonly BotToolItem[] {+ const plugins = catalog.flatMap((plugin) => {+ const server = findPluginServer(plugin, servers);+ return server?.enabled+ ? [+ {+ id: server.id,+ kind: "plugin" as const,+ name: plugin.title,+ description: plugin.description,+ workspaceEnabled: true,+ logo: plugin.logo,+ },+ ]+ : [];+ });+ const mcpServers = servers+ .filter((server) => server.enabled && !isBuiltinMcpServer(server))+ .map((server) => ({+ id: server.id,+ kind: "mcp" as const,+ name: server.name,+ description: mcpDescription(server),+ workspaceEnabled: true,+ }));+ return [...plugins, ...mcpServers].toSorted(+ (left, right) => left.kind.localeCompare(right.kind) || left.name.localeCompare(right.name),+ );+}++export function isBotToolEnabled(+ item: Pick<BotToolItem, "id" | "workspaceEnabled">,+ disabledIds: readonly McpServerId[],+): boolean {+ return item.workspaceEnabled && !disabledIds.includes(item.id);+}++function ToolRow({+ item,+ enabled,+ onToggle,+}: {+ readonly item: BotToolItem;+ readonly enabled: boolean;+ readonly onToggle: (enabled: boolean) => void;+}) {+ return (+ <div className="flex min-h-14 items-center gap-3 rounded-lg px-2 py-2 hover:bg-muted/40">+ <span className="flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-lg border border-border bg-background text-muted-foreground">+ {item.logo ? (+ <picture>+ {item.logo.darkSrc ? (+ <source media="(prefers-color-scheme: dark)" srcSet={item.logo.darkSrc} />+ ) : null}+ <img src={item.logo.src} alt="" className="size-6 object-contain" />+ </picture>+ ) : (+ <ServerIcon className="size-4" />+ )}+ </span>+ <span className="min-w-0 flex-1">+ <span className="block truncate text-sm font-medium">{item.name}</span>+ <span className="block truncate text-xs text-muted-foreground">+ {item.workspaceEnabled ? item.description : "Disabled for the workspace"}+ </span>+ </span>+ <Switch+ checked={enabled}+ disabled={!item.workspaceEnabled}+ onCheckedChange={(checked) => onToggle(Boolean(checked))}+ aria-label={`${enabled ? "Disable" : "Enable"} ${item.name} for this bot`}+ />+ </div>+ );+}++export function BotToolsSheet({+ open,+ onOpenChange,+ servers,+ disabledIds,+ onDisabledIdsChange,+}: {+ readonly open: boolean;+ readonly onOpenChange: (open: boolean) => void;+ readonly servers: readonly McpServer[];+ readonly disabledIds: readonly McpServerId[];+ readonly onDisabledIdsChange: (ids: readonly McpServerId[]) => void;+}) {+ const [query, setQuery] = useState("");+ const items = useMemo(() => buildBotToolItems(servers), [servers]);++ useEffect(() => {+ if (!open) return;+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") onOpenChange(false);+ };+ window.addEventListener("keydown", onKeyDown);+ return () => window.removeEventListener("keydown", onKeyDown);+ }, [onOpenChange, open]);+ const needle = query.trim().toLowerCase();+ const visible = items.filter(+ (item) =>+ needle.length === 0 ||+ item.name.toLowerCase().includes(needle) ||+ item.description.toLowerCase().includes(needle),+ );+ const plugins = visible.filter((item) => item.kind === "plugin");+ const mcpServers = visible.filter((item) => item.kind === "mcp");+ const workspaceEnabledIds = items.filter((item) => item.workspaceEnabled).map((item) => item.id);++ const toggle = (id: McpServerId, enabled: boolean) => {+ onDisabledIdsChange(planBotToolToggle(disabledIds, id, enabled));+ };++ const section = (title: string, sectionItems: readonly BotToolItem[]) =>+ sectionItems.length > 0 ? (+ <section className="mt-5" aria-label={title}>+ <div className="mb-1 flex items-center gap-2 px-2 text-xs font-medium text-muted-foreground">+ {title === "Plugins" ? (+ <PuzzleIcon className="size-3.5" />+ ) : (+ <ServerIcon className="size-3.5" />+ )}+ {title}+ </div>+ <div className="space-y-0.5">+ {sectionItems.map((item) => (+ <ToolRow+ key={item.id}+ item={item}+ enabled={isBotToolEnabled(item, disabledIds)}+ onToggle={(enabled) => toggle(item.id, enabled)}+ />+ ))}+ </div>+ </section>+ ) : null;++ if (!open) return null;++ return createPortal(+ <div className="fixed inset-0 z-[70] flex justify-end" role="presentation">+ <button+ type="button"+ aria-label="Close bot tools"+ className="absolute inset-0 bg-background/60 backdrop-blur-xs"+ onClick={() => onOpenChange(false)}+ />+ <section+ role="dialog"+ aria-modal="true"+ aria-labelledby="bot-tools-title"+ className="pb-safe pt-safe relative flex h-full w-[min(92vw,30rem)] min-h-0 flex-col border-s border-border bg-popover text-popover-foreground shadow-xl"+ >+ <header className="border-b border-border px-5 pb-4 pt-5">+ <div className="flex items-center justify-between gap-3">+ <h2 id="bot-tools-title" className="text-base font-semibold">+ Tools+ </h2>+ <Button+ size="icon-sm"+ variant="ghost"+ aria-label="Close bot tools"+ onClick={() => onOpenChange(false)}+ >+ <XIcon className="size-4" />+ </Button>+ </div>+ <p className="mt-1 text-sm text-muted-foreground">+ Choose which workspace tools this bot can use.+ </p>+ <div className="mt-4 flex items-center gap-2">+ <label className="flex min-w-0 flex-1 items-center gap-2 rounded-lg border border-input bg-background px-2.5 focus-within:ring-2 focus-within:ring-ring">+ <SearchIcon className="size-4 shrink-0 text-muted-foreground" />+ <Input+ value={query}+ onChange={(event) => setQuery(event.currentTarget.value)}+ placeholder="Search tools"+ aria-label="Search bot tools"+ className="border-0 px-0 shadow-none focus-visible:ring-0"+ />+ </label>+ <Button+ size="sm"+ variant="outline"+ onClick={() =>+ onDisabledIdsChange(disabledIds.filter((id) => !workspaceEnabledIds.includes(id)))+ }+ >+ Enable all+ </Button>+ <Button+ size="sm"+ variant="outline"+ onClick={() =>+ onDisabledIdsChange([...new Set([...disabledIds, ...workspaceEnabledIds])])+ }+ >+ Disable all+ </Button>+ </div>+ </header>+ <div className="min-h-0 flex-1 overflow-y-auto px-3 pb-6">+ {visible.length === 0 ? (+ <p className="px-2 py-10 text-center text-sm text-muted-foreground">+ {items.length === 0+ ? "No workspace tools are installed."+ : "No tools match your search."}+ </p>+ ) : (+ <>+ {section("Plugins", plugins)}+ {section("MCP servers", mcpServers)}+ </>+ )}+ </div>+ </section>+ </div>,+ document.body,+ );+}diff --git a/apps/web/src/components/roster/GroupThreadLanding.tsx b/apps/web/src/components/roster/GroupThreadLanding.tsxnew file mode 100644index 000000000..022530087--- /dev/null+++ b/apps/web/src/components/roster/GroupThreadLanding.tsx@@ -0,0 +1,133 @@+import { useNavigate } from "@tanstack/react-router";+import { useEffect } from "react";++import { SidebarInset } from "../ui/sidebar";+import { WorkspacePageHeader } from "../WorkspacePageHeader";+import { BotActivityStatus } from "./BotActivityStatus";+import { BotAvatarView } from "./BotAvatarView";+import { BotConversationScrollArea } from "./BotConversationScrollArea";+import { visibleBotChatMessages } from "./botConversationPresentation";+import { BotPromptComposer } from "./BotPromptComposer";+import { useGroupPresence } from "./botPresence";+import { useRosterStore } from "./rosterStore";+import { useGroupThreadRuntime } from "./useGroupThreadRuntime";++export function GroupThreadLanding({ groupId }: { readonly groupId: string }) {+ const navigate = useNavigate();+ const group = useRosterStore((state) =>+ state.groups.find((candidate) => candidate.id === groupId),+ );+ const bots = useRosterStore((state) => state.bots);+ const runtime = useGroupThreadRuntime(groupId);+ const presence = useGroupPresence(groupId);++ useEffect(() => {+ if (!group) void navigate({ to: "/", replace: true });+ }, [group, navigate]);++ if (!group) return null;+ const members = bots.filter((bot) => bot.groupId === group.id && bot.archivedAt === null);+ const boss = members.find((bot) => bot.id === group.bossBotId) ?? members[0];+ if (!boss) return null;+ const working = runtime.sending || presence === "working";+ const messages = visibleBotChatMessages(runtime.messages, working);+ const activeBot = members.find((bot) => bot.id === runtime.respondingBotId) ?? boss;++ return (+ <SidebarInset+ aria-label={`${group.name} group thread`}+ className="h-dvh min-h-0 overflow-hidden bg-background text-foreground"+ data-testid="group-thread-landing"+ >+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">+ <WorkspacePageHeader className="border-b border-border">+ <div className="flex min-w-0 items-center gap-2">+ <div className="flex -space-x-1.5">+ {members.slice(0, 3).map((bot) => (+ <BotAvatarView+ key={bot.id}+ avatar={bot.avatar}+ name={bot.name}+ className="size-6 ring-2 ring-background"+ />+ ))}+ </div>+ <span className="truncate text-sm font-medium">{group.name}</span>+ </div>+ </WorkspacePageHeader>+ <BotConversationScrollArea>+ {messages.length === 0 ? (+ <div className="flex flex-1 flex-col items-center justify-center gap-3 py-12">+ <div className="flex -space-x-3">+ {members.slice(0, 3).map((bot) => (+ <BotAvatarView+ key={bot.id}+ avatar={bot.avatar}+ name={bot.name}+ className="size-14 ring-4 ring-background"+ />+ ))}+ </div>+ <h1 className="text-lg font-medium">Message {group.name}</h1>+ </div>+ ) : (+ messages.map((message) => {+ if (message.role === "assistant") {+ const respondingBot =+ members.find((bot) => bot.id === message.respondingBotId) ?? boss;+ return (+ <div+ key={message.id}+ className="flex items-start gap-3"+ data-testid="group-provider-message"+ >+ <BotAvatarView+ avatar={respondingBot.avatar}+ name={respondingBot.name}+ className="mt-0.5 size-7 shrink-0"+ />+ <div className="min-w-0 max-w-[85%]">+ <div className="text-sm font-medium">{respondingBot.name}</div>+ <p className="mt-1 whitespace-pre-wrap text-sm leading-6 text-foreground/90">+ {message.text}+ </p>+ </div>+ </div>+ );+ }+ return (+ <div key={message.id} className="flex justify-end" data-testid="group-user-message">+ <div className="max-w-[78%] rounded-2xl bg-foreground/10 px-3.5 py-2 text-sm leading-6">+ <p className="whitespace-pre-wrap">{message.text}</p>+ </div>+ </div>+ );+ })+ )}+ {working ? <BotActivityStatus avatar={activeBot.avatar} name={activeBot.name} /> : null}+ {runtime.error ? (+ <div+ role="alert"+ className="rounded-lg border border-destructive/30 bg-destructive/8 px-3 py-2 text-sm text-destructive"+ >+ {runtime.error}+ </div>+ ) : null}+ </BotConversationScrollArea>+ <BotPromptComposer+ botName={group.name}+ draftKey={`group:${group.id}`}+ disabled={+ runtime.sending ||+ !runtime.groupReady ||+ !runtime.bootstrapped ||+ runtime.defaultProject === null+ }+ mentionBots={members.map((bot) => ({ id: bot.id, name: bot.name }))}+ modelPicker={null}+ onSubmit={runtime.send}+ />+ </div>+ </SidebarInset>+ );+}diff --git a/apps/web/src/components/roster/NewBotDialog.tsx b/apps/web/src/components/roster/NewBotDialog.tsxnew file mode 100644index 000000000..793beb4bf--- /dev/null+++ b/apps/web/src/components/roster/NewBotDialog.tsx@@ -0,0 +1,150 @@+import { useState } from "react";++import { cn } from "../../lib/utils";+import { readFileAsDataUrl } from "../ChatView.logic";+import { Button } from "../ui/button";+import { Dialog, DialogPopup, DialogTitle } from "../ui/dialog";+import { Input } from "../ui/input";+import { BotAvatarView } from "./BotAvatarView";+import { BLOB_COLORS, BLOB_SHAPES, randomBotAvatar } from "./roster.logic";+import type { BotAvatar } from "./types";++/** A compact bot creation form with all required choices in one view. */+export function NewBotDialog({+ open,+ onOpenChange,+ onCreate,+}: {+ open: boolean;+ onOpenChange: (open: boolean) => void;+ onCreate: (input: { name: string; avatar: BotAvatar }) => void;+}) {+ const [name, setName] = useState("");+ const [blobAvatar, setBlobAvatar] = useState(() => randomBotAvatar());+ const [avatar, setAvatar] = useState<BotAvatar>(() => blobAvatar);+ const trimmedName = name.trim();++ const updateBlobAvatar = (next: typeof blobAvatar) => {+ setBlobAvatar(next);+ setAvatar(next);+ };++ const handleUpload = (file: File | undefined) => {+ if (!file) return;+ void readFileAsDataUrl(file).then(+ (assetPath) => {+ setAvatar({ kind: "image", assetPath, dithered: false });+ },+ (error: unknown) => {+ console.error("Could not read avatar image.", error);+ },+ );+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogPopup className="max-w-lg overflow-hidden p-0" bottomStickOnMobile={false}>+ <form+ onSubmit={(event) => {+ event.preventDefault();+ if (trimmedName.length === 0) return;+ onCreate({ name: trimmedName, avatar });+ }}+ >+ <header className="border-b px-6 py-5">+ <DialogTitle>New bot</DialogTitle>+ </header>++ <div className="space-y-6 px-6 py-6">+ <div className="flex items-center gap-4">+ <BotAvatarView avatar={avatar} name={trimmedName} className="size-16 shrink-0" />+ <label className="flex min-w-0 flex-1 flex-col gap-2 text-sm font-medium text-foreground">+ Name+ <Input+ autoFocus+ data-testid="new-bot-name-input"+ maxLength={80}+ placeholder="Bot name"+ value={name}+ onChange={(event) => setName(event.target.value)}+ />+ </label>+ </div>++ <section aria-labelledby="new-bot-avatar-heading" className="space-y-4 border-t pt-5">+ <div className="flex items-center justify-between gap-3">+ <h3 id="new-bot-avatar-heading" className="text-sm font-medium text-foreground">+ Avatar+ </h3>+ <label className="cursor-pointer rounded-md border border-input bg-background px-3 py-1.5 text-sm font-medium text-foreground shadow-xs/5 outline-none transition-colors hover:bg-accent focus-within:ring-2 focus-within:ring-ring">+ Upload image+ <input+ type="file"+ accept="image/*"+ className="sr-only"+ onChange={(event) => handleUpload(event.currentTarget.files?.[0])}+ />+ </label>+ </div>++ <div className="grid grid-cols-4 gap-2 sm:grid-cols-7">+ {BLOB_SHAPES.map((shape) => {+ const selected = avatar.kind === "blob" && blobAvatar.shape === shape;+ return (+ <button+ key={shape}+ type="button"+ aria-label={shape}+ aria-pressed={selected}+ data-bot-hover+ onClick={() => updateBlobAvatar({ ...blobAvatar, shape })}+ className={cn(+ "flex aspect-square cursor-pointer items-center justify-center rounded-lg border border-transparent outline-none transition-colors focus-visible:ring-2 focus-visible:ring-ring",+ selected ? "border-border bg-accent" : "hover:bg-accent/60",+ )}+ >+ <BotAvatarView+ avatar={{ ...blobAvatar, shape }}+ name={trimmedName}+ className="size-9"+ />+ </button>+ );+ })}+ </div>++ <div className="flex flex-wrap gap-2.5">+ {BLOB_COLORS.map((color) => {+ const selected = avatar.kind === "blob" && blobAvatar.color === color;+ return (+ <button+ key={color}+ type="button"+ aria-label={color}+ aria-pressed={selected}+ onClick={() => updateBlobAvatar({ ...blobAvatar, color })}+ style={{ backgroundColor: color }}+ className={cn(+ "size-8 cursor-pointer rounded-full border border-foreground/10 outline-none focus-visible:ring-2 focus-visible:ring-ring",+ selected && "ring-2 ring-ring ring-offset-2 ring-offset-popover",+ )}+ />+ );+ })}+ </div>+ </section>+ </div>++ <footer className="flex justify-end gap-2 border-t bg-muted px-6 py-4">+ <Button type="button" variant="outline" onClick={() => onOpenChange(false)}>+ Cancel+ </Button>+ <Button type="submit" disabled={trimmedName.length === 0}>+ Create bot+ </Button>+ </footer>+ </form>+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/web/src/components/roster/botConversationPresentation.test.ts b/apps/web/src/components/roster/botConversationPresentation.test.tsnew file mode 100644index 000000000..54ebd19da--- /dev/null+++ b/apps/web/src/components/roster/botConversationPresentation.test.ts@@ -0,0 +1,58 @@+import { MessageId, TurnId, type OrchestrationMessage } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { visibleBotChatMessages } from "./botConversationPresentation";++const message = (+ id: string,+ role: "user" | "assistant" | "system",+ streaming: boolean,+ turnId: string | null = null,+): OrchestrationMessage =>+ ({+ id: MessageId.make(id),+ role,+ text: id,+ turnId: turnId === null ? null : TurnId.make(turnId),+ streaming,+ createdAt: "2026-08-27T00:00:00.000Z",+ updatedAt: "2026-08-27T00:00:00.000Z",+ }) as const;++describe("bot conversation presentation", () => {+ it("keeps user messages and settled answers only", () => {+ const messages = [+ message("user", "user", false),+ message("reasoning", "assistant", true, "turn-1"),+ message("answer", "assistant", false, "turn-1"),+ message("system", "system", false),+ ];++ expect(visibleBotChatMessages(messages).map((entry) => entry.id)).toEqual(["user", "answer"]);+ });++ it("shows only the last settled assistant record from one turn", () => {+ const messages = [+ message("user", "user", false),+ message("intermediate", "assistant", false, "turn-1"),+ message("final", "assistant", false, "turn-1"),+ ];++ expect(visibleBotChatMessages(messages).map((entry) => entry.id)).toEqual(["user", "final"]);+ });++ it("hides assistant records from the active turn behind the working status", () => {+ const messages = [+ message("first-user", "user", false),+ message("first-answer", "assistant", false, "turn-1"),+ message("active-user", "user", false),+ message("active-intermediate", "assistant", false, "turn-2"),+ ];++ expect(visibleBotChatMessages(messages, true).map((entry) => entry.id)).toEqual([+ "first-user",+ "first-answer",+ "active-user",+ ]);+ });+});diff --git a/apps/web/src/components/roster/botConversationPresentation.ts b/apps/web/src/components/roster/botConversationPresentation.tsnew file mode 100644index 000000000..cd02a6c42--- /dev/null+++ b/apps/web/src/components/roster/botConversationPresentation.ts@@ -0,0 +1,36 @@+import type { OrchestrationMessage } from "@t3tools/contracts";++/**+ * Bot chat shows each user message and one final assistant answer per turn.+ * Provider progress and intermediate assistant records stay behind the working+ * status so one provider turn cannot appear as several bot replies.+ */+export function visibleBotChatMessages(+ messages: ReadonlyArray<OrchestrationMessage>,+ working = false,+): ReadonlyArray<OrchestrationMessage> {+ const latestAssistantIndexByResponse = new Map<string, number>();+ let precedingUserId = "before-first-user";+ let lastUserIndex = -1;++ messages.forEach((message, index) => {+ if (message.role === "user") {+ precedingUserId = message.id;+ lastUserIndex = index;+ return;+ }+ if (message.role !== "assistant" || message.streaming) return;+ latestAssistantIndexByResponse.set(message.turnId ?? precedingUserId, index);+ });++ precedingUserId = "before-first-user";+ return messages.filter((message, index) => {+ if (message.role === "user") {+ precedingUserId = message.id;+ return true;+ }+ if (message.role !== "assistant" || message.streaming) return false;+ if (working && index > lastUserIndex) return false;+ return latestAssistantIndexByResponse.get(message.turnId ?? precedingUserId) === index;+ });+}diff --git a/apps/web/src/components/roster/botConversationScroll.logic.test.ts b/apps/web/src/components/roster/botConversationScroll.logic.test.tsnew file mode 100644index 000000000..e029ea7bc--- /dev/null+++ b/apps/web/src/components/roster/botConversationScroll.logic.test.ts@@ -0,0 +1,53 @@+import { describe, expect, it } from "vite-plus/test";++import { isConversationAtEnd, reduceConversationFollowState } from "./botConversationScroll.logic";++describe("isConversationAtEnd", () => {+ it("treats underflowing and end-aligned conversations as live", () => {+ expect(isConversationAtEnd({ scrollTop: 0, scrollHeight: 400, clientHeight: 600 })).toBe(true);+ expect(isConversationAtEnd({ scrollTop: 400, scrollHeight: 1000, clientHeight: 600 })).toBe(+ true,+ );+ });++ it("stops live follow when the user moves above the end threshold", () => {+ expect(isConversationAtEnd({ scrollTop: 300, scrollHeight: 1000, clientHeight: 600 })).toBe(+ false,+ );+ expect(isConversationAtEnd({ scrollTop: 378, scrollHeight: 1000, clientHeight: 600 })).toBe(+ true,+ );+ });+});++describe("reduceConversationFollowState", () => {+ it("does not follow streaming growth after the user scrolls away", () => {+ const state = reduceConversationFollowState(+ { followingEnd: true, programmaticScroll: false },+ { type: "user-navigation" },+ );++ expect(state).toEqual({ followingEnd: false, programmaticScroll: false });+ });++ it("re-enables live follow when the user returns to the end", () => {+ const state = reduceConversationFollowState(+ { followingEnd: false, programmaticScroll: false },+ { type: "scroll", isAtEnd: true },+ );++ expect(state).toEqual({ followingEnd: true, programmaticScroll: false });+ });++ it("keeps a smooth scroll active until it reaches the end", () => {+ const started = reduceConversationFollowState(+ { followingEnd: false, programmaticScroll: false },+ { type: "scroll-to-end" },+ );+ const inProgress = reduceConversationFollowState(started, { type: "scroll", isAtEnd: false });+ const finished = reduceConversationFollowState(inProgress, { type: "scroll", isAtEnd: true });++ expect(inProgress).toEqual({ followingEnd: true, programmaticScroll: true });+ expect(finished).toEqual({ followingEnd: true, programmaticScroll: false });+ });+});diff --git a/apps/web/src/components/roster/botConversationScroll.logic.ts b/apps/web/src/components/roster/botConversationScroll.logic.tsnew file mode 100644index 000000000..4e96aa587--- /dev/null+++ b/apps/web/src/components/roster/botConversationScroll.logic.ts@@ -0,0 +1,40 @@+export interface ConversationScrollMetrics {+ readonly scrollTop: number;+ readonly scrollHeight: number;+ readonly clientHeight: number;+}++export const CONVERSATION_END_THRESHOLD_PX = 24;++export interface ConversationFollowState {+ readonly followingEnd: boolean;+ readonly programmaticScroll: boolean;+}++export type ConversationFollowEvent =+ | { readonly type: "user-navigation" }+ | { readonly type: "scroll-to-end" }+ | { readonly type: "scroll"; readonly isAtEnd: boolean };++export function reduceConversationFollowState(+ state: ConversationFollowState,+ event: ConversationFollowEvent,+): ConversationFollowState {+ if (event.type === "user-navigation") {+ return { followingEnd: false, programmaticScroll: false };+ }+ if (event.type === "scroll-to-end") {+ return { followingEnd: true, programmaticScroll: true };+ }+ if (event.isAtEnd) {+ return { followingEnd: true, programmaticScroll: false };+ }+ return state.programmaticScroll ? state : { followingEnd: false, programmaticScroll: false };+}++export function isConversationAtEnd(+ metrics: ConversationScrollMetrics,+ threshold = CONVERSATION_END_THRESHOLD_PX,+): boolean {+ return metrics.scrollHeight - metrics.clientHeight - metrics.scrollTop <= threshold;+}diff --git a/apps/web/src/components/roster/botDraftStore.test.ts b/apps/web/src/components/roster/botDraftStore.test.tsnew file mode 100644index 000000000..86b0a3c93--- /dev/null+++ b/apps/web/src/components/roster/botDraftStore.test.ts@@ -0,0 +1,46 @@+import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";++import { clearBotDraft, readBotDraft, writeBotDraft } from "./botDraftStore";++const memory = new Map<string, string>();++beforeEach(() => {+ memory.clear();+ Object.defineProperty(globalThis, "localStorage", {+ configurable: true,+ value: {+ getItem: (key: string) => memory.get(key) ?? null,+ setItem: (key: string, value: string) => {+ memory.set(key, value);+ },+ removeItem: (key: string) => {+ memory.delete(key);+ },+ clear: () => memory.clear(),+ },+ });+});++afterEach(() => {+ memory.clear();+});++describe("botDraftStore", () => {+ it("restores a typed draft after a simulated restart", () => {+ writeBotDraft("bot-1", "yo what tool calls u got?");+ expect(readBotDraft("bot-1")).toBe("yo what tool calls u got?");+ });++ it("clears a draft after send", () => {+ writeBotDraft("bot-1", "half a sentence");+ clearBotDraft("bot-1");+ expect(readBotDraft("bot-1")).toBe("");+ });++ it("keeps drafts for other bots", () => {+ writeBotDraft("bot-1", "one");+ writeBotDraft("bot-2", "two");+ clearBotDraft("bot-1");+ expect(readBotDraft("bot-2")).toBe("two");+ });+});diff --git a/apps/web/src/components/roster/botDraftStore.ts b/apps/web/src/components/roster/botDraftStore.tsnew file mode 100644index 000000000..329c3a7a5--- /dev/null+++ b/apps/web/src/components/roster/botDraftStore.ts@@ -0,0 +1,57 @@+const DRAFTS_KEY = "akeru:bot-drafts:v1";+const MAX_DRAFT_CHARS = 20_000;++function storage(): Storage | null {+ try {+ return globalThis.localStorage;+ } catch {+ return null;+ }+}++function readAll(): Record<string, string> {+ const localStorage = storage();+ if (!localStorage) return {};+ try {+ const raw = localStorage.getItem(DRAFTS_KEY);+ if (raw === null) return {};+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return {};+ return Object.fromEntries(+ Object.entries(parsed).filter(+ (entry): entry is [string, string] => typeof entry[1] === "string",+ ),+ );+ } catch {+ return {};+ }+}++function writeAll(drafts: Record<string, string>): void {+ const localStorage = storage();+ if (!localStorage) return;+ try {+ localStorage.setItem(DRAFTS_KEY, JSON.stringify(drafts));+ } catch {+ // Quota or private mode. Draft recovery is best-effort.+ }+}++export function readBotDraft(draftKey: string): string {+ return readAll()[draftKey] ?? "";+}++export function writeBotDraft(draftKey: string, text: string): void {+ const drafts = readAll();+ const clipped = text.slice(0, MAX_DRAFT_CHARS);+ if (clipped.length === 0) {+ delete drafts[draftKey];+ } else {+ drafts[draftKey] = clipped;+ }+ writeAll(drafts);+}++export function clearBotDraft(draftKey: string): void {+ writeBotDraft(draftKey, "");+}diff --git a/apps/web/src/components/roster/botEngineSelection.test.ts b/apps/web/src/components/roster/botEngineSelection.test.tsnew file mode 100644index 000000000..b113ee7f8--- /dev/null+++ b/apps/web/src/components/roster/botEngineSelection.test.ts@@ -0,0 +1,44 @@+import { ProviderInstanceId } from "@t3tools/contracts";+import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";+import { describe, expect, it } from "vite-plus/test";++import { deriveProviderInstanceEntries } from "../../providerInstances";+import { makeComposerTestProvider } from "../../test/chatComposerProps";+import { resolveStickyBotEngine } from "./botEngineSelection";++const settings = DEFAULT_UNIFIED_SETTINGS;++describe("resolveStickyBotEngine", () => {+ it("keeps the bot engine model instead of the app default", () => {+ const providers = [makeComposerTestProvider()];+ const instanceEntries = deriveProviderInstanceEntries(providers);+ const instanceId = instanceEntries[0]?.instanceId;+ if (!instanceId) throw new Error("missing instance");++ const resolved = resolveStickyBotEngine({+ engine: { provider: instanceId, model: "gpt-5.6-sol" },+ instanceEntries,+ settings,+ providers,+ defaultSelection: { instanceId, model: "gpt-5.6-luna" },+ });++ expect(resolved).toEqual({ instanceId, model: "gpt-5.6-sol" });+ });++ it("uses the default instance when the bot has no engine", () => {+ const providers = [makeComposerTestProvider()];+ const instanceEntries = deriveProviderInstanceEntries(providers);+ const instanceId = instanceEntries[0]?.instanceId ?? ProviderInstanceId.make("codex");++ const resolved = resolveStickyBotEngine({+ engine: null,+ instanceEntries,+ settings,+ providers,+ defaultSelection: { instanceId, model: "gpt-5.6-luna" },+ });++ expect(resolved?.instanceId).toBe(instanceId);+ });+});diff --git a/apps/web/src/components/roster/botEngineSelection.ts b/apps/web/src/components/roster/botEngineSelection.tsnew file mode 100644index 000000000..ec8c9a5a6--- /dev/null+++ b/apps/web/src/components/roster/botEngineSelection.ts@@ -0,0 +1,36 @@+import {+ ProviderInstanceId,+ type BotEngine,+ type ServerProvider,+ type UnifiedSettings,+} from "@t3tools/contracts";++import { resolveAppModelSelectionForInstance } from "../../modelSelection";+import {+ resolveSelectableProviderInstanceEntry,+ type ProviderInstanceEntry,+} from "../../providerInstances";++export function resolveStickyBotEngine(input: {+ readonly engine: BotEngine | null;+ readonly instanceEntries: ReadonlyArray<ProviderInstanceEntry>;+ readonly settings: UnifiedSettings;+ readonly providers: ReadonlyArray<ServerProvider>;+ readonly defaultSelection: { readonly instanceId: ProviderInstanceId; readonly model: string };+}): { readonly instanceId: ProviderInstanceId; readonly model: string } | null {+ const preferredId = ProviderInstanceId.make(+ input.engine?.provider ?? input.defaultSelection.instanceId,+ );+ const entry =+ resolveSelectableProviderInstanceEntry(input.instanceEntries, preferredId) ??+ input.instanceEntries[0] ??+ null;+ if (!entry) return null;+ if (input.engine && input.engine.provider === entry.instanceId) {+ return { instanceId: entry.instanceId, model: input.engine.model };+ }+ const model =+ resolveAppModelSelectionForInstance(entry.instanceId, input.settings, input.providers, null) ??+ input.defaultSelection.model;+ return { instanceId: entry.instanceId, model };+}diff --git a/apps/web/src/components/roster/botPresence.ts b/apps/web/src/components/roster/botPresence.tsnew file mode 100644index 000000000..ab70baf73--- /dev/null+++ b/apps/web/src/components/roster/botPresence.ts@@ -0,0 +1,48 @@+import { EnvironmentId, ThreadId, type ScopedThreadRef } from "@t3tools/contracts";+import { useMemo } from "react";++import { useThreadShell, useThreadShells } from "../../state/entities";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { findLatestBotThreadTarget, findLatestGroupThreadTarget } from "./botThreadRuntime.logic";+import { parseChatPath, resolveBotPresence, type RosterPresence } from "./roster.logic";+import { useRosterStore } from "./rosterStore";++/**+ * Live presence for one bot, derived from its latest durable server thread.+ */+export function useBotPresence(botId: string): RosterPresence {+ const chatPath = useRosterStore((state) => state.chatPathByBotId[botId] ?? null);+ const environmentId = usePrimaryEnvironmentId();+ const threadShells = useThreadShells();+ const ref = useMemo<ScopedThreadRef | null>(() => {+ const durableTarget = environmentId+ ? findLatestBotThreadTarget(botId, environmentId, threadShells)+ : null;+ const target = durableTarget ?? (chatPath === null ? null : parseChatPath(chatPath));+ return target+ ? {+ environmentId: EnvironmentId.make(target.environmentId),+ threadId: ThreadId.make(target.threadId),+ }+ : null;+ }, [botId, chatPath, environmentId, threadShells]);+ return resolveBotPresence(useThreadShell(ref));+}++/** Live presence for a group, derived from its latest durable server thread. */+export function useGroupPresence(groupId: string): RosterPresence {+ const environmentId = usePrimaryEnvironmentId();+ const threadShells = useThreadShells();+ const ref = useMemo<ScopedThreadRef | null>(() => {+ const target = environmentId+ ? findLatestGroupThreadTarget(groupId, environmentId, threadShells)+ : null;+ return target+ ? {+ environmentId: EnvironmentId.make(target.environmentId),+ threadId: ThreadId.make(target.threadId),+ }+ : null;+ }, [environmentId, groupId, threadShells]);+ return resolveBotPresence(useThreadShell(ref));+}diff --git a/apps/web/src/components/roster/botSandbox.test.ts b/apps/web/src/components/roster/botSandbox.test.tsnew file mode 100644index 000000000..c84b178f5--- /dev/null+++ b/apps/web/src/components/roster/botSandbox.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from "vite-plus/test";++import { BOT_SANDBOX_OPTIONS, botSandboxChoice, botSandboxLabel } from "./botSandbox";++describe("botSandbox", () => {+ it("treats a missing bot sandbox as local", () => {+ expect(botSandboxChoice(null)).toBe("local");+ expect(botSandboxChoice("local")).toBe("local");+ expect(botSandboxChoice("vercel")).toBe("vercel");+ });++ it("lists the first sandbox providers", () => {+ expect(BOT_SANDBOX_OPTIONS.map((option) => option.value)).toEqual([+ "local",+ "vercel",+ "akeru-cloud",+ "upstash",+ ]);+ expect(botSandboxLabel("akeru-cloud")).toBe("Akeru Cloud");+ });+});diff --git a/apps/web/src/components/roster/botSandbox.ts b/apps/web/src/components/roster/botSandbox.tsnew file mode 100644index 000000000..32068fa9b--- /dev/null+++ b/apps/web/src/components/roster/botSandbox.ts@@ -0,0 +1,18 @@+import type { Bot } from "./types";++export const BOT_SANDBOX_OPTIONS = [+ { value: "local", label: "Local" },+ { value: "vercel", label: "Vercel" },+ { value: "akeru-cloud", label: "Akeru Cloud" },+ { value: "upstash", label: "Upstash" },+] as const;++export type BotSandboxChoice = (typeof BOT_SANDBOX_OPTIONS)[number]["value"];++export function botSandboxChoice(sandbox: Bot["sandbox"]): BotSandboxChoice {+ return sandbox ?? "local";+}++export function botSandboxLabel(sandbox: BotSandboxChoice): string {+ return BOT_SANDBOX_OPTIONS.find((option) => option.value === sandbox)?.label ?? "Local";+}diff --git a/apps/web/src/components/roster/botThreadRuntime.logic.test.ts b/apps/web/src/components/roster/botThreadRuntime.logic.test.tsnew file mode 100644index 000000000..41fdec565--- /dev/null+++ b/apps/web/src/components/roster/botThreadRuntime.logic.test.ts@@ -0,0 +1,116 @@+import { BotId, GroupId, ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import {+ buildBotTurnStartInput,+ buildGroupTurnStartInput,+ findLatestBotThreadTarget,+ findLatestGroupThreadTarget,+} from "./botThreadRuntime.logic";++describe("bot thread runtime", () => {+ it("associates the first durable thread with its bot", () => {+ const input = buildBotTurnStartInput({+ botId: BotId.make("bot-akeru"),+ threadId: ThreadId.make("thread-akeru"),+ projectId: ProjectId.make("project-akeru"),+ title: "Hello",+ message: {+ messageId: "message-akeru" as never,+ role: "user",+ text: "Hello",+ attachments: [],+ },+ modelSelection: {+ instanceId: ProviderInstanceId.make("codex"),+ model: "gpt-5.6",+ },+ runtimeMode: "full-access",+ interactionMode: "default",+ createdAt: "2026-08-27T00:00:00.000Z",+ createThread: true,+ });++ expect(input.bootstrap?.createThread?.botId).toBe("bot-akeru");+ expect(input.bootstrap?.createThread?.projectId).toBe("project-akeru");+ });++ it("associates a group thread and routes a mention to its selected bot", () => {+ const input = buildGroupTurnStartInput({+ groupId: GroupId.make("group-product"),+ respondingBotId: BotId.make("bot-specialist"),+ threadId: ThreadId.make("thread-product"),+ projectId: ProjectId.make("project-akeru"),+ title: "Review this",+ message: {+ messageId: "message-product" as never,+ role: "user",+ text: "@Mori Review this",+ attachments: [],+ },+ modelSelection: {+ instanceId: ProviderInstanceId.make("codex"),+ model: "gpt-5.6",+ },+ runtimeMode: "full-access",+ interactionMode: "default",+ createdAt: "2026-08-27T00:00:00.000Z",+ createThread: true,+ });++ expect(input.bootstrap?.createThread?.groupId).toBe("group-product");+ expect(input.respondingBotId).toBe("bot-specialist");+ });++ it("restores the latest durable thread owned by the bot", () => {+ expect(+ findLatestBotThreadTarget("bot-akeru", "env-a", [+ {+ environmentId: "env-a",+ id: "thread-old",+ botId: "bot-akeru",+ updatedAt: "2026-08-26T00:00:00.000Z",+ archivedAt: null,+ deletedAt: null,+ },+ {+ environmentId: "env-a",+ id: "thread-other",+ botId: "bot-other",+ updatedAt: "2026-08-28T00:00:00.000Z",+ archivedAt: null,+ deletedAt: null,+ },+ {+ environmentId: "env-b",+ id: "thread-new",+ botId: "bot-akeru",+ updatedAt: "2026-08-27T00:00:00.000Z",+ archivedAt: null,+ deletedAt: null,+ },+ ]),+ ).toEqual({ environmentId: "env-a", threadId: "thread-old" });+ });++ it("restores the latest durable thread owned by a group", () => {+ expect(+ findLatestGroupThreadTarget("group-product", "env-a", [+ {+ environmentId: "env-a",+ id: "thread-old",+ groupId: "group-product",+ updatedAt: "2026-08-26T00:00:00.000Z",+ archivedAt: null,+ },+ {+ environmentId: "env-a",+ id: "thread-new",+ groupId: "group-product",+ updatedAt: "2026-08-27T00:00:00.000Z",+ archivedAt: null,+ },+ ]),+ ).toEqual({ environmentId: "env-a", threadId: "thread-new" });+ });+});diff --git a/apps/web/src/components/roster/botThreadRuntime.logic.ts b/apps/web/src/components/roster/botThreadRuntime.logic.tsnew file mode 100644index 000000000..b8e4f458c--- /dev/null+++ b/apps/web/src/components/roster/botThreadRuntime.logic.ts@@ -0,0 +1,146 @@+import type { StartThreadTurnInput } from "@t3tools/client-runtime/state/threads";+import type {+ BotId,+ GroupId,+ ModelSelection,+ ProjectId,+ ProviderInteractionMode,+ RuntimeMode,+ ThreadId,+} from "@t3tools/contracts";++export function buildBotTurnStartInput(input: {+ botId: BotId;+ threadId: ThreadId;+ projectId: ProjectId;+ title: string;+ message: StartThreadTurnInput["message"];+ modelSelection: ModelSelection;+ runtimeMode: RuntimeMode;+ interactionMode: ProviderInteractionMode;+ createdAt: string;+ createThread: boolean;+}): StartThreadTurnInput {+ return {+ threadId: input.threadId,+ message: input.message,+ modelSelection: input.modelSelection,+ titleSeed: input.title,+ runtimeMode: input.runtimeMode,+ interactionMode: input.interactionMode,+ ...(input.createThread+ ? {+ bootstrap: {+ createThread: {+ projectId: input.projectId,+ botId: input.botId,+ title: input.title,+ modelSelection: input.modelSelection,+ runtimeMode: input.runtimeMode,+ interactionMode: input.interactionMode,+ branch: null,+ worktreePath: null,+ createdAt: input.createdAt,+ },+ },+ }+ : {}),+ createdAt: input.createdAt,+ };+}++export function buildGroupTurnStartInput(input: {+ groupId: GroupId;+ respondingBotId?: BotId;+ threadId: ThreadId;+ projectId: ProjectId;+ title: string;+ message: StartThreadTurnInput["message"];+ modelSelection: ModelSelection;+ runtimeMode: RuntimeMode;+ interactionMode: ProviderInteractionMode;+ createdAt: string;+ createThread: boolean;+}): StartThreadTurnInput {+ return {+ threadId: input.threadId,+ message: input.message,+ modelSelection: input.modelSelection,+ titleSeed: input.title,+ runtimeMode: input.runtimeMode,+ interactionMode: input.interactionMode,+ ...(input.respondingBotId ? { respondingBotId: input.respondingBotId } : {}),+ ...(input.createThread+ ? {+ bootstrap: {+ createThread: {+ projectId: input.projectId,+ groupId: input.groupId,+ title: input.title,+ modelSelection: input.modelSelection,+ runtimeMode: input.runtimeMode,+ interactionMode: input.interactionMode,+ branch: null,+ worktreePath: null,+ createdAt: input.createdAt,+ },+ },+ }+ : {}),+ createdAt: input.createdAt,+ };+}++export function findLatestBotThreadTarget(+ botId: string,+ environmentId: string,+ threads: readonly {+ environmentId: string;+ id: string;+ botId?: string | null | undefined;+ updatedAt: string;+ archivedAt: string | null;+ deletedAt?: string | null | undefined;+ }[],+): { environmentId: string; threadId: string } | null {+ const latest = threads+ .filter(+ (thread) =>+ thread.environmentId === environmentId &&+ thread.botId === botId &&+ thread.archivedAt === null &&+ thread.deletedAt == null,+ )+ .toSorted(+ (left, right) =>+ right.updatedAt.localeCompare(left.updatedAt) || right.id.localeCompare(left.id),+ )[0];+ return latest ? { environmentId: latest.environmentId, threadId: latest.id } : null;+}++export function findLatestGroupThreadTarget(+ groupId: string,+ environmentId: string,+ threads: readonly {+ environmentId: string;+ id: string;+ groupId?: string | null | undefined;+ updatedAt: string;+ archivedAt: string | null;+ deletedAt?: string | null | undefined;+ }[],+): { environmentId: string; threadId: string } | null {+ const latest = threads+ .filter(+ (thread) =>+ thread.environmentId === environmentId &&+ thread.groupId === groupId &&+ thread.archivedAt === null &&+ thread.deletedAt == null,+ )+ .toSorted(+ (left, right) =>+ right.updatedAt.localeCompare(left.updatedAt) || right.id.localeCompare(left.id),+ )[0];+ return latest ? { environmentId: latest.environmentId, threadId: latest.id } : null;+}diff --git a/apps/web/src/components/roster/dither.logic.test.ts b/apps/web/src/components/roster/dither.logic.test.tsnew file mode 100644index 000000000..c28327d35--- /dev/null+++ b/apps/web/src/components/roster/dither.logic.test.ts@@ -0,0 +1,145 @@+import { describe, expect, it } from "vite-plus/test";++import {+ contrastRatio,+ DITHER_GRID_SIZE,+ ditherForegroundColor,+ ditherSeedForName,+ generateDitherIdenticon,+ identiconPathData,+ orderedDitherRgba,+ rerollDitherSeed,+ resolveUploadAvatar,+} from "./dither.logic";+import { BLOB_COLORS } from "./roster.logic";++describe("ditherForegroundColor", () => {+ it("meets 4.5:1 contrast against every palette background", () => {+ for (const color of BLOB_COLORS) {+ const foreground = ditherForegroundColor(color);+ expect(contrastRatio(color, foreground), color).toBeGreaterThanOrEqual(4.5);+ }+ });++ it("chooses the higher-contrast monochrome color", () => {+ for (const color of BLOB_COLORS) {+ const foreground = ditherForegroundColor(color);+ const other = foreground === "#000000" ? "#ffffff" : "#000000";+ expect(contrastRatio(color, foreground)).toBeGreaterThanOrEqual(contrastRatio(color, other));+ }+ });+});++describe("generateDitherIdenticon", () => {+ it("is deterministic: same seed, same cells and colors", () => {+ const a = generateDitherIdenticon("Akeru");+ const b = generateDitherIdenticon("Akeru");+ expect(b.cells).toEqual(a.cells);+ expect(b.background).toBe(a.background);+ expect(b.foreground).toBe(a.foreground);+ });++ it("differs across seeds", () => {+ const seeds = ["Akeru", "Mori", "Sage", "Akeru#a1b2c3"];+ const patterns = seeds.map((seed) => identiconPathData(generateDitherIdenticon(seed)));+ expect(new Set(patterns).size).toBe(seeds.length);+ });++ it("paints a readable pattern: both on and off cells, contrasting colors", () => {+ for (const seed of ["Akeru", "Mori", "Sage", "z", "bot"]) {+ const identicon = generateDitherIdenticon(seed);+ const onCount = identicon.cells.filter(Boolean).length;+ expect(onCount).toBeGreaterThan(0);+ expect(onCount).toBeLessThan(identicon.cells.length);+ expect(identicon.foreground).not.toBe(identicon.background);+ }+ });++ it("mirrors horizontally, identicon style", () => {+ const { size, cells } = generateDitherIdenticon("Akeru");+ for (let y = 0; y < size; y++) {+ for (let x = 0; x < size / 2; x++) {+ expect(cells[y * size + x]).toBe(cells[y * size + (size - 1 - x)]);+ }+ }+ });++ it("survives an empty seed", () => {+ const identicon = generateDitherIdenticon("");+ expect(identicon.cells).toHaveLength(DITHER_GRID_SIZE * DITHER_GRID_SIZE);+ });+});++describe("orderedDitherRgba", () => {+ const gradient = (width: number, height: number): Uint8ClampedArray => {+ const data = new Uint8ClampedArray(width * height * 4);+ for (let index = 0; index < width * height; index++) {+ const value = Math.round((index / (width * height - 1)) * 255);+ data.set([value, value, value, 255], index * 4);+ }+ return data;+ };++ it("changes pixels and leaves only pure black or white", () => {+ const width = 16;+ const height = 16;+ const data = gradient(width, height);+ const before = Uint8ClampedArray.from(data);+ orderedDitherRgba(data, width, height);+ expect(data).not.toEqual(before);+ for (let index = 0; index < data.length; index += 4) {+ expect([0, 255]).toContain(data[index]);+ expect(data[index + 1]).toBe(data[index]);+ expect(data[index + 2]).toBe(data[index]);+ expect(data[index + 3]).toBe(255);+ }+ });++ it("is deterministic for the same input", () => {+ const a = gradient(8, 8);+ const b = gradient(8, 8);+ orderedDitherRgba(a, 8, 8);+ orderedDitherRgba(b, 8, 8);+ expect(a).toEqual(b);+ });+});++describe("seeds", () => {+ it("derives the initial seed from the name, with a fallback", () => {+ expect(ditherSeedForName(" Akeru ")).toBe("Akeru");+ expect(ditherSeedForName(" ")).toBe("bot");+ });++ it("rerolls keep the name prefix and vary with the random source", () => {+ const first = rerollDitherSeed("Akeru", () => 0.25);+ const second = rerollDitherSeed("Akeru", () => 0.75);+ expect(first.startsWith("Akeru#")).toBe(true);+ expect(second).not.toBe(first);+ expect(rerollDitherSeed("Akeru", () => 0.25)).toBe(first);+ });+});++describe("resolveUploadAvatar", () => {+ const upload = { plainUrl: "data:plain", ditheredUrl: "data:dithered" };++ it("is null until an image is chosen", () => {+ expect(resolveUploadAvatar(null, false)).toBeNull();+ expect(resolveUploadAvatar(null, true)).toBeNull();+ });++ it("saves the plain rendering with dithered: false when the toggle is off", () => {+ expect(resolveUploadAvatar(upload, false)).toEqual({+ kind: "image",+ assetPath: "data:plain",+ dithered: false,+ });+ });++ it("saves the dithered rendering with dithered: true when the toggle is on", () => {+ expect(resolveUploadAvatar(upload, true)).toEqual({+ kind: "image",+ assetPath: "data:dithered",+ dithered: true,+ });+ });+});diff --git a/apps/web/src/components/roster/dither.logic.ts b/apps/web/src/components/roster/dither.logic.tsnew file mode 100644index 000000000..b5269e19a--- /dev/null+++ b/apps/web/src/components/roster/dither.logic.ts@@ -0,0 +1,190 @@+import { BLOB_COLORS } from "./roster.logic";+import type { BotAvatar } from "./types";++/**+ * Dither Kit style identicons: a seeded intensity field pushed through a+ * Bayer ordered-dither threshold. Everything here is deterministic — the same+ * seed always yields the same pixels — so avatars render from the seed alone+ * and nothing needs to be stored.+ */++export const DITHER_GRID_SIZE = 16;++// Classic 4×4 Bayer matrix; thresholds are (value + 0.5) / 16.+const BAYER_4 = [+ [0, 8, 2, 10],+ [12, 4, 14, 6],+ [3, 11, 1, 9],+ [15, 7, 13, 5],+] as const;++// 8×8 Bayer matrix for photo dithering; thresholds are (value + 0.5) / 64.+const BAYER_8 = [+ [0, 32, 8, 40, 2, 34, 10, 42],+ [48, 16, 56, 24, 50, 18, 58, 26],+ [12, 44, 4, 36, 14, 46, 6, 38],+ [60, 28, 52, 20, 62, 30, 54, 22],+ [3, 35, 11, 43, 1, 33, 9, 41],+ [51, 19, 59, 27, 49, 17, 57, 25],+ [15, 47, 7, 39, 13, 45, 5, 37],+ [63, 31, 55, 23, 61, 29, 53, 21],+] as const;++/** FNV-1a, 32-bit. Stable across sessions, unlike anything Math-random. */+function hashSeed(seed: string): number {+ let hash = 0x811c9dc5;+ for (let index = 0; index < seed.length; index++) {+ hash ^= seed.charCodeAt(index);+ hash = Math.imul(hash, 0x01000193);+ }+ return hash >>> 0;+}++/** mulberry32: tiny seeded PRNG, consumed in a fixed order for determinism. */+function mulberry32(state: number): () => number {+ let a = state >>> 0;+ return () => {+ a = (a + 0x6d2b79f5) >>> 0;+ let t = a;+ t = Math.imul(t ^ (t >>> 15), t | 1);+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;+ };+}++/** The seed a bot's name implies; empty names still get a stable image. */+export function ditherSeedForName(name: string): string {+ const trimmed = name.trim();+ return trimmed.length === 0 ? "bot" : trimmed;+}++/**+ * Rerolled seed: the name plus a random suffix, so the identicon stays+ * name-flavored while every roll lands on a different image. The random+ * source is injectable for tests.+ */+export function rerollDitherSeed(name: string, random: () => number = Math.random): string {+ const suffix = Math.floor(random() * 36 ** 6)+ .toString(36)+ .padStart(6, "0");+ return `${ditherSeedForName(name)}#${suffix}`;+}++function relativeLuminance(hex: string): number {+ const match = /^#([0-9a-f]{6})$/i.exec(hex);+ if (match === null) return 0;+ const value = Number.parseInt(match[1]!, 16);+ const channel = (shift: number) => {+ const srgb = ((value >> shift) & 0xff) / 255;+ return srgb <= 0.04045 ? srgb / 12.92 : ((srgb + 0.055) / 1.055) ** 2.4;+ };+ return 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0);+}++/** WCAG contrast ratio for two six-digit hex colors. */+export function contrastRatio(first: string, second: string): number {+ const firstLuminance = relativeLuminance(first);+ const secondLuminance = relativeLuminance(second);+ const lighter = Math.max(firstLuminance, secondLuminance);+ const darker = Math.min(firstLuminance, secondLuminance);+ return (lighter + 0.05) / (darker + 0.05);+}++/** Pick the higher-contrast monochrome foreground for dither pixels. */+export function ditherForegroundColor(background: string): "#000000" | "#ffffff" {+ return contrastRatio(background, "#000000") >= contrastRatio(background, "#ffffff")+ ? "#000000"+ : "#ffffff";+}++export interface DitherIdenticon {+ /** Grid side length; cells is row-major size × size. */+ size: number;+ /** True cells paint the foreground color. */+ cells: boolean[];+ background: string;+ foreground: string;+}++/**+ * Seed → identicon. A jittered radial intensity field plus per-cell noise is+ * thresholded by the Bayer 4×4 matrix, then mirrored horizontally for the+ * classic identicon symmetry. Background comes from the blob palette and the+ * foreground picks whichever of black or white has the higher measured+ * contrast, so the image stays readable in both color schemes.+ */+export function generateDitherIdenticon(seed: string): DitherIdenticon {+ const random = mulberry32(hashSeed(seed.length === 0 ? "bot" : seed));+ const background = BLOB_COLORS[Math.floor(random() * BLOB_COLORS.length)]!;+ const size = DITHER_GRID_SIZE;+ const half = size / 2;+ const centerX = half - 0.5 + (random() - 0.5) * 3;+ const centerY = half - 0.5 + (random() - 0.5) * 3;+ const falloff = 1.2 + random() * 1.4;+ const noiseWeight = 0.25 + random() * 0.3;++ const cells = Array.from({ length: size * size }, () => false);+ for (let y = 0; y < size; y++) {+ for (let x = 0; x < half; x++) {+ const dx = (x - centerX) / half;+ const dy = (y - centerY) / half;+ const base = Math.max(0, 1 - Math.sqrt(dx * dx + dy * dy) ** falloff);+ const intensity = base * (1 - noiseWeight) + random() * noiseWeight;+ const on = intensity > (BAYER_4[y % 4]![x % 4]! + 0.5) / 16;+ cells[y * size + x] = on;+ cells[y * size + (size - 1 - x)] = on;+ }+ }+ return { size, cells, background, foreground: ditherForegroundColor(background) };+}++/** One SVG path of unit squares for the on cells; a single element per avatar. */+export function identiconPathData(identicon: DitherIdenticon): string {+ const parts: string[] = [];+ for (let y = 0; y < identicon.size; y++) {+ for (let x = 0; x < identicon.size; x++) {+ if (identicon.cells[y * identicon.size + x]) parts.push(`M${x} ${y}h1v1h-1z`);+ }+ }+ return parts.join("");+}++/**+ * In-place ordered dither over RGBA pixels: per-pixel luminance against the+ * tiled Bayer 8×8 threshold, output pure black or white, alpha untouched.+ * Operates on the raw array so tests run without a DOM ImageData.+ */+export function orderedDitherRgba(data: Uint8ClampedArray, width: number, height: number): void {+ for (let y = 0; y < height; y++) {+ for (let x = 0; x < width; x++) {+ const index = (y * width + x) * 4;+ const luminance =+ (0.299 * data[index]! + 0.587 * data[index + 1]! + 0.114 * data[index + 2]!) / 255;+ const value = luminance > (BAYER_8[y % 8]![x % 8]! + 0.5) / 64 ? 255 : 0;+ data[index] = value;+ data[index + 1] = value;+ data[index + 2] = value;+ }+ }+}++/** Both renderings of one upload, computed together at upload time. */+export interface UploadRendering {+ plainUrl: string;+ ditheredUrl: string;+}++/**+ * The avatar record an upload saves: the dithered rendering with+ * dithered: true when the toggle is on, the plain one with dithered: false+ * otherwise. Null until an image is chosen.+ */+export function resolveUploadAvatar(+ upload: UploadRendering | null,+ ditherEnabled: boolean,+): BotAvatar | null {+ if (upload === null) return null;+ return ditherEnabled+ ? { kind: "image", assetPath: upload.ditheredUrl, dithered: true }+ : { kind: "image", assetPath: upload.plainUrl, dithered: false };+}diff --git a/apps/web/src/components/roster/roster.logic.test.ts b/apps/web/src/components/roster/roster.logic.test.tsnew file mode 100644index 000000000..80f705ffd--- /dev/null+++ b/apps/web/src/components/roster/roster.logic.test.ts@@ -0,0 +1,404 @@+import { describe, expect, it } from "vite-plus/test";++import {+ blinkDelayMs,+ buildGroupedRosterSections,+ buildRosterSections,+ buildRosterStrip,+ buildRosterTiles,+ compareRosterBots,+ filterRosterBots,+ DEFAULT_BLOB_COLOR,+ DEFAULT_BLOB_SHAPE,+ formatRosterTimestamp,+ isRecordableChatPath,+ parseChatPath,+ randomBotAvatar,+ resolveBlobRendering,+ resolveBotPresence,+ resolveLatestRosterMessage,+ resolveRosterBotId,+ resolveRosterIndicator,+ BLOB_COLORS,+ BLOB_SHAPES,+ type RosterLastMessage,+} from "./roster.logic";+import type { Bot, BotAvatar, Group } from "./types";++function bot(input: Partial<Bot> & Pick<Bot, "id" | "name">): Bot {+ return {+ title: "Bot",+ label: null,+ description: null,+ disabledMcpServerIds: [],+ avatar: { kind: "blob", shape: "circle", color: "#5B7FD4" },+ engine: null,+ sandbox: null,+ runtimeMode: "full-access",+ usageCap: null,+ groupId: null,+ pinned: false,+ archivedAt: null,+ createdAt: "2026-08-01T00:00:00.000Z",+ updatedAt: "2026-08-01T00:00:00.000Z",+ ...input,+ };+}++describe("resolveRosterBotId", () => {+ it("does not redirect to a persisted bot that is absent from the loaded roster", () => {+ expect(resolveRosterBotId("missing", [])).toBeNull();+ expect(+ resolveRosterBotId("missing", [+ bot({ id: "available", name: "Available" }),+ bot({ id: "archived", name: "Archived", archivedAt: "2026-08-02T00:00:00.000Z" }),+ ]),+ ).toBe("available");+ });+});++describe("buildRosterSections", () => {+ it("partitions only bots by their binary pin state", () => {+ const sections = buildRosterSections([+ bot({ id: "pinned-a", name: "Pinned A", pinned: true }),+ bot({ id: "plain-a", name: "Plain A" }),+ bot({ id: "pinned-b", name: "Pinned B", pinned: true }),+ bot({ id: "plain-b", name: "Plain B" }),+ ]);++ expect(sections.map((section) => section.name)).toEqual(["Pinned", "Bots"]);+ expect(sections[0]?.bots.map((entry) => entry.id)).toEqual(["pinned-a", "pinned-b"]);+ expect(sections[1]?.bots.map((entry) => entry.id)).toEqual(["plain-a", "plain-b"]);+ });++ it("hides archived bots without changing persisted order", () => {+ const sections = buildRosterSections([+ bot({ id: "first", name: "First" }),+ bot({ id: "gone", name: "Gone", archivedAt: "2026-08-20T00:00:00.000Z" }),+ bot({ id: "second", name: "Second" }),+ ]);++ expect(sections[0]?.bots.map((entry) => entry.id)).toEqual(["first", "second"]);+ });++ it("unwraps the previous object call shape during a hot update", () => {+ const sections = buildRosterSections({+ bots: [bot({ id: "pinned", name: "Pinned", pinned: true })],+ });++ expect(sections[0]?.bots.map((entry) => entry.id)).toEqual(["pinned"]);+ });+});++describe("buildGroupedRosterSections", () => {+ const group: Group = {+ id: "group-product",+ name: "Product",+ bossBotId: "assigned",+ members: [{ botId: "assigned", role: "boss" }],+ createdAt: "2026-08-01T00:00:00.000Z",+ updatedAt: "2026-08-01T00:00:00.000Z",+ };++ it("shows assigned groups before Unassigned and leaves pinned bots in the strip", () => {+ const sections = buildGroupedRosterSections(+ [+ bot({ id: "assigned", name: "Assigned", groupId: group.id }),+ bot({ id: "free", name: "Free" }),+ bot({ id: "pinned", name: "Pinned", groupId: group.id, pinned: true }),+ ],+ [group],+ );++ expect(sections.map((section) => section.name)).toEqual(["Product", "Unassigned"]);+ expect(sections[0]?.bots.map((entry) => entry.id)).toEqual(["assigned"]);+ expect(sections[1]?.bots.map((entry) => entry.id)).toEqual(["free"]);+ });+});++describe("buildRosterStrip", () => {+ it("hides archived bots and puts pinned bots first without recency sorting", () => {+ const strip = buildRosterStrip(+ [+ bot({ id: "quiet", name: "Quiet" }),+ bot({ id: "gone", name: "Gone", archivedAt: "2026-08-20T00:00:00.000Z" }),+ bot({ id: "pinned", name: "Pinned", pinned: true }),+ bot({ id: "busy", name: "Busy" }),+ ],+ { busy: { text: "hi", at: "2026-08-27T10:00:00.000Z" } },+ );+ expect(strip.map((entry) => entry.id)).toEqual(["pinned", "quiet", "busy"]);+ });+});++describe("buildRosterTiles", () => {+ it("shows at most five recent bots without limiting the rail", () => {+ const bots = Array.from({ length: 7 }, (_, index) =>+ bot({ id: `bot-${index}`, name: `Bot ${index}`, pinned: true }),+ );+ const messages = Object.fromEntries(+ bots.map((entry, index) => [+ entry.id,+ { text: `${index}`, at: `2026-08-${String(index + 1).padStart(2, "0")}T10:00:00.000Z` },+ ]),+ );++ expect(buildRosterTiles(bots, messages).map((entry) => entry.id)).toEqual([+ "bot-0",+ "bot-1",+ "bot-2",+ "bot-3",+ "bot-4",+ ]);+ expect(buildRosterStrip(bots, messages)).toHaveLength(7);+ });+});++describe("filterRosterBots", () => {+ const bots = [+ bot({ id: "1", name: "Akeru", label: "Research", description: "Finds evidence" }),+ bot({ id: "2", name: "Mori", label: "Design", description: "Reviews interfaces" }),+ ];++ it("matches everything on a blank query", () => {+ expect(filterRosterBots(bots, " ").map((entry) => entry.id)).toEqual(["1", "2"]);+ });++ it("matches the bot profile case-insensitively", () => {+ expect(filterRosterBots(bots, "MORI").map((entry) => entry.id)).toEqual(["2"]);+ expect(filterRosterBots(bots, "research").map((entry) => entry.id)).toEqual(["1"]);+ expect(filterRosterBots(bots, "interfaces").map((entry) => entry.id)).toEqual(["2"]);+ expect(filterRosterBots(bots, "nobody")).toEqual([]);+ });+});++describe("randomBotAvatar", () => {+ it("returns a valid blob and never picks white", () => {+ for (let i = 0; i < 20; i++) {+ const avatar = randomBotAvatar(() => i / 20);+ expect(avatar.kind).toBe("blob");+ if (avatar.kind !== "blob") continue;+ expect(BLOB_SHAPES).toContain(avatar.shape);+ expect(BLOB_COLORS).toContain(avatar.color);+ expect(avatar.color).not.toBe("#FFFFFF");+ }+ });++ it("is deterministic for an injected random source", () => {+ expect(randomBotAvatar(() => 0)).toEqual(randomBotAvatar(() => 0));+ });+});++describe("resolveRosterIndicator", () => {+ it("shows yellow for needs-you, green for working, and nothing for idle", () => {+ expect(resolveRosterIndicator("needs-you")).toBe("needs-you");+ expect(resolveRosterIndicator("working")).toBe("working");+ expect(resolveRosterIndicator("idle")).toBeNull();+ });+});++describe("resolveBotPresence", () => {+ const shell = (input: {+ status?: string;+ activeTurnId?: string | null;+ hasPendingApprovals?: boolean;+ hasPendingUserInput?: boolean;+ backgroundLiveness?: "working" | "monitoring" | null;+ }) =>+ ({+ session:+ input.status === undefined+ ? null+ : { status: input.status, activeTurnId: input.activeTurnId ?? null },+ hasPendingApprovals: input.hasPendingApprovals ?? false,+ hasPendingUserInput: input.hasPendingUserInput ?? false,+ backgroundLiveness: input.backgroundLiveness ?? null,+ }) as Parameters<typeof resolveBotPresence>[0];++ it("is idle without a linked thread or running turn", () => {+ expect(resolveBotPresence(null)).toBe("idle");+ expect(resolveBotPresence(shell({}))).toBe("idle");+ expect(resolveBotPresence(shell({ status: "running", activeTurnId: null }))).toBe("idle");+ expect(resolveBotPresence(shell({ status: "ready" }))).toBe("idle");+ });++ it("works while a turn runs or background work stays live", () => {+ expect(resolveBotPresence(shell({ status: "running", activeTurnId: "turn-1" }))).toBe(+ "working",+ );+ expect(resolveBotPresence(shell({ backgroundLiveness: "working" }))).toBe("working");+ expect(resolveBotPresence(shell({ backgroundLiveness: "monitoring" }))).toBe("idle");+ });++ it("needs-you outranks a running turn", () => {+ expect(+ resolveBotPresence(+ shell({ status: "running", activeTurnId: "turn-1", hasPendingApprovals: true }),+ ),+ ).toBe("needs-you");+ expect(resolveBotPresence(shell({ hasPendingUserInput: true }))).toBe("needs-you");+ });+});++describe("resolveLatestRosterMessage", () => {+ const messages = (+ entries: Array<{ role: "user" | "assistant" | "system"; text: string; at: string }>,+ ) =>+ entries.map((entry, index) => ({+ id: `message-${index}`,+ role: entry.role,+ text: entry.text,+ turnId: null,+ streaming: false,+ createdAt: entry.at,+ updatedAt: entry.at,+ })) as Parameters<typeof resolveLatestRosterMessage>[1];++ it("uses the latest real user or provider message and its timestamp", () => {+ expect(+ resolveLatestRosterMessage(+ { text: "handoff", at: "2026-08-20T10:00:00.000Z" },+ messages([+ { role: "user", text: "Question", at: "2026-08-20T10:01:00.000Z" },+ { role: "assistant", text: "Answer", at: "2026-08-20T10:02:00.000Z" },+ ]),+ ),+ ).toEqual({ text: "Answer", at: "2026-08-20T10:02:00.000Z" });+ });++ it("keeps a newer handoff preview and ignores system or empty messages", () => {+ const fallback = { text: "Newest prompt", at: "2026-08-20T10:03:00.000Z" };+ expect(+ resolveLatestRosterMessage(+ fallback,+ messages([+ { role: "assistant", text: "Older answer", at: "2026-08-20T10:02:00.000Z" },+ { role: "system", text: "Internal", at: "2026-08-20T10:04:00.000Z" },+ { role: "assistant", text: "", at: "2026-08-20T10:05:00.000Z" },+ ]),+ ),+ ).toEqual(fallback);+ });+});++describe("compareRosterBots", () => {+ const lastMessageByBotId: Record<string, RosterLastMessage> = {+ older: { text: "old", at: "2026-08-25T10:00:00.000Z" },+ newer: { text: "new", at: "2026-08-27T10:00:00.000Z" },+ };++ it("sorts the latest conversation first", () => {+ const sorted = [bot({ id: "older", name: "Older" }), bot({ id: "newer", name: "Newer" })].sort(+ (a, b) => compareRosterBots(a, b, lastMessageByBotId),+ );+ expect(sorted.map((entry) => entry.id)).toEqual(["newer", "older"]);+ });++ it("puts bots without messages after those with, alphabetized", () => {+ const sorted = [+ bot({ id: "quiet-b", name: "Zed" }),+ bot({ id: "older", name: "Older" }),+ bot({ id: "quiet-a", name: "Ada" }),+ ].sort((a, b) => compareRosterBots(a, b, lastMessageByBotId));+ expect(sorted.map((entry) => entry.id)).toEqual(["older", "quiet-a", "quiet-b"]);+ });++ it("treats an unparseable timestamp as no message", () => {+ const sorted = [+ bot({ id: "broken", name: "Broken" }),+ bot({ id: "older", name: "Older" }),+ ].sort((a, b) =>+ compareRosterBots(a, b, {+ ...lastMessageByBotId,+ broken: { text: "?", at: "not-a-date" },+ }),+ );+ expect(sorted.map((entry) => entry.id)).toEqual(["older", "broken"]);+ });+});++describe("resolveBlobRendering", () => {+ it("passes a valid blob avatar through", () => {+ expect(resolveBlobRendering({ kind: "blob", shape: "hex", color: "#5BA97B" })).toEqual({+ shape: "hex",+ color: "#5BA97B",+ });+ });++ it("falls back to the default blob for non-blob kinds", () => {+ expect(resolveBlobRendering({ kind: "dither", seed: "abc" })).toEqual({+ shape: DEFAULT_BLOB_SHAPE,+ color: DEFAULT_BLOB_COLOR,+ });+ expect(resolveBlobRendering({ kind: "image", assetPath: "/a.png", dithered: false })).toEqual({+ shape: DEFAULT_BLOB_SHAPE,+ color: DEFAULT_BLOB_COLOR,+ });+ expect(resolveBlobRendering(null)).toEqual({+ shape: DEFAULT_BLOB_SHAPE,+ color: DEFAULT_BLOB_COLOR,+ });+ });++ it("falls back for an unknown shape or empty color from persisted data", () => {+ const persisted = { kind: "blob", shape: "starburst", color: "" } as unknown as BotAvatar;+ expect(resolveBlobRendering(persisted)).toEqual({+ shape: DEFAULT_BLOB_SHAPE,+ color: DEFAULT_BLOB_COLOR,+ });+ });++ it("falls back for a retired shape name", () => {+ const persisted = { kind: "blob", shape: "pebble", color: "#FFFFFF" } as unknown as BotAvatar;+ expect(resolveBlobRendering(persisted)).toEqual({+ shape: DEFAULT_BLOB_SHAPE,+ color: "#FFFFFF",+ });+ });+});++describe("blinkDelayMs", () => {+ it("is a stable phase offset within one blink cycle", () => {+ expect(blinkDelayMs("Akeru")).toBe(blinkDelayMs("Akeru"));+ expect(blinkDelayMs("Akeru")).toBeLessThanOrEqual(0);+ expect(blinkDelayMs("Akeru")).toBeGreaterThan(-6400);+ });++ it("staggers different bots", () => {+ expect(blinkDelayMs("Akeru")).not.toBe(blinkDelayMs("Mori"));+ });+});++describe("formatRosterTimestamp", () => {+ const now = new Date("2026-08-27T15:00:00").getTime();++ it("shows a clock time today, Yesterday, then weekday, then date", () => {+ expect(formatRosterTimestamp("2026-08-27T09:30:00", "24-hour", now)).toBe("09:30");+ expect(formatRosterTimestamp("2026-08-26T09:30:00", "24-hour", now)).toBe("Yesterday");+ expect(formatRosterTimestamp("2026-08-24T09:30:00", "24-hour", now)).not.toContain(":");+ expect(formatRosterTimestamp("2026-01-02T09:30:00", "24-hour", now)).toContain("2");+ });++ it("returns empty for an invalid date", () => {+ expect(formatRosterTimestamp("nope", "24-hour", now)).toBe("");+ });+});++describe("parseChatPath", () => {+ it("parses a legacy server thread route", () => {+ expect(parseChatPath("/env-1/thread-9")).toEqual({+ kind: "thread",+ environmentId: "env-1",+ threadId: "thread-9",+ });+ });++ it("rejects non-chat routes", () => {+ expect(isRecordableChatPath("/")).toBe(false);+ expect(isRecordableChatPath("/settings/appearance")).toBe(false);+ expect(isRecordableChatPath("/projects/my-project")).toBe(false);+ expect(isRecordableChatPath("/bots/bot-akeru")).toBe(false);+ expect(isRecordableChatPath("/draft/draft-123")).toBe(false);+ expect(isRecordableChatPath("/usage")).toBe(false);+ });+});diff --git a/apps/web/src/components/roster/roster.logic.ts b/apps/web/src/components/roster/roster.logic.tsnew file mode 100644index 000000000..96d4ad5a8--- /dev/null+++ b/apps/web/src/components/roster/roster.logic.ts@@ -0,0 +1,326 @@+import type { OrchestrationThreadShell } from "@t3tools/contracts";+import type { TimestampFormat } from "@t3tools/contracts/settings";+import { formatShortTimestamp, parseTimestampDate } from "../../timestampFormat";+import type { Bot, BotAvatar, BotBlobShape, Group } from "./types";++export const BLOB_SHAPES: readonly BotBlobShape[] = [+ "circle",+ "squircle",+ "square",+ "pill",+ "triangle",+ "hex",+ "cloud",+ "drop",+];++export const BLOB_COLORS: readonly string[] = [+ "#FFFFFF",+ "#E0645C",+ "#E8883A",+ "#D9A833",+ "#5BA97B",+ "#4E9BB8",+ "#5B7FD4",+ "#8B6FC9",+ "#C96FA8",+ "#7A8699",+];++export const DEFAULT_BLOB_SHAPE: BotBlobShape = "circle";+export const DEFAULT_BLOB_COLOR = "#7A8699";++export function isBotBlobShape(value: string): value is BotBlobShape {+ return (BLOB_SHAPES as readonly string[]).includes(value);+}++/**+ * Every avatar kind resolves to a paintable blob so the roster never renders+ * an empty slot: dither and image avatars (and any unknown blob shape coming+ * from persisted or server data) fall back to the default circle blob until+ * their real renderer applies.+ */+export function resolveBlobRendering(avatar: BotAvatar | null | undefined): {+ shape: BotBlobShape;+ color: string;+} {+ if (avatar?.kind !== "blob") {+ return { shape: DEFAULT_BLOB_SHAPE, color: DEFAULT_BLOB_COLOR };+ }+ // Unknown names (including the retired creature set) fall back to the+ // default circle rather than an empty slot.+ return {+ shape: isBotBlobShape(avatar.shape) ? avatar.shape : DEFAULT_BLOB_SHAPE,+ color: avatar.color || DEFAULT_BLOB_COLOR,+ };+}++/**+ * Random blob avatar for a freshly created bot. White is excluded so an+ * auto-assigned body never washes out on the light sidebar; it stays+ * pickable in the avatar picker. `random` is injectable for tests.+ */+export function randomBotAvatar(+ random: () => number = Math.random,+): Extract<BotAvatar, { kind: "blob" }> {+ const colors = BLOB_COLORS.filter((color) => color !== "#FFFFFF");+ const shape = BLOB_SHAPES[Math.floor(random() * BLOB_SHAPES.length)] ?? DEFAULT_BLOB_SHAPE;+ const color = colors[Math.floor(random() * colors.length)] ?? DEFAULT_BLOB_COLOR;+ return { kind: "blob", shape, color };+}++/** What a bot is up to right now, driving the avatar animation and indicator. */+export type RosterPresence = "idle" | "working" | "needs-you";++/** Only live bot states get a light; row selection already marks the active bot. */+export function resolveRosterIndicator(presence: RosterPresence): "needs-you" | "working" | null {+ if (presence === "working") return "working";+ if (presence === "needs-you") return "needs-you";+ return null;+}++type PresenceShell = Pick<+ OrchestrationThreadShell,+ "session" | "hasPendingApprovals" | "hasPendingUserInput" | "backgroundLiveness"+>;++/**+ * Presence for the thread a bot's chat points at. Pending approvals or user+ * input outrank a running turn: the bot is waiting on you, not working. The+ * running test mirrors the legacy sidebar's working indicator; background+ * liveness keeps the bot working while subagents or workflows run on after+ * the turn settles.+ */+export function resolveBotPresence(shell: PresenceShell | null): RosterPresence {+ if (shell === null) return "idle";+ if (shell.hasPendingApprovals || shell.hasPendingUserInput) return "needs-you";+ if (shell.session?.status === "running" && shell.session.activeTurnId != null) return "working";+ if (shell.backgroundLiveness === "working") return "working";+ return "idle";+}++/**+ * Phase offset for the idle blink, so a roster full of bots never blinks in+ * sync. Negative so the animation starts mid-cycle. The modulo must match the+ * `bot-blink` duration in index.css.+ */+export function blinkDelayMs(seed: string): number {+ let hash = 0;+ for (let i = 0; i < seed.length; i++) hash = (hash * 31 + seed.charCodeAt(i)) | 0;+ return -(Math.abs(hash) % 6400);+}++export function resolveRosterBotId(+ selectedBotId: string | null,+ bots: ReadonlyArray<Pick<Bot, "id" | "archivedAt">>,+): string | null {+ if (+ selectedBotId !== null &&+ bots.some((bot) => bot.id === selectedBotId && bot.archivedAt === null)+ ) {+ return selectedBotId;+ }+ return bots.find((bot) => bot.archivedAt === null)?.id ?? null;+}++export interface RosterLastMessage {+ text: string;+ at: string;+}++export function resolveLatestRosterMessage(+ fallback: RosterLastMessage | null,+ messages: ReadonlyArray<{+ role: "user" | "assistant" | "system";+ text: string;+ createdAt: string;+ }>,+): RosterLastMessage | null {+ let latest: RosterLastMessage | null = null;+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];+ if (message && message.role !== "system" && message.text.trim().length > 0) {+ latest = { text: message.text, at: message.createdAt };+ break;+ }+ }+ if (!latest) return fallback;+ if (!fallback) return latest;+ return latest.at >= fallback.at ? latest : fallback;+}++export interface RosterSection {+ id: "pinned" | "unpinned";+ name: "Pinned" | "Bots";+ bots: Bot[];+}++function lastMessageSortValue(+ bot: Bot,+ lastMessageByBotId: Readonly<Record<string, RosterLastMessage>>,+): number | null {+ const at = lastMessageByBotId[bot.id]?.at;+ if (at === undefined) return null;+ return parseTimestampDate(at)?.getTime() ?? null;+}++/** Latest conversation first; bots without messages trail, alphabetized. */+export function compareRosterBots(+ a: Bot,+ b: Bot,+ lastMessageByBotId: Readonly<Record<string, RosterLastMessage>>,+): number {+ const aAt = lastMessageSortValue(a, lastMessageByBotId);+ const bAt = lastMessageSortValue(b, lastMessageByBotId);+ if (aAt !== null && bAt !== null && aAt !== bAt) return bAt - aAt;+ if (aAt !== null && bAt === null) return -1;+ if (aAt === null && bAt !== null) return 1;+ return a.name.localeCompare(b.name, undefined, { sensitivity: "base" });+}++type RosterSectionsInput = readonly Bot[] | { bots: readonly Bot[] };++function isPreviousRosterSectionsInput(+ input: RosterSectionsInput,+): input is { bots: readonly Bot[] } {+ return !Array.isArray(input);+}++/**+ * Pinned and unpinned bots keep their persisted order within each section.+ * The object form covers a previous caller that can remain mounted during HMR.+ */+export function buildRosterSections(input: RosterSectionsInput): RosterSection[] {+ const bots = isPreviousRosterSectionsInput(input) ? input.bots : input;+ const visibleBots = bots.filter((bot) => bot.archivedAt === null);+ const pinned = visibleBots.filter((bot) => bot.pinned);+ const unpinned = visibleBots.filter((bot) => !bot.pinned);+ return [+ ...(pinned.length > 0 ? [{ id: "pinned", name: "Pinned", bots: pinned } as const] : []),+ ...(unpinned.length > 0 ? [{ id: "unpinned", name: "Bots", bots: unpinned } as const] : []),+ ];+}++export const ROSTER_TILE_LIMIT = 5;++/** Visible bots, pinned first, with persisted order preserved in each partition. */+export function buildRosterStrip(+ bots: readonly Bot[],+ _lastMessageByBotId: Readonly<Record<string, RosterLastMessage>>,+): Bot[] {+ const visible = bots.filter((bot) => bot.archivedAt === null);+ return [...visible.filter((bot) => bot.pinned), ...visible.filter((bot) => !bot.pinned)];+}++/** The expanded roster shows pinned bots in a fixed grid, never a carousel. */+export function buildRosterTiles(+ bots: readonly Bot[],+ _lastMessageByBotId: Readonly<Record<string, RosterLastMessage>>,+): Bot[] {+ return bots.filter((bot) => bot.archivedAt === null && bot.pinned).slice(0, ROSTER_TILE_LIMIT);+}++export function filterRosterBots(bots: readonly Bot[], query: string): Bot[] {+ const needle = query.trim().toLowerCase();+ if (needle.length === 0) return [...bots];+ return bots.filter(+ (bot) =>+ bot.name.toLowerCase().includes(needle) ||+ (bot.label?.toLowerCase().includes(needle) ?? false) ||+ (bot.description?.toLowerCase().includes(needle) ?? false),+ );+}++export interface RosterGroupSection {+ readonly id: string;+ readonly name: string;+ readonly bots: ReadonlyArray<Bot>;+}++/** Assigned groups first, then every bot without a group under Unassigned. */+export function buildGroupedRosterSections(+ bots: ReadonlyArray<Bot>,+ groups: ReadonlyArray<Group>,+): ReadonlyArray<RosterGroupSection> {+ const active = bots.filter((bot) => bot.archivedAt === null && bot.pinned === false);+ const assigned = groups.flatMap((group) => {+ const groupBots = active.filter((bot) => bot.groupId === group.id);+ return groupBots.length > 0 ? [{ id: group.id, name: group.name, bots: groupBots }] : [];+ });+ const unassigned = active.filter((bot) => bot.groupId === null);+ return [+ ...assigned,+ ...(unassigned.length > 0 ? [{ id: "unassigned", name: "Unassigned", bots: unassigned }] : []),+ ];+}++const weekdayFormatter = new Intl.DateTimeFormat(undefined, { weekday: "short" });+const numericDateFormatter = new Intl.DateTimeFormat(undefined, {+ month: "numeric",+ day: "numeric",+});+const numericDateWithYearFormatter = new Intl.DateTimeFormat(undefined, {+ month: "numeric",+ day: "numeric",+ year: "numeric",+});++/**+ * Compact roster timestamp, iMessage-style: today shows the clock time,+ * yesterday "Yesterday", the rest of the past week its weekday, older dates+ * the numeric date (with the year once the calendar year differs).+ */+export function formatRosterTimestamp(+ isoDate: string,+ timestampFormat: TimestampFormat,+ nowMs: number = Date.now(),+): string {+ const date = parseTimestampDate(isoDate);+ if (!date) return "";++ const now = new Date(nowMs);+ const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();+ const startOfMessageDay = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();+ const dayDiff = Math.round((startOfToday - startOfMessageDay) / 86_400_000);++ if (dayDiff <= 0) return formatShortTimestamp(isoDate, timestampFormat);+ if (dayDiff === 1) return "Yesterday";+ if (dayDiff < 7) return weekdayFormatter.format(date);+ return date.getFullYear() === now.getFullYear()+ ? numericDateFormatter.format(date)+ : numericDateWithYearFormatter.format(date);+}++// Route prefixes that also produce one- or two-segment paths but are never a+// chat. Everything else with two segments is /$environmentId/$threadId.+const NON_CHAT_ROUTE_PREFIXES = new Set([+ "settings",+ "projects",+ "bots",+ "connect",+ "draft",+ "pair",+ "usage",+]);++export type RosterChatTarget = {+ kind: "thread";+ environmentId: string;+ threadId: string;+};++/**+ * Parses the legacy /$environmentId/$threadId path cached for a bot.+ * The bot page stays canonical and uses this only to recover thread identity.+ */+export function parseChatPath(pathname: string): RosterChatTarget | null {+ const segments = pathname.split("/").filter((segment) => segment.length > 0);+ if (segments.length !== 2) return null;+ if (NON_CHAT_ROUTE_PREFIXES.has(segments[0]!)) return null;+ return { kind: "thread", environmentId: segments[0]!, threadId: segments[1]! };+}++/** True when a pathname is a chat route worth remembering for a bot. */+export function isRecordableChatPath(pathname: string): boolean {+ return parseChatPath(pathname) !== null;+}diff --git a/apps/web/src/components/roster/rosterStore.test.ts b/apps/web/src/components/roster/rosterStore.test.tsnew file mode 100644index 000000000..37a93cda2--- /dev/null+++ b/apps/web/src/components/roster/rosterStore.test.ts@@ -0,0 +1,133 @@+import { afterEach, beforeEach, describe, expect, it } from "vite-plus/test";++import { useRosterStore } from "./rosterStore";+import type { Bot } from "./types";++function bot(id: string, archivedAt: string | null = null): Bot {+ return {+ id,+ name: id,+ title: "Assistant",+ label: null,+ description: null,+ disabledMcpServerIds: [],+ avatar: { kind: "blob", shape: "circle", color: "#5B7FD4" },+ engine: null,+ sandbox: null,+ runtimeMode: "full-access",+ usageCap: null,+ groupId: null,+ pinned: false,+ archivedAt,+ createdAt: "2026-08-01T00:00:00.000Z",+ updatedAt: "2026-08-01T00:00:00.000Z",+ };+}++const initialState = useRosterStore.getState();++beforeEach(() => {+ useRosterStore.setState({+ bots: [],+ groups: [],+ lastMessageByBotId: {},+ selectedBotId: null,+ chatPathByBotId: {},+ });+});++afterEach(() => {+ useRosterStore.setState({+ bots: initialState.bots,+ groups: initialState.groups,+ lastMessageByBotId: initialState.lastMessageByBotId,+ selectedBotId: initialState.selectedBotId,+ chatPathByBotId: initialState.chatPathByBotId,+ });+ if (typeof window !== "undefined") {+ window.localStorage.removeItem("akeru:roster:v1");+ }+});++describe("bot selection", () => {+ it("selects the first available bot when a roster arrives without the active bot", () => {+ useRosterStore.setState({ selectedBotId: "missing" });+ useRosterStore.getState().replaceRoster({+ bots: [bot("archived", "2026-08-20T00:00:00.000Z"), bot("akeru")],+ groups: [],+ });++ expect(useRosterStore.getState().selectedBotId).toBe("akeru");+ });++ it("updates a bot's roster preview after a local message", () => {+ const message = { text: "Ship it", at: "2026-08-20T00:00:00.000Z" };++ useRosterStore.getState().recordLastMessage("akeru", message);++ expect(useRosterStore.getState().lastMessageByBotId.akeru).toEqual(message);+ });++ it("keeps each bot's remembered thread path", () => {+ useRosterStore.getState().recordChatPath("akeru", "/env-1/thread-1");+ useRosterStore.getState().recordChatPath("mori", "/draft/draft-2");++ expect(useRosterStore.getState().chatPathByBotId).toEqual({+ akeru: "/env-1/thread-1",+ mori: "/draft/draft-2",+ });++ useRosterStore.getState().forgetChatPath("akeru");+ expect(useRosterStore.getState().chatPathByBotId).toEqual({+ mori: "/draft/draft-2",+ });+ });+});++describe("pin and order", () => {+ it("pins and unpins only on a completed partition move", () => {+ useRosterStore.setState({ bots: [bot("one"), bot("two"), bot("three")] });++ useRosterStore.getState().moveBot("two", null, true);+ expect(useRosterStore.getState().bots.map(({ id, pinned }) => [id, pinned])).toEqual([+ ["two", true],+ ["one", false],+ ["three", false],+ ]);++ useRosterStore.getState().moveBot("two", null, false);+ expect(useRosterStore.getState().bots.map(({ id, pinned }) => [id, pinned])).toEqual([+ ["one", false],+ ["three", false],+ ["two", false],+ ]);+ });++ it("reorders both partitions and supports valid cross-partition drops", () => {+ useRosterStore.setState({+ bots: [+ { ...bot("pin-a"), pinned: true },+ { ...bot("pin-b"), pinned: true },+ bot("plain-a"),+ bot("plain-b"),+ ],+ });++ useRosterStore.getState().moveBot("pin-b", "pin-a", true);+ useRosterStore.getState().moveBot("plain-b", "plain-a", false);+ useRosterStore.getState().moveBot("plain-a", "pin-a", true);+ expect(useRosterStore.getState().bots.map(({ id, pinned }) => [id, pinned])).toEqual([+ ["pin-b", true],+ ["plain-a", true],+ ["pin-a", true],+ ["plain-b", false],+ ]);+ });++ it("ignores an invalid cross-partition target", () => {+ useRosterStore.setState({ bots: [{ ...bot("pinned"), pinned: true }, bot("plain")] });++ useRosterStore.getState().moveBot("pinned", "plain", true);+ expect(useRosterStore.getState().bots.map((entry) => entry.id)).toEqual(["pinned", "plain"]);+ });+});diff --git a/apps/web/src/components/roster/rosterStore.ts b/apps/web/src/components/roster/rosterStore.tsnew file mode 100644index 000000000..d6644c505--- /dev/null+++ b/apps/web/src/components/roster/rosterStore.ts@@ -0,0 +1,225 @@+import { create } from "zustand";++import type { RosterLastMessage } from "./roster.logic";+import type { Bot, BotAvatar, Group } from "./types";++const PERSISTED_ROSTER_KEY = "akeru:roster:v1";++interface PersistedRoster {+ selectedBotId?: string;+ chatPathByBotId?: Record<string, string>;+ botLayout?: Array<{ id: string; pinned: boolean }>;+}++function firstAvailableBotId(bots: readonly Bot[]): string | null {+ return bots.find((bot) => bot.archivedAt === null)?.id ?? null;+}++function readPersistedRoster(): PersistedRoster | null {+ if (typeof window === "undefined") return null;+ try {+ const raw = window.localStorage.getItem(PERSISTED_ROSTER_KEY);+ if (raw === null) return null;+ const parsed: unknown = JSON.parse(raw);+ if (typeof parsed !== "object" || parsed === null) return null;+ const { selectedBotId, chatPathByBotId, botLayout } = parsed as {+ selectedBotId?: unknown;+ chatPathByBotId?: unknown;+ botLayout?: unknown;+ };+ return {+ ...(typeof selectedBotId === "string" ? { selectedBotId } : {}),+ ...(typeof chatPathByBotId === "object" && chatPathByBotId !== null+ ? { chatPathByBotId: chatPathByBotId as Record<string, string> }+ : {}),+ ...(Array.isArray(botLayout) &&+ botLayout.every(+ (entry) =>+ typeof entry === "object" &&+ entry !== null &&+ typeof (entry as { id?: unknown }).id === "string" &&+ typeof (entry as { pinned?: unknown }).pinned === "boolean",+ )+ ? { botLayout: botLayout as Array<{ id: string; pinned: boolean }> }+ : {}),+ };+ } catch {+ return null;+ }+}++function persistRoster(roster: PersistedRoster): void {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(PERSISTED_ROSTER_KEY, JSON.stringify(roster));+ } catch (error) {+ console.error("Could not persist bot roster.", error);+ }+}++interface RosterStore {+ bots: Bot[];+ groups: Group[];+ lastMessageByBotId: Record<string, RosterLastMessage>;+ selectedBotId: string | null;+ chatPathByBotId: Record<string, string>;+ selectBot: (botId: string) => void;+ setBotAvatar: (botId: string, avatar: BotAvatar) => boolean;+ moveBot: (activeBotId: string, overBotId: string | null, pinned: boolean) => void;+ commitBotLayout: (bots: Bot[]) => void;+ recordLastMessage: (botId: string, message: RosterLastMessage) => void;+ recordChatPath: (botId: string, path: string) => void;+ forgetChatPath: (botId: string) => void;+ replaceRoster: (input: {+ bots: Bot[];+ groups: Group[];+ lastMessageByBotId?: Record<string, RosterLastMessage>;+ }) => void;+}++export function moveRosterBot(+ bots: readonly Bot[],+ activeBotId: string,+ overBotId: string | null,+ pinned: boolean,+): Bot[] | null {+ const active = bots.find((bot) => bot.id === activeBotId);+ const over = overBotId ? bots.find((bot) => bot.id === overBotId) : null;+ if (!active || active.archivedAt !== null) return null;+ if (over && (over.archivedAt !== null || over.pinned !== pinned)) return null;+ if (active.id === over?.id && active.pinned === pinned) return null;++ const moved = { ...active, pinned };+ const next = bots.filter((bot) => bot.id !== activeBotId);+ if (over) {+ const overIndex = next.findIndex((bot) => bot.id === over.id);+ next.splice(overIndex, 0, moved);+ } else {+ const partitionEnd = next.findLastIndex((bot) => bot.pinned === pinned);+ next.splice(partitionEnd + 1, 0, moved);+ }+ return next;+}++function saveState(state: Pick<RosterStore, "bots" | "selectedBotId" | "chatPathByBotId">) {+ persistRoster({+ ...(state.selectedBotId === null ? {} : { selectedBotId: state.selectedBotId }),+ chatPathByBotId: state.chatPathByBotId,+ botLayout: state.bots.map((bot) => ({ id: bot.id, pinned: bot.pinned })),+ });+}++const persisted = readPersistedRoster();++export const useRosterStore = create<RosterStore>((set, get) => ({+ bots: [],+ groups: [],+ lastMessageByBotId: {},+ selectedBotId: persisted?.selectedBotId ?? null,+ chatPathByBotId: persisted?.chatPathByBotId ?? {},++ selectBot: (botId) => {+ if (!get().bots.some((bot) => bot.id === botId && bot.archivedAt === null)) return;+ if (get().selectedBotId === botId) return;+ set({ selectedBotId: botId });+ saveState(get());+ },++ setBotAvatar: (botId, avatar) => {+ set((state) => ({+ bots: state.bots.map((bot) =>+ bot.id === botId ? { ...bot, avatar, updatedAt: new Date().toISOString() } : bot,+ ),+ }));+ saveState(get());+ return true;+ },++ moveBot: (activeBotId, overBotId, pinned) => {+ const current = get().bots;+ const bots = moveRosterBot(current, activeBotId, overBotId, pinned);+ if (!bots) return;+ const active = current.find((bot) => bot.id === activeBotId);+ const nextBots = bots.map((bot) =>+ bot.id === activeBotId && active?.pinned !== pinned+ ? { ...bot, updatedAt: new Date().toISOString() }+ : bot,+ );+ set({ bots: nextBots });+ saveState(get());+ },++ commitBotLayout: (bots) => {+ const current = get().bots;+ if (+ bots.length !== current.length ||+ new Set(bots.map((bot) => bot.id)).size !== bots.length ||+ bots.some((bot) => !current.some((candidate) => candidate.id === bot.id))+ ) {+ return;+ }+ const currentById = new Map(current.map((bot) => [bot.id, bot]));+ const committed = bots.map((bot) => {+ const previous = currentById.get(bot.id)!;+ return previous.pinned === bot.pinned+ ? previous+ : { ...previous, pinned: bot.pinned, updatedAt: new Date().toISOString() };+ });+ set({ bots: committed });+ saveState(get());+ },++ recordLastMessage: (botId, message) => {+ set((state) => ({ lastMessageByBotId: { ...state.lastMessageByBotId, [botId]: message } }));+ },++ recordChatPath: (botId, path) => {+ if (get().chatPathByBotId[botId] === path) return;+ set((state) => ({ chatPathByBotId: { ...state.chatPathByBotId, [botId]: path } }));+ saveState(get());+ },++ forgetChatPath: (botId) => {+ if (get().chatPathByBotId[botId] === undefined) return;+ const chatPathByBotId = { ...get().chatPathByBotId };+ delete chatPathByBotId[botId];+ set({ chatPathByBotId });+ saveState(get());+ },++ replaceRoster: (input) => {+ const currentLayout =+ get().bots.length > 0+ ? get().bots.map((bot) => ({ id: bot.id, pinned: bot.pinned }))+ : (persisted?.botLayout ?? []);+ const orderById = new Map(currentLayout.map((entry, index) => [entry.id, index] as const));+ const pinnedById = new Map(currentLayout.map((entry) => [entry.id, entry.pinned] as const));+ const bots = input.bots+ .map((bot) => ({ ...bot, pinned: pinnedById.get(bot.id) ?? false }))+ .sort(+ (left, right) =>+ (orderById.get(left.id) ?? Number.MAX_SAFE_INTEGER) -+ (orderById.get(right.id) ?? Number.MAX_SAFE_INTEGER),+ );+ const selectedBotId = bots.some(+ (bot) => bot.id === get().selectedBotId && bot.archivedAt === null,+ )+ ? get().selectedBotId+ : firstAvailableBotId(bots);+ set({+ bots,+ groups: input.groups,+ selectedBotId,+ ...(input.lastMessageByBotId ? { lastMessageByBotId: input.lastMessageByBotId } : {}),+ });+ saveState(get());+ },+}));++export function useSelectedBot(): Bot | null {+ return useRosterStore((state) =>+ state.selectedBotId === null+ ? null+ : (state.bots.find((bot) => bot.id === state.selectedBotId) ?? null),+ );+}diff --git a/apps/web/src/components/roster/types.ts b/apps/web/src/components/roster/types.tsnew file mode 100644index 000000000..2e66653cd--- /dev/null+++ b/apps/web/src/components/roster/types.ts@@ -0,0 +1,51 @@+import type { McpServerId } from "@t3tools/contracts";++/**+ * Local mirror of the bot roster wire shape the server-side persistence work+ * is building in parallel. Field-for-field identical so integration becomes a+ * type-import swap to `@t3tools/contracts`; do not diverge from that shape+ * here.+ */++export type BotBlobShape =+ | "circle"+ | "squircle"+ | "square"+ | "pill"+ | "triangle"+ | "hex"+ | "cloud"+ | "drop";++export type BotAvatar =+ | { kind: "blob"; shape: BotBlobShape; color: string }+ | { kind: "dither"; seed: string }+ | { kind: "image"; assetPath: string; dithered: boolean };++export interface Bot {+ id: string;+ name: string;+ title: string;+ label: string | null;+ description: string | null;+ disabledMcpServerIds: readonly McpServerId[];+ avatar: BotAvatar;+ engine: { provider: string; model: string } | null;+ sandbox: "local" | "vercel" | "akeru-cloud" | "upstash" | null;+ runtimeMode: "approval-required" | "auto-accept-edits" | "auto" | "full-access";+ usageCap: { unit: "tokens"; limit: number } | null;+ groupId: string | null;+ pinned: boolean;+ archivedAt: string | null;+ createdAt: string;+ updatedAt: string;+}++export interface Group {+ id: string;+ name: string;+ bossBotId: string | null;+ members: ReadonlyArray<{ botId: string; role: "boss" | "specialist" }>;+ createdAt: string;+ updatedAt: string;+}diff --git a/apps/web/src/components/roster/useBotThreadRuntime.ts b/apps/web/src/components/roster/useBotThreadRuntime.tsnew file mode 100644index 000000000..6eb043635--- /dev/null+++ b/apps/web/src/components/roster/useBotThreadRuntime.ts@@ -0,0 +1,242 @@+import { useAtomValue } from "@effect/atom-react";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";+import {+ BotId,+ DEFAULT_RUNTIME_MODE,+ EnvironmentId,+ ThreadId,+ type ModelSelection,+ type ScopedThreadRef,+} from "@t3tools/contracts";+import { useCallback, useMemo, useRef, useState } from "react";++import { usePrimarySettings } from "../../hooks/useSettings";+import { DEFAULT_INTERACTION_MODE } from "../../types";+import { newMessageId, newThreadId } from "../../lib/utils";+import { resolveAppModelSelectionState } from "../../modelSelection";+import {+ useAllEnvironmentShellsBootstrapped,+ useProjects,+ useThreadMessages,+ useThreadShell,+ useThreadShells,+} from "../../state/entities";+import { environmentBotsAtom } from "../../state/bots";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { primaryServerProvidersAtom } from "../../state/server";+import { threadEnvironment } from "../../state/threads";+import { useAtomCommand } from "../../state/use-atom-command";+import { sortScopedProjectsForSidebar } from "../Sidebar.logic";+import { buildBotTurnStartInput, findLatestBotThreadTarget } from "./botThreadRuntime.logic";+import { parseChatPath } from "./roster.logic";+import { useRosterStore } from "./rosterStore";++const NO_ENVIRONMENT = "" as EnvironmentId;++function errorMessage(result: Parameters<typeof squashAtomCommandFailure>[0]): string {+ const error = squashAtomCommandFailure(result);+ return error instanceof Error ? error.message : "Could not send the message.";+}++function threadTitle(prompt: string, files: readonly File[]): string {+ const seed = prompt || (files[0] ? `Image: ${files[0].name}` : "New thread");+ return seed.length > 80 ? `${seed.slice(0, 79)}…` : seed;+}++function readFileAsDataUrl(file: File): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.addEventListener(+ "error",+ () => reject(reader.error ?? new Error(`Could not read ${file.name}.`)),+ { once: true },+ );+ reader.addEventListener(+ "load",+ () =>+ typeof reader.result === "string"+ ? resolve(reader.result)+ : reject(new Error(`Could not read ${file.name}.`)),+ { once: true },+ );+ reader.readAsDataURL(file);+ });+}++export function useBotThreadRuntime(botId: string, effectiveModelSelection: ModelSelection | null) {+ const projects = useProjects();+ const primaryEnvironmentId = usePrimaryEnvironmentId();+ const serverBots = useAtomValue(environmentBotsAtom(primaryEnvironmentId ?? NO_ENVIRONMENT));+ const threadShells = useThreadShells();+ const bootstrapped = useAllEnvironmentShellsBootstrapped();+ const settings = usePrimarySettings();+ const providers = useAtomValue(primaryServerProvidersAtom);+ const rememberedPath = useRosterStore((state) => state.chatPathByBotId[botId]);+ const bot = useRosterStore((state) => state.bots.find((candidate) => candidate.id === botId));+ const target = rememberedPath ? parseChatPath(rememberedPath) : null;+ const primaryThreadShells = useMemo(+ () =>+ primaryEnvironmentId+ ? threadShells.filter((thread) => thread.environmentId === primaryEnvironmentId)+ : [],+ [primaryEnvironmentId, threadShells],+ );+ const serverTarget = primaryEnvironmentId+ ? findLatestBotThreadTarget(botId, primaryEnvironmentId, primaryThreadShells)+ : null;+ const rememberedThreadRef = useMemo<ScopedThreadRef | null>(() => {+ const candidate =+ serverTarget ??+ (target?.kind === "thread" && target.environmentId === primaryEnvironmentId ? target : null);+ return candidate+ ? scopeThreadRef(+ EnvironmentId.make(candidate.environmentId),+ ThreadId.make(candidate.threadId),+ )+ : null;+ }, [primaryEnvironmentId, serverTarget, target]);+ const rememberedThread = useThreadShell(rememberedThreadRef);+ const linkedThreadRef = rememberedThread ? rememberedThreadRef : null;+ const retainedThreadRef = useRef<{ botId: string; threadRef: ScopedThreadRef | null }>({+ botId,+ threadRef: null,+ });+ if (retainedThreadRef.current.botId !== botId) {+ retainedThreadRef.current = { botId, threadRef: null };+ }+ if (linkedThreadRef) {+ retainedThreadRef.current.threadRef = linkedThreadRef;+ }+ const messages = useThreadMessages(linkedThreadRef);+ const defaultProject = useMemo(+ () =>+ bootstrapped && primaryEnvironmentId+ ? (sortScopedProjectsForSidebar(+ projects.filter((project) => project.environmentId === primaryEnvironmentId),+ primaryThreadShells,+ "updated_at",+ )[0] ?? null)+ : null,+ [bootstrapped, primaryEnvironmentId, primaryThreadShells, projects],+ );+ const activeProject =+ projects.find(+ (project) =>+ project.environmentId === rememberedThread?.environmentId &&+ project.id === rememberedThread.projectId,+ ) ?? defaultProject;+ const appDefaultModelSelection = useMemo(+ () => resolveAppModelSelectionState(settings, providers),+ [providers, settings],+ );+ const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });+ const botReady = serverBots.some((candidate) => candidate.id === botId);+ const sendInFlightRef = useRef(false);+ const [sending, setSending] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const send = useCallback(+ async (prompt: string, files: readonly File[]): Promise<boolean> => {+ if (sendInFlightRef.current) return false;+ if (!botReady) {+ setError("The bot is still connecting.");+ return false;+ }+ if (!activeProject) {+ setError("Add a project before you message a bot.");+ return false;+ }+ const unsupported = files.find((file) => !file.type.startsWith("image/"));+ if (unsupported) {+ setError("Bot attachments must be images.");+ return false;+ }++ sendInFlightRef.current = true;+ setSending(true);+ setError(null);+ const createdAt = new Date().toISOString();+ const currentThreadRef = retainedThreadRef.current.threadRef;+ const threadId = currentThreadRef?.threadId ?? newThreadId();+ const modelSelection: ModelSelection =+ effectiveModelSelection ?? activeProject.defaultModelSelection ?? appDefaultModelSelection;+ const runtimeMode = bot?.runtimeMode ?? DEFAULT_RUNTIME_MODE;+ const title = threadTitle(prompt, files);++ try {+ const attachments = await Promise.all(+ files.map(async (file) => ({+ type: "image" as const,+ name: file.name,+ mimeType: file.type,+ sizeBytes: file.size,+ dataUrl: await readFileAsDataUrl(file),+ })),+ );+ const environmentId = currentThreadRef?.environmentId ?? activeProject.environmentId;+ const startResult = await startTurn({+ environmentId,+ input: buildBotTurnStartInput({+ botId: BotId.make(botId),+ threadId,+ projectId: activeProject.id,+ title,+ message: {+ messageId: newMessageId(),+ role: "user",+ text: prompt,+ attachments,+ },+ modelSelection,+ runtimeMode,+ interactionMode: DEFAULT_INTERACTION_MODE,+ createdAt,+ createThread: currentThreadRef === null,+ }),+ });+ if (startResult._tag === "Failure") {+ setError(errorMessage(startResult));+ return false;+ }++ const threadRef = scopeThreadRef(environmentId, threadId);+ retainedThreadRef.current.threadRef = threadRef;+ useRosterStore+ .getState()+ .recordChatPath(botId, `/${threadRef.environmentId}/${threadRef.threadId}`);+ useRosterStore.getState().recordLastMessage(botId, {+ text: prompt || (files.length === 1 ? "Sent an image" : "Sent images"),+ at: createdAt,+ });+ return true;+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Could not send the message.");+ return false;+ } finally {+ sendInFlightRef.current = false;+ setSending(false);+ }+ },+ [+ activeProject,+ appDefaultModelSelection,+ bot,+ botId,+ effectiveModelSelection,+ botReady,+ startTurn,+ ],+ );++ return {+ bootstrapped,+ botReady,+ defaultProject: activeProject,+ error,+ linkedThreadRef,+ messages,+ send,+ sending,+ };+}diff --git a/apps/web/src/components/roster/useGroupThreadRuntime.ts b/apps/web/src/components/roster/useGroupThreadRuntime.tsnew file mode 100644index 000000000..e9bb42503--- /dev/null+++ b/apps/web/src/components/roster/useGroupThreadRuntime.ts@@ -0,0 +1,237 @@+import { useAtomValue } from "@effect/atom-react";+import { scopeThreadRef } from "@t3tools/client-runtime/environment";+import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";+import {+ BotId,+ DEFAULT_RUNTIME_MODE,+ EnvironmentId,+ GroupId,+ ProviderInstanceId,+ ThreadId,+ type ModelSelection,+ type ScopedThreadRef,+} from "@t3tools/contracts";+import { useCallback, useMemo, useRef, useState } from "react";++import { usePrimarySettings } from "../../hooks/useSettings";+import { newMessageId, newThreadId } from "../../lib/utils";+import { resolveAppModelSelectionState } from "../../modelSelection";+import { environmentGroupsAtom } from "../../state/bots";+import {+ useAllEnvironmentShellsBootstrapped,+ useProjects,+ useThreadMessages,+ useThreadShell,+ useThreadShells,+} from "../../state/entities";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { primaryServerProvidersAtom } from "../../state/server";+import { threadEnvironment } from "../../state/threads";+import { useAtomCommand } from "../../state/use-atom-command";+import { DEFAULT_INTERACTION_MODE } from "../../types";+import { sortScopedProjectsForSidebar } from "../Sidebar.logic";+import { buildGroupTurnStartInput, findLatestGroupThreadTarget } from "./botThreadRuntime.logic";+import { useRosterStore } from "./rosterStore";++const NO_ENVIRONMENT = "" as EnvironmentId;++function errorMessage(result: Parameters<typeof squashAtomCommandFailure>[0]): string {+ const error = squashAtomCommandFailure(result);+ return error instanceof Error ? error.message : "Could not send the message.";+}++function threadTitle(prompt: string, files: readonly File[]): string {+ const seed = prompt || (files[0] ? `Image: ${files[0].name}` : "New thread");+ return seed.length > 80 ? `${seed.slice(0, 79)}…` : seed;+}++function readFileAsDataUrl(file: File): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.addEventListener(+ "error",+ () => reject(reader.error ?? new Error(`Could not read ${file.name}.`)),+ { once: true },+ );+ reader.addEventListener(+ "load",+ () =>+ typeof reader.result === "string"+ ? resolve(reader.result)+ : reject(new Error(`Could not read ${file.name}.`)),+ { once: true },+ );+ reader.readAsDataURL(file);+ });+}++export function useGroupThreadRuntime(groupId: string) {+ const projects = useProjects();+ const primaryEnvironmentId = usePrimaryEnvironmentId();+ const serverGroups = useAtomValue(environmentGroupsAtom(primaryEnvironmentId ?? NO_ENVIRONMENT));+ const threadShells = useThreadShells();+ const bootstrapped = useAllEnvironmentShellsBootstrapped();+ const settings = usePrimarySettings();+ const providers = useAtomValue(primaryServerProvidersAtom);+ const bots = useRosterStore((state) => state.bots);+ const group = useRosterStore((state) =>+ state.groups.find((candidate) => candidate.id === groupId),+ );+ const primaryThreadShells = useMemo(+ () =>+ primaryEnvironmentId+ ? threadShells.filter((thread) => thread.environmentId === primaryEnvironmentId)+ : [],+ [primaryEnvironmentId, threadShells],+ );+ const serverTarget = primaryEnvironmentId+ ? findLatestGroupThreadTarget(groupId, primaryEnvironmentId, primaryThreadShells)+ : null;+ const rememberedThreadRef = useMemo<ScopedThreadRef | null>(+ () =>+ serverTarget+ ? scopeThreadRef(+ EnvironmentId.make(serverTarget.environmentId),+ ThreadId.make(serverTarget.threadId),+ )+ : null,+ [serverTarget],+ );+ const rememberedThread = useThreadShell(rememberedThreadRef);+ const linkedThreadRef = rememberedThread ? rememberedThreadRef : null;+ const retainedThreadRef = useRef<{ groupId: string; threadRef: ScopedThreadRef | null }>({+ groupId,+ threadRef: null,+ });+ if (retainedThreadRef.current.groupId !== groupId) {+ retainedThreadRef.current = { groupId, threadRef: null };+ }+ if (linkedThreadRef) retainedThreadRef.current.threadRef = linkedThreadRef;+ const messages = useThreadMessages(linkedThreadRef);+ const defaultProject = useMemo(+ () =>+ bootstrapped && primaryEnvironmentId+ ? (sortScopedProjectsForSidebar(+ projects.filter((project) => project.environmentId === primaryEnvironmentId),+ primaryThreadShells,+ "updated_at",+ )[0] ?? null)+ : null,+ [bootstrapped, primaryEnvironmentId, primaryThreadShells, projects],+ );+ const activeProject =+ projects.find(+ (project) =>+ project.environmentId === rememberedThread?.environmentId &&+ project.id === rememberedThread.projectId,+ ) ?? defaultProject;+ const appDefaultModelSelection = useMemo(+ () => resolveAppModelSelectionState(settings, providers),+ [providers, settings],+ );+ const startTurn = useAtomCommand(threadEnvironment.startTurn, { reportFailure: false });+ const groupReady = serverGroups.some((candidate) => candidate.id === groupId);+ const sendInFlightRef = useRef(false);+ const [sending, setSending] = useState(false);+ const [error, setError] = useState<string | null>(null);++ const send = useCallback(+ async (prompt: string, files: readonly File[], requestedBotId?: string): Promise<boolean> => {+ if (sendInFlightRef.current) return false;+ if (!groupReady || !group) {+ setError("The group is still connecting.");+ return false;+ }+ if (!activeProject) {+ setError("Add a project before you message a group.");+ return false;+ }+ const unsupported = files.find((file) => !file.type.startsWith("image/"));+ if (unsupported) {+ setError("Group attachments must be images.");+ return false;+ }++ const respondingBotId = requestedBotId ?? group.bossBotId;+ const respondingBot = bots.find(+ (bot) => bot.id === respondingBotId && bot.groupId === groupId,+ );+ if (!respondingBot) {+ setError("Choose a current group member.");+ return false;+ }+ const modelSelection: ModelSelection = respondingBot.engine+ ? {+ instanceId: ProviderInstanceId.make(respondingBot.engine.provider),+ model: respondingBot.engine.model,+ }+ : (activeProject.defaultModelSelection ?? appDefaultModelSelection);++ sendInFlightRef.current = true;+ setSending(true);+ setError(null);+ const createdAt = new Date().toISOString();+ const currentThreadRef = retainedThreadRef.current.threadRef;+ const threadId = currentThreadRef?.threadId ?? newThreadId();++ try {+ const attachments = await Promise.all(+ files.map(async (file) => ({+ type: "image" as const,+ name: file.name,+ mimeType: file.type,+ sizeBytes: file.size,+ dataUrl: await readFileAsDataUrl(file),+ })),+ );+ const environmentId = currentThreadRef?.environmentId ?? activeProject.environmentId;+ const result = await startTurn({+ environmentId,+ input: buildGroupTurnStartInput({+ groupId: GroupId.make(groupId),+ respondingBotId: BotId.make(respondingBot.id),+ threadId,+ projectId: activeProject.id,+ title: threadTitle(prompt, files),+ message: {+ messageId: newMessageId(),+ role: "user",+ text: prompt,+ attachments,+ },+ modelSelection,+ runtimeMode: respondingBot.runtimeMode ?? DEFAULT_RUNTIME_MODE,+ interactionMode: DEFAULT_INTERACTION_MODE,+ createdAt,+ createThread: currentThreadRef === null,+ }),+ });+ if (result._tag === "Failure") {+ setError(errorMessage(result));+ return false;+ }+ retainedThreadRef.current.threadRef = scopeThreadRef(environmentId, threadId);+ return true;+ } catch (cause) {+ setError(cause instanceof Error ? cause.message : "Could not send the message.");+ return false;+ } finally {+ sendInFlightRef.current = false;+ setSending(false);+ }+ },+ [activeProject, appDefaultModelSelection, bots, group, groupId, groupReady, startTurn],+ );++ return {+ bootstrapped,+ defaultProject: activeProject,+ error,+ groupReady,+ linkedThreadRef,+ messages,+ respondingBotId: rememberedThread?.respondingBotId ?? group?.bossBotId ?? null,+ send,+ sending,+ };+}diff --git a/apps/web/src/components/roster/useServerRoster.ts b/apps/web/src/components/roster/useServerRoster.tsnew file mode 100644index 000000000..0e339bb5c--- /dev/null+++ b/apps/web/src/components/roster/useServerRoster.ts@@ -0,0 +1,79 @@+import { useAtomValue } from "@effect/atom-react";+import { BotId, type EnvironmentId } from "@t3tools/contracts";+import { useCallback, useEffect } from "react";++import {+ botEnvironment,+ environmentBotsAtom,+ environmentGroupsAtom,+ environmentRosterLoadedAtom,+} from "../../state/bots";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { useAtomCommand } from "../../state/use-atom-command";+import { useRosterStore } from "./rosterStore";+import type { BotAvatar } from "./types";++const NO_ENVIRONMENT = "" as EnvironmentId;++/** Mirrors the primary environment's persisted bot roster into the UI store. */+export function useServerRosterSync(): void {+ const environmentId = usePrimaryEnvironmentId();+ const atomKey = environmentId ?? NO_ENVIRONMENT;+ const loaded = useAtomValue(environmentRosterLoadedAtom(atomKey));+ const bots = useAtomValue(environmentBotsAtom(atomKey));+ const groups = useAtomValue(environmentGroupsAtom(atomKey));+ const createBot = useAtomCommand(botEnvironment.create, { reportFailure: false });++ useEffect(() => {+ if (environmentId === null || !loaded) return;+ if (bots.length === 0) {+ void createBot({+ environmentId,+ input: {+ botId: BotId.make("bot-akeru"),+ name: "Akeru",+ title: "Generalist",+ label: null,+ description: null,+ avatar: { kind: "blob", shape: "circle", color: "#5B7FD4" },+ engine: null,+ sandbox: null,+ runtimeMode: "full-access",+ usageCap: null,+ groupId: null,+ },+ });+ return;+ }+ useRosterStore.getState().replaceRoster({+ bots: bots.map((bot) => ({+ ...bot,+ avatar: { ...bot.avatar },+ pinned: false,+ })),+ groups: groups.map((group) => ({ ...group })),+ });+ }, [bots, createBot, environmentId, groups, loaded]);+}++export function useSaveBotAvatar(): (botId: string, avatar: BotAvatar) => Promise<boolean> {+ const environmentId = usePrimaryEnvironmentId();+ const bots = useAtomValue(environmentBotsAtom(environmentId ?? NO_ENVIRONMENT));+ const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });++ return useCallback(+ async (botId: string, avatar: BotAvatar) => {+ const serverBot = bots.find((candidate) => candidate.id === botId);+ if (environmentId !== null && serverBot !== undefined) {+ const result = await updateBot({+ environmentId,+ input: { botId: serverBot.id, avatar },+ });+ return result._tag === "Success";+ }+ useRosterStore.getState().setBotAvatar(botId, avatar);+ return true;+ },+ [bots, environmentId, updateBot],+ );+}diff --git a/apps/web/src/components/settings/ConnectionsSettings.tsx b/apps/web/src/components/settings/ConnectionsSettings.tsxindex 18d1b0f1c..7cf293150 100644--- a/apps/web/src/components/settings/ConnectionsSettings.tsx+++ b/apps/web/src/components/settings/ConnectionsSettings.tsx@@ -1412,7 +1412,7 @@ function SavedBackendListRow({: null;const metadataBits = [sshTarget ? `SSH ${formatDesktopSshTarget(sshTarget)}` : null,- environment.relayManaged ? "T3 Connect" : null,+ environment.relayManaged ? "Managed tunnel" : null,].filter((value): value is string => value !== null);// The WSL backend is a desktop-managed local backend (it surfaces as a bearer@@ -1582,7 +1582,7 @@ function CloudLinkSwitch({disabled,disabledReason,onCheckedChange,- ariaLabel = "Enable T3 Connect",+ ariaLabel = "Enable remote access",}: {readonly checked: boolean;readonly disabled: boolean;@@ -1621,9 +1621,9 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: bconst [isUpdatingPreference, setIsUpdatingPreference] = useState(false);const disabledReason = !isSignedIn- ? "Sign in to T3 Connect to manage this environment."+ ? "Sign in to manage this environment.": !canManageRelay- ? "Your session does not have permission to manage T3 Connect access."+ ? "Your session does not have permission to manage remote access.": null;const isBusy = isUpdating || isUpdatingPreference;@@ -1636,15 +1636,15 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: btoastManager.add({type: "success",title: enabled- ? "T3 Connect linked"+ ? "Environment linked": publishAgentActivity- ? "T3 Connect tunnel disabled"- : "T3 Connect unlinked",+ ? "Managed tunnel disabled"+ : "Environment unlinked",description: enabled- ? "This environment is available through T3 Connect."+ ? "This environment is available through its managed tunnel.": publishAgentActivity? "The managed tunnel was removed. Agent activity publishing stays on."- : "This environment is no longer available through T3 Connect.",+ : "This environment is no longer available through its managed tunnel.",});}setIsUpdating(false);@@ -1669,11 +1669,11 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b<>{window.desktopBridge ? (<SettingsRow- title="T3 Connect"+ title="Remote access"description={managedTunnelActive- ? "This environment is available to your other devices through T3 Connect."- : "Make this environment available to your other devices through T3 Connect."+ ? "This environment is available to your other devices through its managed tunnel."+ : "Make this environment available to your other devices through a managed tunnel."}status={operationError ?? primaryCloudLinkState.error}control={@@ -1688,7 +1688,7 @@ function ConfiguredCloudLinkRow({ canManageRelay }: { readonly canManageRelay: b) : null}<SettingsRowtitle="Publish agent activity"- description="Send activity from this environment to your mobile clients for push notifications and Live Activities. Works without a T3 Connect tunnel."+ description="Send activity from this environment to your mobile clients for push notifications and Live Activities. Works without a managed tunnel."control={<CloudLinkSwitchariaLabel="Publish agent activity to mobile clients"@@ -1717,7 +1717,7 @@ function EmptyRemoteEnvironments({ cloudEnabled = true }: { readonly cloudEnable<EmptyTitle>No saved remote environments</EmptyTitle><EmptyDescription>{cloudEnabled- ? "Click “Add environment” to pair another environment, or connect one from T3 Connect."+ ? "Click “Add environment” to pair another environment, or connect one of your linked environments.": "Click “Add environment” to pair another environment."}</EmptyDescription></EmptyHeader>@@ -2884,7 +2884,7 @@ export function ConnectionsSettings() {{desktopWslState.enabled ? (<SettingsRowtitle="WSL only"- description="Stop the Windows backend and run only the WSL backend. Useful if you develop entirely inside WSL and don't want a second backend process. T3 Code restarts when you change this."+ description="Stop the Windows backend and run only the WSL backend. Useful if you develop entirely inside WSL and don't want a second backend process. Akeru Bot restarts when you change this."className="bg-muted/20 pl-7 sm:pl-8"control={<Switch@@ -3115,8 +3115,8 @@ export function ConnectionsSettings() {</AlertDialogTitle><AlertDialogDescription>{pendingDesktopServerExposureMode === "network-accessible"- ? "T3 Code will restart to expose this environment over the network."- : "T3 Code will restart and limit this environment back to this machine."}+ ? "Akeru Bot will restart to expose this environment over the network."+ : "Akeru Bot will restart and limit this environment back to this machine."}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>@@ -3174,15 +3174,15 @@ export function ConnectionsSettings() {<AlertDialogDescription>{pendingWslChange?.kind === "disable"? pendingWslChange.wasWslOnly- ? "T3 Code will restart on the Windows backend. Threads and projects opened against WSL stay safe inside the distro and become available again when you re-enable WSL."- : "The WSL backend will stop. Threads and projects opened against WSL stay safe inside the distro, but they'll be unavailable in T3 Code until you re-enable WSL."+ ? "Akeru Bot will restart on the Windows backend. Threads and projects opened against WSL stay safe inside the distro and become available again when you re-enable WSL."+ : "The WSL backend will stop. Threads and projects opened against WSL stay safe inside the distro, but they'll be unavailable in Akeru Bot until you re-enable WSL.": pendingWslChange?.kind === "distro"- ? "T3 Code will restart the WSL backend on the new distro. Sessions still running on the current distro will be interrupted."+ ? "Akeru Bot will restart the WSL backend on the new distro. Sessions still running on the current distro will be interrupted.": pendingWslChange?.kind === "enable"? "Run the WSL backend alongside the Windows one, or stop the Windows backend and use only WSL? You can change this later from Settings.": pendingWslChange?.nextValue- ? "T3 Code will restart and start only the WSL backend. Your Windows-side projects won't be accessible until you turn this off again."- : "T3 Code will restart and bring the Windows backend back up alongside WSL."}+ ? "Akeru Bot will restart and start only the WSL backend. Your Windows-side projects won't be accessible until you turn this off again."+ : "Akeru Bot will restart and bring the Windows backend back up alongside WSL."}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>@@ -3268,7 +3268,7 @@ export function ConnectionsSettings() {<AlertDialogHeader><AlertDialogTitle>Disable Tailscale HTTPS?</AlertDialogTitle><AlertDialogDescription>- T3 Code will restart the local backend without Tailscale Serve.+ Akeru Bot will restart the local backend without Tailscale Serve.</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>@@ -3306,7 +3306,7 @@ export function ConnectionsSettings() {<DialogHeader><DialogTitle>Set up Tailscale HTTPS?</DialogTitle><DialogDescription>- T3 Code will restart the local backend with Tailscale Serve enabled and ask+ Akeru Bot will restart the local backend with Tailscale Serve enabled and askTailscale to proxy HTTPS traffic to this backend.</DialogDescription></DialogHeader>diff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsxindex 9c36d32ff..35a9e44f6 100644--- a/apps/web/src/components/settings/DiagnosticsSettings.tsx+++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx@@ -964,7 +964,7 @@ export function DiagnosticsSettingsPanel() {type: "info",title: "Process already exited",description:- "The process is not a child of the T3 Server. It might already have exited.",+ "The process is not a child of the Akeru Bot server. It might already have exited.",});return;}@@ -1077,7 +1077,7 @@ export function DiagnosticsSettingsPanel() {<StatBlocklabel="CPU Time"value={resourceData ? formatCpuTime(resourceData.totalCpuSecondsApprox) : "..."}- tooltip="Approximate active CPU time for the T3 server root process and its descendants during the selected window. It grows only while sampled processes use CPU and older samples leave as the window moves."+ tooltip="Approximate active CPU time for the Akeru Bot server root process and its descendants during the selected window. It grows only while sampled processes use CPU and older samples leave as the window moves."/><StatBlocklabel="Samples"diff --git a/apps/web/src/components/settings/GroupSettingsSection.test.ts b/apps/web/src/components/settings/GroupSettingsSection.test.tsnew file mode 100644index 000000000..551d4a389--- /dev/null+++ b/apps/web/src/components/settings/GroupSettingsSection.test.ts@@ -0,0 +1,23 @@+import { BotId, GroupId } from "@t3tools/contracts";+import { describe, expect, it } from "vite-plus/test";++import { availableSpecialists } from "./GroupSettingsSection";++const bot = (id: string, groupId: string | null, archivedAt: string | null = null) => ({+ id: BotId.make(id),+ name: id,+ groupId: groupId === null ? null : GroupId.make(groupId),+ archivedAt,+});++describe("group settings", () => {+ it("offers active unassigned bots as specialists", () => {+ expect(+ availableSpecialists([+ bot("free", null),+ bot("assigned", "group-one"),+ bot("archived", null, "2026-08-27T00:00:00.000Z"),+ ]).map((entry) => entry.id),+ ).toEqual(["free"]);+ });+});diff --git a/apps/web/src/components/settings/GroupSettingsSection.tsx b/apps/web/src/components/settings/GroupSettingsSection.tsxnew file mode 100644index 000000000..c4cd9834c--- /dev/null+++ b/apps/web/src/components/settings/GroupSettingsSection.tsx@@ -0,0 +1,293 @@+import {+ BotId,+ GROUP_SHARED_WORKSPACE_WARNING,+ GroupId,+ type EnvironmentId,+ type OrchestrationBot,+ type OrchestrationGroup,+} from "@t3tools/contracts";+import { Trash2Icon, UserPlusIcon } from "lucide-react";+import { useEffect, useMemo, useState } from "react";++import { randomUUID } from "../../lib/utils";+import { botEnvironment } from "../../state/bots";+import { useAtomCommand } from "../../state/use-atom-command";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";+import { toastManager } from "../ui/toast";+import { SettingsRow, SettingsSection } from "./settingsLayout";++export function availableSpecialists(+ bots: ReadonlyArray<Pick<OrchestrationBot, "id" | "name" | "archivedAt" | "groupId">>,+): ReadonlyArray<Pick<OrchestrationBot, "id" | "name" | "archivedAt" | "groupId">> {+ return bots.filter((bot) => bot.archivedAt === null && bot.groupId === null);+}++export function GroupSettingsSection({+ environmentId,+ bots,+ groups,+}: {+ readonly environmentId: EnvironmentId;+ readonly bots: ReadonlyArray<OrchestrationBot>;+ readonly groups: ReadonlyArray<OrchestrationGroup>;+}) {+ const createGroup = useAtomCommand(botEnvironment.groups.create, { reportFailure: false });+ const deleteGroup = useAtomCommand(botEnvironment.groups.delete, { reportFailure: false });+ const assignMember = useAtomCommand(botEnvironment.groups.assignMember, {+ reportFailure: false,+ });+ const unassignMember = useAtomCommand(botEnvironment.groups.unassignMember, {+ reportFailure: false,+ });+ const setBoss = useAtomCommand(botEnvironment.groups.setBoss, { reportFailure: false });+ const [selectedGroupId, setSelectedGroupId] = useState<string | null>(groups[0]?.id ?? null);+ const [newGroupName, setNewGroupName] = useState("");+ const [newBossId, setNewBossId] = useState<string>(+ bots.find((bot) => bot.groupId === null && bot.archivedAt === null)?.id ?? "",+ );+ const [specialistId, setSpecialistId] = useState("");+ const [busy, setBusy] = useState(false);+ const selectedGroup = groups.find((group) => group.id === selectedGroupId) ?? groups[0] ?? null;+ const unassignedBots = useMemo(() => availableSpecialists(bots), [bots]);+ const members = selectedGroup+ ? selectedGroup.members.flatMap((membership) => {+ const bot = bots.find((candidate) => candidate.id === membership.botId);+ return bot ? [{ bot, role: membership.role }] : [];+ })+ : [];++ useEffect(() => {+ if (selectedGroup && selectedGroup.id !== selectedGroupId) {+ setSelectedGroupId(selectedGroup.id);+ }+ }, [selectedGroup, selectedGroupId]);++ useEffect(() => {+ if (!unassignedBots.some((bot) => bot.id === newBossId)) {+ setNewBossId(unassignedBots[0]?.id ?? "");+ }+ if (!unassignedBots.some((bot) => bot.id === specialistId)) {+ setSpecialistId("");+ }+ }, [newBossId, specialistId, unassignedBots]);++ const run = async (action: () => Promise<{ readonly _tag: string }>, failure: string) => {+ setBusy(true);+ const result = await action();+ setBusy(false);+ if (result._tag === "Failure") {+ toastManager.add({ type: "error", title: failure });+ return false;+ }+ return true;+ };++ const create = async () => {+ const name = newGroupName.trim();+ if (!name || !newBossId) return;+ const groupId = GroupId.make(`group-${randomUUID()}`);+ if (+ await run(+ () =>+ createGroup({+ environmentId,+ input: { groupId, name, bossBotId: BotId.make(newBossId) },+ }),+ "Could not create group",+ )+ ) {+ setSelectedGroupId(groupId);+ setNewGroupName("");+ }+ };++ return (+ <SettingsSection title="Groups">+ <div className="mx-3 mb-3 rounded-lg border border-warning/30 bg-warning/8 px-3 py-2 text-xs leading-5 text-muted-foreground sm:mx-4">+ {GROUP_SHARED_WORKSPACE_WARNING}+ </div>+ <SettingsRow+ title="New group"+ description="Choose one boss. Specialists can be added after creation."+ control={+ <div className="flex w-72 flex-col gap-2">+ <Input+ aria-label="New group name"+ placeholder="Group name"+ value={newGroupName}+ onChange={(event) => setNewGroupName(event.currentTarget.value)}+ />+ <Select value={newBossId} onValueChange={(value) => value && setNewBossId(value)}>+ <SelectTrigger aria-label="New group boss" className="w-full">+ <SelectValue placeholder="Choose boss" />+ </SelectTrigger>+ <SelectPopup>+ {unassignedBots.map((bot) => (+ <SelectItem key={bot.id} value={bot.id}>+ {bot.name}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ <Button+ disabled={busy || !newGroupName.trim() || !newBossId}+ onClick={() => void create()}+ >+ Create group+ </Button>+ </div>+ }+ />+ {selectedGroup ? (+ <>+ <SettingsRow+ title="Manage group"+ control={+ <Select+ value={selectedGroup.id}+ onValueChange={(value) => value && setSelectedGroupId(value)}+ >+ <SelectTrigger aria-label="Group" className="w-52">+ <SelectValue />+ </SelectTrigger>+ <SelectPopup>+ {groups.map((group) => (+ <SelectItem key={group.id} value={group.id}>+ {group.name}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ }+ />+ <SettingsRow+ title="Boss"+ description="Changing the boss keeps the previous boss as a specialist."+ control={+ <Select+ value={selectedGroup.bossBotId ?? ""}+ onValueChange={(botId) => {+ if (!botId || botId === selectedGroup.bossBotId) return;+ void run(+ () =>+ setBoss({+ environmentId,+ input: {+ groupId: selectedGroup.id,+ bossBotId: BotId.make(botId),+ unassignPreviousBoss: false,+ },+ }),+ "Could not change group boss",+ );+ }}+ >+ <SelectTrigger aria-label="Group boss" className="w-52">+ <SelectValue />+ </SelectTrigger>+ <SelectPopup>+ {members.map(({ bot }) => (+ <SelectItem key={bot.id} value={bot.id}>+ {bot.name}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ }+ />+ <div className="space-y-1 px-3 pb-3 sm:px-4">+ {members.map(({ bot, role }) => (+ <div key={bot.id} className="flex min-h-10 items-center gap-3 rounded-lg px-2">+ <span className="min-w-0 flex-1 truncate text-sm">{bot.name}</span>+ <span className="text-xs capitalize text-muted-foreground">{role}</span>+ <Button+ aria-label={`Remove ${bot.name} from ${selectedGroup.name}`}+ disabled={busy || role === "boss"}+ size="icon-sm"+ variant="ghost"+ onClick={() =>+ void run(+ () =>+ unassignMember({+ environmentId,+ input: { groupId: selectedGroup.id, botId: BotId.make(bot.id) },+ }),+ `Could not remove ${bot.name}`,+ )+ }+ >+ <Trash2Icon />+ </Button>+ </div>+ ))}+ </div>+ <SettingsRow+ title="Add specialist"+ control={+ <div className="flex items-center gap-2">+ <Select+ value={specialistId}+ onValueChange={(value) => value && setSpecialistId(value)}+ >+ <SelectTrigger aria-label="Specialist" className="w-44">+ <SelectValue placeholder="Choose bot" />+ </SelectTrigger>+ <SelectPopup>+ {unassignedBots.map((bot) => (+ <SelectItem key={bot.id} value={bot.id}>+ {bot.name}+ </SelectItem>+ ))}+ </SelectPopup>+ </Select>+ <Button+ aria-label="Add specialist"+ disabled={busy || !specialistId}+ size="icon-sm"+ variant="outline"+ onClick={() => {+ if (!specialistId) return;+ void run(+ () =>+ assignMember({+ environmentId,+ input: {+ groupId: selectedGroup.id,+ botId: BotId.make(specialistId),+ role: "specialist",+ },+ }),+ "Could not add specialist",+ ).then((success) => success && setSpecialistId(""));+ }}+ >+ <UserPlusIcon />+ </Button>+ </div>+ }+ />+ <SettingsRow+ title="Delete group"+ description="Bots return to Unassigned. Threads keep their group owner."+ control={+ <Button+ disabled={busy}+ variant="destructive"+ onClick={() =>+ void run(+ () => deleteGroup({ environmentId, input: { groupId: selectedGroup.id } }),+ "Could not delete group",+ )+ }+ >+ Delete group+ </Button>+ }+ />+ </>+ ) : null}+ </SettingsSection>+ );+}diff --git a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts b/apps/web/src/components/settings/KeybindingsSettings.logic.test.tsindex 90eaaef99..b9d042f51 100644--- a/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts+++ b/apps/web/src/components/settings/KeybindingsSettings.logic.test.ts@@ -151,7 +151,12 @@ describe("KeybindingsSettings.logic", () => {] satisfies ResolvedKeybindingsConfig);expect(options).toEqual(- expect.arrayContaining(["chat.new", "rightPanel.toggleMaximized", "script.setup-db.run"]),+ expect.arrayContaining([+ "chat.new",+ "rightPanel.toggle",+ "rightPanel.toggleMaximized",+ "script.setup-db.run",+ ]),);});diff --git a/apps/web/src/components/settings/KeybindingsSettings.tsx b/apps/web/src/components/settings/KeybindingsSettings.tsxindex ccbd1f065..1624e5b55 100644--- a/apps/web/src/components/settings/KeybindingsSettings.tsx+++ b/apps/web/src/components/settings/KeybindingsSettings.tsx@@ -258,7 +258,7 @@ function UnknownWhenVariableWarning({}/><TooltipPopup side="top" className="max-w-72 whitespace-normal leading-relaxed">- T3 Code does not recognize this condition yet. It can still be saved, but it may not match+ Akeru Bot does not recognize this condition yet. It can still be saved, but it may not matchunless the runtime provides it.</TooltipPopup></Tooltip>@@ -1248,8 +1248,8 @@ export function KeybindingsSettingsPanel() {<div className="flex items-start gap-2 border-b border-warning/20 bg-warning/5 px-3 py-2.5 text-[12px] leading-relaxed text-muted-foreground sm:px-4"><InfoIcon className="mt-0.5 size-3.5 shrink-0 text-warning" /><p>- Some shortcuts may be claimed by the browser before T3 Code sees them. Use the desktop- app for better keybinding support.+ Some shortcuts may be claimed by the browser before Akeru Bot sees them. Use the+ desktop app for better keybinding support.</p></div>) : null}diff --git a/apps/web/src/components/settings/PluginsSettings.test.ts b/apps/web/src/components/settings/PluginsSettings.test.tsnew file mode 100644index 000000000..ceffad06c--- /dev/null+++ b/apps/web/src/components/settings/PluginsSettings.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vite-plus/test";++import { validateMcpServerDraft } from "./PluginsSettings";++describe("raw MCP server settings", () => {+ it("accepts standard input/output and HTTP server configurations", () => {+ expect(+ validateMcpServerDraft({+ name: "Filesystem",+ transport: "stdio",+ command: "bunx",+ args: "@modelcontextprotocol/server-filesystem",+ url: "",+ }),+ ).toBeNull();+ expect(+ validateMcpServerDraft({+ name: "Remote",+ transport: "url",+ command: "",+ args: "",+ url: "https://mcp.example.com",+ }),+ ).toBeNull();+ });++ it("rejects missing commands and credentials embedded in URLs", () => {+ expect(+ validateMcpServerDraft({+ name: "Filesystem",+ transport: "stdio",+ command: " ",+ args: "",+ url: "",+ }),+ ).toBe("Command is required.");+ expect(+ validateMcpServerDraft({+ name: "Remote",+ transport: "url",+ command: "",+ args: "",+ url: "https://[email protected]",+ }),+ ).toBe("Store credentials outside the server URL.");+ });+});diff --git a/apps/web/src/components/settings/PluginsSettings.tsx b/apps/web/src/components/settings/PluginsSettings.tsxnew file mode 100644index 000000000..a9a9bf69a--- /dev/null+++ b/apps/web/src/components/settings/PluginsSettings.tsx@@ -0,0 +1,353 @@+import { useAtomValue } from "@effect/atom-react";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+} from "@t3tools/client-runtime/state/runtime";+import { McpServerId, type EnvironmentId, type McpServer } from "@t3tools/contracts";+import { PencilIcon, PlusIcon, Trash2Icon } from "lucide-react";+import { useState } from "react";++import { ensureLocalApi } from "../../localApi";+import { randomUUID } from "../../lib/utils";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { environmentMcpServersAtom, mcpServerEnvironment } from "../../state/mcpServers";+import { useAtomCommand } from "../../state/use-atom-command";+import { Button } from "../ui/button";+import {+ Dialog,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogPopup,+ DialogTitle,+} from "../ui/dialog";+import { Field, FieldLabel } from "../ui/field";+import { Input } from "../ui/input";+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";+import { Switch } from "../ui/switch";+import { Textarea } from "../ui/textarea";+import { toastManager } from "../ui/toast";+import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";++interface McpServerDraft {+ readonly name: string;+ readonly transport: "stdio" | "url";+ readonly command: string;+ readonly args: string;+ readonly url: string;+}++const EMPTY_DRAFT: McpServerDraft = {+ name: "",+ transport: "stdio",+ command: "",+ args: "",+ url: "",+};++function draftFromServer(server: McpServer): McpServerDraft {+ return server.transport === "stdio"+ ? {+ name: server.name,+ transport: server.transport,+ command: server.command,+ args: server.args?.join("\n") ?? "",+ url: "",+ }+ : {+ name: server.name,+ transport: server.transport,+ command: "",+ args: "",+ url: server.url,+ };+}++export function validateMcpServerDraft(draft: McpServerDraft): string | null {+ if (draft.name.trim().length === 0) return "Name is required.";+ if (draft.transport === "stdio") {+ return draft.command.trim().length === 0 ? "Command is required." : null;+ }+ try {+ const url = new URL(draft.url.trim());+ if (url.protocol !== "http:" && url.protocol !== "https:") {+ return "URL must start with http:// or https://.";+ }+ return url.username.length === 0 && url.password.length === 0+ ? null+ : "Store credentials outside the server URL.";+ } catch {+ return "Enter a valid HTTP or HTTPS URL.";+ }+}++function commandDescription(server: McpServer): string {+ if (server.transport === "url") return server.url;+ return [server.command, ...(server.args ?? [])].join(" ");+}++function PluginsSettingsForEnvironment({+ environmentId,+}: {+ readonly environmentId: EnvironmentId;+}) {+ const servers = useAtomValue(environmentMcpServersAtom(environmentId));+ const createServer = useAtomCommand(mcpServerEnvironment.create, { reportFailure: false });+ const updateServer = useAtomCommand(mcpServerEnvironment.update, { reportFailure: false });+ const deleteServer = useAtomCommand(mcpServerEnvironment.delete, { reportFailure: false });+ const enableServer = useAtomCommand(mcpServerEnvironment.enable, { reportFailure: false });+ const disableServer = useAtomCommand(mcpServerEnvironment.disable, { reportFailure: false });+ const [dialogOpen, setDialogOpen] = useState(false);+ const [editingServer, setEditingServer] = useState<McpServer | null>(null);+ const [draft, setDraft] = useState<McpServerDraft>(EMPTY_DRAFT);+ const [submitAttempted, setSubmitAttempted] = useState(false);+ const [pendingServerId, setPendingServerId] = useState<string | null>(null);+ const validationError = validateMcpServerDraft(draft);++ const openCreate = () => {+ setEditingServer(null);+ setDraft(EMPTY_DRAFT);+ setSubmitAttempted(false);+ setDialogOpen(true);+ };++ const openEdit = (server: McpServer) => {+ setEditingServer(server);+ setDraft(draftFromServer(server));+ setSubmitAttempted(false);+ setDialogOpen(true);+ };++ const reportFailure = (title: string, result: Awaited<ReturnType<typeof createServer>>) => {+ if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return false;+ const error = squashAtomCommandFailure(result);+ toastManager.add({+ type: "error",+ title,+ description: error instanceof Error ? error.message : "The command failed.",+ });+ return true;+ };++ const save = async () => {+ setSubmitAttempted(true);+ if (validationError !== null) return;++ const mcpServerId = editingServer?.id ?? McpServerId.make(randomUUID());+ setPendingServerId(mcpServerId);+ const configuration =+ draft.transport === "stdio"+ ? {+ name: draft.name.trim(),+ transport: draft.transport,+ command: draft.command.trim(),+ args: draft.args+ .split("\n")+ .map((argument) => argument.trim())+ .filter((argument) => argument.length > 0),+ }+ : {+ name: draft.name.trim(),+ transport: draft.transport,+ url: draft.url.trim(),+ };+ const result = editingServer+ ? await updateServer({ environmentId, input: { mcpServerId, ...configuration } })+ : await createServer({ environmentId, input: { mcpServerId, ...configuration } });+ setPendingServerId(null);+ if (+ reportFailure(+ editingServer ? "Could not update MCP server" : "Could not add MCP server",+ result,+ )+ ) {+ return;+ }+ setDialogOpen(false);+ };++ const toggle = async (server: McpServer, enabled: boolean) => {+ setPendingServerId(server.id);+ const mutation = enabled ? enableServer : disableServer;+ const result = await mutation({+ environmentId,+ input: { mcpServerId: server.id },+ });+ setPendingServerId(null);+ reportFailure(enabled ? "Could not enable MCP server" : "Could not disable MCP server", result);+ };++ const remove = async (server: McpServer) => {+ const confirmed = await ensureLocalApi().dialogs.confirm(+ `Delete the MCP server '${server.name}'?`,+ { variant: "destructive" },+ );+ if (!confirmed) return;+ setPendingServerId(server.id);+ const result = await deleteServer({+ environmentId,+ input: { mcpServerId: server.id },+ });+ setPendingServerId(null);+ reportFailure("Could not delete MCP server", result);+ };++ return (+ <SettingsPageContainer>+ <SettingsSection+ title="MCP servers"+ headerAction={+ <Button size="sm" onClick={openCreate}>+ <PlusIcon className="size-4" />+ Add server+ </Button>+ }+ >+ {servers.length === 0 ? (+ <p className="px-4 py-6 text-sm text-muted-foreground">+ No MCP servers yet. A raw MCP server runs with or without Executor.+ </p>+ ) : (+ servers.map((server) => {+ const pending = pendingServerId === server.id;+ return (+ <SettingsRow+ key={server.id}+ title={server.name}+ description={commandDescription(server)}+ status={server.transport === "stdio" ? "Standard input/output" : "URL"}+ control={+ <div className="flex items-center gap-1">+ <Switch+ checked={server.enabled}+ disabled={pending}+ onCheckedChange={(checked) => void toggle(server, Boolean(checked))}+ aria-label={`${server.enabled ? "Disable" : "Enable"} ${server.name}`}+ />+ <Button+ size="icon-sm"+ variant="ghost-muted"+ disabled={pending}+ aria-label={`Edit ${server.name}`}+ onClick={() => openEdit(server)}+ >+ <PencilIcon className="size-4" />+ </Button>+ <Button+ size="icon-sm"+ variant="ghost-muted"+ disabled={pending}+ aria-label={`Delete ${server.name}`}+ onClick={() => void remove(server)}+ >+ <Trash2Icon className="size-4" />+ </Button>+ </div>+ }+ />+ );+ })+ )}+ </SettingsSection>++ <Dialog open={dialogOpen} onOpenChange={setDialogOpen}>+ <DialogPopup className="max-w-lg">+ <DialogHeader>+ <DialogTitle>{editingServer ? "Edit MCP server" : "Add MCP server"}</DialogTitle>+ <DialogDescription>+ Register a raw MCP server. Store credentials outside this record.+ </DialogDescription>+ </DialogHeader>+ <div className="space-y-4 px-6 py-4">+ <Field>+ <FieldLabel>Name</FieldLabel>+ <Input+ value={draft.name}+ onChange={(event) => setDraft({ ...draft, name: event.currentTarget.value })}+ autoFocus+ />+ </Field>+ <Field>+ <FieldLabel>Transport</FieldLabel>+ <Select+ value={draft.transport}+ onValueChange={(transport) => {+ if (transport === "stdio" || transport === "url") {+ setDraft({ ...draft, transport });+ }+ }}+ >+ <SelectTrigger className="w-full" aria-label="MCP transport">+ <SelectValue>+ {draft.transport === "stdio" ? "Standard input/output" : "URL"}+ </SelectValue>+ </SelectTrigger>+ <SelectPopup>+ <SelectItem value="stdio">Standard input/output</SelectItem>+ <SelectItem value="url">URL</SelectItem>+ </SelectPopup>+ </Select>+ </Field>+ {draft.transport === "stdio" ? (+ <>+ <Field>+ <FieldLabel>Command</FieldLabel>+ <Input+ value={draft.command}+ onChange={(event) => setDraft({ ...draft, command: event.currentTarget.value })}+ placeholder="bunx"+ />+ </Field>+ <Field>+ <FieldLabel>Arguments, one per line</FieldLabel>+ <Textarea+ value={draft.args}+ onChange={(event) => setDraft({ ...draft, args: event.currentTarget.value })}+ placeholder={"@modelcontextprotocol/server-filesystem\n/workspace"}+ rows={4}+ />+ </Field>+ </>+ ) : (+ <Field>+ <FieldLabel>URL</FieldLabel>+ <Input+ value={draft.url}+ onChange={(event) => setDraft({ ...draft, url: event.currentTarget.value })}+ placeholder="https://mcp.example.com"+ />+ </Field>+ )}+ {submitAttempted && validationError ? (+ <p className="text-xs text-destructive-foreground">{validationError}</p>+ ) : null}+ </div>+ <DialogFooter>+ <Button variant="ghost" onClick={() => setDialogOpen(false)}>+ Cancel+ </Button>+ <Button disabled={pendingServerId !== null} onClick={() => void save()}>+ {editingServer ? "Save" : "Add server"}+ </Button>+ </DialogFooter>+ </DialogPopup>+ </Dialog>+ </SettingsPageContainer>+ );+}++export function PluginsSettingsPanel() {+ const environmentId = usePrimaryEnvironmentId();+ if (environmentId === null) {+ return (+ <SettingsPageContainer>+ <SettingsSection title="MCP servers">+ <p className="px-4 py-6 text-sm text-muted-foreground">+ Connect an environment to manage MCP servers.+ </p>+ </SettingsSection>+ </SettingsPageContainer>+ );+ }+ return <PluginsSettingsForEnvironment environmentId={environmentId} />;+}diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsxindex 3a38a91e2..fe3b7c021 100644--- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx+++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx@@ -156,7 +156,7 @@ function providerEnvironmentIcon(environment: EnvironmentPresentation) {function providerEnvironmentDetail(environment: EnvironmentPresentation): string {if (environment.entry.target._tag === "PrimaryConnectionTarget") return "Primary device";- if (environment.relayManaged) return "T3 Connect";+ if (environment.relayManaged) return "Managed tunnel";if (environment.entry.target._tag === "SshConnectionTarget") return "SSH";if (isDesktopLocalConnectionTarget(environment.entry.target)) return "Local device";return environment.displayUrl ?? "Remote device";diff --git a/apps/web/src/components/settings/ProvidersPanel.tsx b/apps/web/src/components/settings/ProvidersPanel.tsxnew file mode 100644index 000000000..5bf761824--- /dev/null+++ b/apps/web/src/components/settings/ProvidersPanel.tsx@@ -0,0 +1,412 @@+import { CheckIcon, CopyIcon, ExternalLinkIcon, LoaderIcon, LogOutIcon } from "lucide-react";+import { useCallback, useEffect, useMemo, useState } from "react";+import type {+ SubscriptionAuthLoginProgress,+ SubscriptionAuthStartResult,+ SubscriptionProviderId,+ SubscriptionProviderStatus,+} from "@t3tools/contracts";+import {+ isAtomCommandInterrupted,+ squashAtomCommandFailure,+ type AtomCommandResult,+} from "@t3tools/client-runtime/state/runtime";++import { usePrimaryEnvironmentId } from "../../state/environments";+import { serverEnvironment } from "../../state/server";+import { useEnvironmentQuery } from "../../state/query";+import { useAtomCommand } from "../../state/use-atom-command";+import { Badge } from "../ui/badge";+import { Button } from "../ui/button";+import { Input } from "../ui/input";+import { ClaudeAI, CursorIcon, type Icon } from "../Icons";+import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";++interface SubscriptionProviderDefinition {+ readonly id: SubscriptionProviderId;+ readonly label: string;+ readonly subscription: string;+ readonly description: string;+ readonly icon: Icon | string;+}++const SUBSCRIPTION_PROVIDERS: readonly SubscriptionProviderDefinition[] = [+ {+ id: "openai-codex",+ label: "ChatGPT",+ subscription: "Plus, Pro, Business, Enterprise, or Edu",+ description: "Use your ChatGPT subscription with Codex models.",+ icon: "/provider-icons/openai.svg",+ },+ {+ id: "anthropic",+ label: "Claude",+ subscription: "Pro or Max",+ description: "Use your Claude subscription with Claude Code models.",+ icon: ClaudeAI,+ },+ {+ id: "cursor",+ label: "Cursor",+ subscription: "Pro, Pro+, Ultra, Teams, or Enterprise",+ description: "Use the models included with your Cursor subscription.",+ icon: CursorIcon,+ },+ {+ id: "xai",+ label: "Grok",+ subscription: "SuperGrok or X Premium+",+ description: "Use Grok through your xAI subscription.",+ icon: "/provider-icons/xai.svg",+ },+ {+ id: "kimi-for-coding",+ label: "Kimi For Coding",+ subscription: "Kimi For Coding plan",+ description: "Use Kimi coding models through your Moonshot subscription.",+ icon: "/provider-icons/kimi-for-coding.svg",+ },+];++interface ActiveLogin {+ readonly flow: SubscriptionAuthStartResult;+ readonly providerLabel: string;+ readonly error: string | null;+}++function commandError(result: AtomCommandResult<unknown, unknown>): string {+ if (result._tag !== "Failure") return "The request failed.";+ const error = squashAtomCommandFailure(result);+ return error instanceof Error ? error.message : "The request failed.";+}++function ProviderLoginCard({+ definition,+ status,+ busy,+ onConnect,+ onDisconnect,+}: {+ readonly definition: SubscriptionProviderDefinition;+ readonly status: SubscriptionProviderStatus | undefined;+ readonly busy: boolean;+ readonly onConnect: () => void;+ readonly onDisconnect: () => void;+}) {+ const connected = status?.connected === true;+ const ProviderIcon = typeof definition.icon === "string" ? null : definition.icon;++ return (+ <SettingsRow+ title={+ <span className="flex items-center gap-2">+ {ProviderIcon ? (+ <ProviderIcon className="size-4 shrink-0" />+ ) : (+ <img+ src={definition.icon as string}+ alt=""+ className="size-4 shrink-0 brightness-0 dark:invert"+ />+ )}+ {definition.label}+ {connected ? (+ <Badge variant="success" className="h-4 px-1.5 text-[10px]">+ Connected+ </Badge>+ ) : null}+ </span>+ }+ description={definition.description}+ status={definition.subscription}+ control={+ connected ? (+ <Button size="xs" variant="ghost-muted" disabled={busy} onClick={onDisconnect}>+ {busy ? (+ <LoaderIcon className="size-3.5 animate-spin" />+ ) : (+ <LogOutIcon className="size-3.5" />+ )}+ Disconnect+ </Button>+ ) : (+ <Button size="xs" variant="outline" disabled={busy} onClick={onConnect}>+ {busy ? <LoaderIcon className="size-3.5 animate-spin" /> : null}+ Connect+ </Button>+ )+ }+ />+ );+}++function ActiveLoginPanel({+ login,+ pastedCode,+ onPastedCodeChange,+ onComplete,+ onCancel,+ completing,+}: {+ readonly login: ActiveLogin;+ readonly pastedCode: string;+ readonly onPastedCodeChange: (value: string) => void;+ readonly onComplete: () => void;+ readonly onCancel: () => void;+ readonly completing: boolean;+}) {+ const { flow } = login;+ return (+ <div className="mx-3 mb-3 space-y-3 rounded-xl border bg-muted/30 p-4 sm:mx-4">+ <div className="flex items-center justify-between gap-3">+ <p className="text-[13px] text-muted-foreground">+ {flow.instructions ?? "Finish signing in on the provider page."}+ </p>+ <Button+ size="xs"+ variant="outline"+ render={<a href={flow.url} target="_blank" rel="noreferrer" />}+ >+ Open sign-in+ <ExternalLinkIcon className="size-3.5" />+ </Button>+ </div>++ {flow.userCode ? (+ <div className="flex items-center gap-2 rounded-lg bg-background px-3 py-2">+ <code className="flex-1 text-sm font-semibold tracking-widest">{flow.userCode}</code>+ <Button+ size="icon-xs"+ variant="ghost"+ aria-label="Copy sign-in code"+ onClick={() => void navigator.clipboard.writeText(flow.userCode ?? "")}+ >+ <CopyIcon className="size-3.5" />+ </Button>+ </div>+ ) : null}++ {flow.completion === "paste" ? (+ <div className="flex gap-2">+ <Input+ value={pastedCode}+ onChange={(event) => onPastedCodeChange(event.currentTarget.value)}+ placeholder="Paste the authorization code"+ aria-label="Authorization code"+ className="flex-1"+ />+ <Button+ size="xs"+ disabled={pastedCode.trim().length === 0 || completing}+ onClick={onComplete}+ >+ {completing ? <LoaderIcon className="size-3.5 animate-spin" /> : null}+ Connect+ </Button>+ </div>+ ) : (+ <div className="flex items-center gap-2 text-[13px] text-muted-foreground">+ <LoaderIcon className="size-3.5 animate-spin" />+ Waiting for approval…+ </div>+ )}++ {login.error ? <p className="text-[13px] text-destructive">{login.error}</p> : null}++ <Button size="xs" variant="ghost-muted" onClick={onCancel}>+ Cancel+ </Button>+ </div>+ );+}++export function ProvidersPanel() {+ const environmentId = usePrimaryEnvironmentId();+ const statusQuery = useEnvironmentQuery(+ environmentId === null+ ? null+ : serverEnvironment.subscriptionAuth({ environmentId, input: {} }),+ );+ const startAuth = useAtomCommand(serverEnvironment.startSubscriptionAuth, {+ reportFailure: false,+ });+ const pollAuth = useAtomCommand(serverEnvironment.pollSubscriptionAuth, {+ reportFailure: false,+ });+ const completeAuth = useAtomCommand(serverEnvironment.completeSubscriptionAuth, {+ reportFailure: false,+ });+ const cancelAuth = useAtomCommand(serverEnvironment.cancelSubscriptionAuth, {+ reportFailure: false,+ });+ const logoutAuth = useAtomCommand(serverEnvironment.logoutSubscriptionAuth, {+ reportFailure: false,+ });++ const [activeLogin, setActiveLogin] = useState<ActiveLogin | null>(null);+ const [busyProvider, setBusyProvider] = useState<SubscriptionProviderId | null>(null);+ const [pastedCode, setPastedCode] = useState("");+ const [completing, setCompleting] = useState(false);++ const statusByProvider = useMemo(+ () => new Map(statusQuery.data?.providers.map((status) => [status.provider, status]) ?? []),+ [statusQuery.data],+ );++ const settleLogin = useCallback(+ (progress: SubscriptionAuthLoginProgress) => {+ if (progress.status === "connected") {+ setActiveLogin(null);+ setBusyProvider(null);+ setPastedCode("");+ statusQuery.refresh();+ return true;+ }+ if (progress.status === "failed") {+ setActiveLogin((current) => (current ? { ...current, error: progress.error } : current));+ setBusyProvider(null);+ }+ return false;+ },+ [statusQuery],+ );++ useEffect(() => {+ if (!activeLogin || activeLogin.flow.completion !== "poll" || environmentId === null) return;++ let cancelled = false;+ let timer: ReturnType<typeof setTimeout> | undefined;+ const poll = async () => {+ const result = await pollAuth({+ environmentId,+ input: { loginId: activeLogin.flow.loginId },+ });+ if (cancelled || isAtomCommandInterrupted(result)) return;+ if (result._tag === "Failure") {+ setActiveLogin((current) =>+ current ? { ...current, error: commandError(result) } : current,+ );+ setBusyProvider(null);+ return;+ }+ if (settleLogin(result.value)) return;+ if (result.value.status === "pending") {+ timer = setTimeout(poll, Math.max(1000, result.value.nextPollMs));+ }+ };++ timer = setTimeout(poll, 1000);+ return () => {+ cancelled = true;+ if (timer) clearTimeout(timer);+ };+ }, [activeLogin, environmentId, pollAuth, settleLogin]);++ const connect = async (definition: SubscriptionProviderDefinition) => {+ if (environmentId === null) return;+ setBusyProvider(definition.id);+ const result = await startAuth({+ environmentId,+ input: { provider: definition.id },+ });+ if (isAtomCommandInterrupted(result)) return;+ if (result._tag === "Failure") {+ setBusyProvider(null);+ return;+ }+ setActiveLogin({ flow: result.value, providerLabel: definition.label, error: null });+ window.open(result.value.url, "_blank", "noopener,noreferrer");+ };++ const complete = async () => {+ if (environmentId === null || !activeLogin) return;+ setCompleting(true);+ const result = await completeAuth({+ environmentId,+ input: { loginId: activeLogin.flow.loginId, code: pastedCode },+ });+ setCompleting(false);+ if (isAtomCommandInterrupted(result)) return;+ if (result._tag === "Failure") {+ setActiveLogin((current) =>+ current ? { ...current, error: commandError(result) } : current,+ );+ return;+ }+ settleLogin(result.value);+ };++ const cancelLogin = async () => {+ const login = activeLogin;+ setActiveLogin(null);+ setBusyProvider(null);+ setPastedCode("");+ if (environmentId === null || !login) return;+ await cancelAuth({ environmentId, input: { loginId: login.flow.loginId } });+ };++ const disconnect = async (provider: SubscriptionProviderId) => {+ if (environmentId === null) return;+ setBusyProvider(provider);+ const result = await logoutAuth({ environmentId, input: { provider } });+ setBusyProvider(null);+ if (result._tag === "Success") statusQuery.refresh();+ };++ if (activeLogin) {+ return (+ <SettingsPageContainer>+ <SettingsSection title={`Connect ${activeLogin.providerLabel}`}>+ <ActiveLoginPanel+ login={activeLogin}+ pastedCode={pastedCode}+ onPastedCodeChange={setPastedCode}+ onComplete={() => void complete()}+ onCancel={() => void cancelLogin()}+ completing={completing}+ />+ </SettingsSection>+ </SettingsPageContainer>+ );+ }++ return (+ <SettingsPageContainer>+ <SettingsSection title="Subscriptions">+ <div className="px-3 pb-2 text-[13px] leading-[1.45] text-muted-foreground sm:px-4">+ Connect accounts you already pay for. Akeru uses the coding access included with each+ subscription. Tokens stay on this Akeru server.+ </div>++ {statusQuery.error ? (+ <div className="mx-3 rounded-xl border border-destructive/30 bg-destructive/5 p-3 text-sm text-destructive sm:mx-4">+ {statusQuery.error}+ </div>+ ) : null}++ {SUBSCRIPTION_PROVIDERS.map((definition) => (+ <ProviderLoginCard+ key={definition.id}+ definition={definition}+ status={statusByProvider.get(definition.id)}+ busy={busyProvider === definition.id || statusQuery.isPending}+ onConnect={() => void connect(definition)}+ onDisconnect={() => void disconnect(definition.id)}+ />+ ))}+ </SettingsSection>++ <SettingsSection title="How credentials are used">+ <SettingsRow+ title={+ <span className="flex items-center gap-2">+ <CheckIcon className="size-4 text-success" />+ Stored on your Akeru server+ </span>+ }+ description="Refresh tokens never enter a project or sandbox. A run receives only the short-lived access token it needs."+ />+ </SettingsSection>+ </SettingsPageContainer>+ );+}diff --git a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsxindex 741cd3c3f..8b22aba2a 100644--- a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx+++ b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx@@ -136,7 +136,7 @@ function categoryLabel(category: ResourceTelemetryProcessCategory): string {case "resource-monitor":return "Monitor";case "unknown-t3":- return "T3 process";+ return "Akeru Bot process";}}@@ -996,7 +996,7 @@ export function ResourceTelemetryDiagnostics() {<div className="flex flex-col gap-3 border-b border-border/60 bg-linear-to-r from-muted/45 via-muted/20 to-transparent px-4 py-4 sm:flex-row sm:items-center sm:justify-between sm:px-5"><div><div className="text-[10px] font-semibold uppercase tracking-[0.14em] text-muted-foreground/70">- T3 system footprint+ Akeru Bot system footprint</div><p className="mt-1 max-w-xl text-xs leading-relaxed text-muted-foreground">Live native counters for the server, providers, terminals, desktop processes, and@@ -1279,8 +1279,8 @@ export function ResourceTelemetryDiagnostics() {<div className="overflow-hidden rounded-2xl border border-border/70 bg-card shadow-[0_1px_1px_rgb(0_0_0/0.03)]"><div className="bg-muted/15 px-4 py-3 text-[11px] leading-relaxed text-muted-foreground sm:px-5">Native counters identify which process is reading or writing. These application-level- counters identify known T3 operations so process spikes can be correlated with specific- persistence and logging paths.+ counters identify known Akeru Bot operations so process spikes can be correlated with+ specific persistence and logging paths.</div><AttributionTable entries={snapshot?.attribution.entries ?? []} /></div>diff --git a/apps/web/src/components/settings/SettingsBreadcrumb.tsx b/apps/web/src/components/settings/SettingsBreadcrumb.tsxdeleted file mode 100644index bb631187c..000000000--- a/apps/web/src/components/settings/SettingsBreadcrumb.tsx+++ /dev/null@@ -1,34 +0,0 @@-import {- WorkspaceBreadcrumb,- WorkspaceBreadcrumbItem,- WorkspaceBreadcrumbSeparator,-} from "../WorkspaceBreadcrumb";-import { SETTINGS_SECTION_LABELS } from "./settingsSearch";--const SETTINGS_BREADCRUMB_LABELS: Readonly<Record<string, string>> = {- ...SETTINGS_SECTION_LABELS,- "/settings/diagnostics": "Diagnostics",-};--function settingsBreadcrumbLabel(pathname: string): string | null {- const normalizedPathname = pathname.replace(/\/+$/, "") || "/";- return SETTINGS_BREADCRUMB_LABELS[normalizedPathname] ?? null;-}--export function SettingsBreadcrumb({ pathname }: { pathname: string }) {- const sectionLabel = settingsBreadcrumbLabel(pathname);-- return (- <WorkspaceBreadcrumb ariaLabel="Settings breadcrumb">- {sectionLabel ? (- <>- <WorkspaceBreadcrumbItem>Settings</WorkspaceBreadcrumbItem>- <WorkspaceBreadcrumbSeparator />- </>- ) : null}- <WorkspaceBreadcrumbItem current className="truncate">- {sectionLabel ?? "Settings"}- </WorkspaceBreadcrumbItem>- </WorkspaceBreadcrumb>- );-}diff --git a/apps/web/src/components/settings/SettingsDialog.tsx b/apps/web/src/components/settings/SettingsDialog.tsxnew file mode 100644index 000000000..31480c50b--- /dev/null+++ b/apps/web/src/components/settings/SettingsDialog.tsx@@ -0,0 +1,119 @@+import {+ BotIcon,+ KeyboardIcon,+ Link02Icon,+ PaintBrush01Icon,+ Settings02Icon,+} from "@hugeicons/core-free-icons";+import type { IconSvgElement } from "@hugeicons/react";+import { Suspense, lazy, type ComponentType } from "react";++import { cn } from "~/lib/utils";+import { Dialog, DialogPopup, DialogTitle } from "~/components/ui/dialog";+import { AppIcon } from "~/components/ui/app-icon";+import { Spinner } from "~/components/ui/spinner";+import { closeSettings, useSettingsDialogStore, type SettingsSection } from "~/settingsDialogStore";++const GeneralSettingsPanel = lazy(async () => ({+ default: (await import("./SettingsPanels")).GeneralSettingsPanel,+}));+const AppearanceSettingsPanel = lazy(async () => ({+ default: (await import("./SettingsPanels")).AppearanceSettingsPanel,+}));+const ProvidersPanel = lazy(async () => ({+ default: (await import("./ProvidersPanel")).ProvidersPanel,+}));+const ConnectionsSettings = lazy(async () => ({+ default: (await import("./ConnectionsSettings")).ConnectionsSettings,+}));+const KeybindingsSettingsPanel = lazy(async () => ({+ default: (await import("./KeybindingsSettings")).KeybindingsSettingsPanel,+}));+const SourceControlSettingsPanel = lazy(async () => ({+ default: (await import("./SourceControlSettings")).SourceControlSettingsPanel,+}));+const DiagnosticsSettingsPanel = lazy(async () => ({+ default: (await import("./DiagnosticsSettings")).DiagnosticsSettingsPanel,+}));++const SECTION_PANELS: Readonly<Record<SettingsSection, ComponentType>> = {+ general: GeneralSettingsPanel,+ appearance: AppearanceSettingsPanel,+ providers: ProvidersPanel,+ connections: ConnectionsSettings,+ keybindings: KeybindingsSettingsPanel,+ "source-control": SourceControlSettingsPanel,+ diagnostics: DiagnosticsSettingsPanel,+};++/** Sections with a nav row. Anything else is reached from a link inside a panel. */+const NAV_ITEMS: ReadonlyArray<{+ readonly section: SettingsSection;+ readonly label: string;+ readonly icon: IconSvgElement;+}> = [+ { section: "general", label: "General", icon: Settings02Icon },+ { section: "appearance", label: "Appearance", icon: PaintBrush01Icon },+ { section: "providers", label: "Providers", icon: BotIcon },+ { section: "connections", label: "Connections", icon: Link02Icon },+ { section: "keybindings", label: "Keybindings", icon: KeyboardIcon },+];++export function SettingsDialog() {+ const section = useSettingsDialogStore((state) => state.section);+ const openSettings = useSettingsDialogStore((state) => state.openSettings);+ const Panel = section ? SECTION_PANELS[section] : null;++ return (+ <Dialog+ open={section !== null}+ onOpenChange={(open) => {+ if (!open) closeSettings();+ }}+ >+ <DialogPopup+ className="h-[min(44rem,88dvh)] max-w-4xl flex-row overflow-hidden max-sm:flex-col"+ bottomStickOnMobile={false}+ >+ <DialogTitle className="sr-only">Settings</DialogTitle>+ <nav+ aria-label="Settings sections"+ className="flex w-52 shrink-0 flex-col gap-0.5 border-e bg-muted/30 p-2 max-sm:w-full max-sm:flex-row max-sm:overflow-x-auto max-sm:border-e-0 max-sm:border-b"+ >+ {NAV_ITEMS.map((item) => {+ const isActive = section === item.section;+ return (+ <button+ key={item.section}+ type="button"+ aria-current={isActive ? "page" : undefined}+ onClick={() => openSettings(item.section)}+ className={cn(+ "flex h-8 shrink-0 items-center gap-2 rounded-md px-2 text-sm font-medium transition-colors",+ isActive+ ? "bg-accent text-accent-foreground"+ : "text-muted-foreground hover:bg-accent/50 hover:text-foreground",+ )}+ >+ <AppIcon className="size-4 shrink-0" icon={item.icon} />+ <span className="truncate">{item.label}</span>+ </button>+ );+ })}+ </nav>++ <div className="flex min-h-0 min-w-0 flex-1 flex-col">+ <Suspense+ fallback={+ <div className="flex flex-1 items-center justify-center">+ <Spinner />+ </div>+ }+ >+ {Panel ? <Panel /> : null}+ </Suspense>+ </div>+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsxindex e77c05549..068dfe2f6 100644--- a/apps/web/src/components/settings/SettingsPanels.tsx+++ b/apps/web/src/components/settings/SettingsPanels.tsx@@ -1,5 +1,4 @@import { ArchiveIcon, ArchiveX, ChevronRightIcon, LoaderIcon, SettingsIcon } from "lucide-react";-import { Link } from "@tanstack/react-router";import type { CSSProperties, ReactNode } from "react";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useAtomValue } from "@effect/atom-react";@@ -55,6 +54,7 @@ import {useEnvironmentStageLabel,} from "../SidebarStageBackdrop";import { isElectron } from "../../env";+import { openSettings } from "../../settingsDialogStore";import { buildHostedChannelSelectionUrl, type HostedAppChannel } from "../../hostedPairing";import { useCustomThemes } from "../../hooks/useCustomThemes";import {@@ -488,6 +488,9 @@ export function useSettingsRestore(onRestored?: () => void) {...(settings.timestampFormat !== DEFAULT_UNIFIED_SETTINGS.timestampFormat? ["Time format"]: []),+ ...(settings.usageRefreshMinutes !== DEFAULT_UNIFIED_SETTINGS.usageRefreshMinutes+ ? ["Usage refresh"]+ : []),...(settings.sidebarThreadPreviewCount !== DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount? ["Visible threads"]: []),@@ -578,6 +581,7 @@ export function useSettingsRestore(onRestored?: () => void) {settings.sidebarThreadPreviewCount,settings.showSkillsInSlashMenu,settings.timestampFormat,+ settings.usageRefreshMinutes,settings.wordWrap,followSystem,theme,@@ -650,6 +654,7 @@ export function useSettingsRestore(onRestored?: () => void) {updateSettings({appearanceContrast: DEFAULT_UNIFIED_SETTINGS.appearanceContrast,timestampFormat: DEFAULT_UNIFIED_SETTINGS.timestampFormat,+ usageRefreshMinutes: DEFAULT_UNIFIED_SETTINGS.usageRefreshMinutes,wordWrap: DEFAULT_UNIFIED_SETTINGS.wordWrap,diffIgnoreWhitespace: DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace,showSkillsInSlashMenu: DEFAULT_UNIFIED_SETTINGS.showSkillsInSlashMenu,@@ -1833,19 +1838,6 @@ function LegacyFeaturesSection() {/>}/>- <SettingsRow- {...searchableSetting("legacy-sidebar")}- description="Brings back the original sidebar with per-project thread trees. The default sidebar shows one flat list: active work as rich cards, settled threads as compact rows."- control={- <Switch- checked={settings.legacySidebarEnabled}- onCheckedChange={(checked) =>- updateSettings({ legacySidebarEnabled: Boolean(checked) })- }- aria-label="Sidebar (legacy)"- />- }- /></div></CollapsiblePanel></Collapsible>@@ -2055,6 +2047,52 @@ export function GeneralSettingsPanel() {}/>+ <SettingsRow+ {...searchableSetting("usage-refresh")}+ description="How often the Usage page reloads plan limits."+ resetAction={+ settings.usageRefreshMinutes !== DEFAULT_UNIFIED_SETTINGS.usageRefreshMinutes ? (+ <SettingResetButton+ label="usage refresh"+ onClick={() =>+ updateSettings({+ usageRefreshMinutes: DEFAULT_UNIFIED_SETTINGS.usageRefreshMinutes,+ })+ }+ />+ ) : null+ }+ control={+ <Select+ value={String(settings.usageRefreshMinutes)}+ onValueChange={(value) => {+ const minutes = Number(value);+ if (minutes === 1 || minutes === 5 || minutes === 15 || minutes === 30) {+ updateSettings({ usageRefreshMinutes: minutes });+ }+ }}+ >+ <SelectTrigger className="w-full sm:w-40" aria-label="Usage refresh">+ <SelectValue>{`${settings.usageRefreshMinutes} min`}</SelectValue>+ </SelectTrigger>+ <SelectPopup align="end" alignItemWithTrigger={false}>+ <SelectItem hideIndicator value="1">+ 1 min+ </SelectItem>+ <SelectItem hideIndicator value="5">+ 5 min+ </SelectItem>+ <SelectItem hideIndicator value="15">+ 15 min+ </SelectItem>+ <SelectItem hideIndicator value="30">+ 30 min+ </SelectItem>+ </SelectPopup>+ </Select>+ }+ />+<SettingsRow{...searchableSetting("hide-whitespace-changes")}description="Set whether the diff panel ignores whitespace-only edits by default."@@ -2485,7 +2523,7 @@ export function GeneralSettingsPanel() {{...searchableSetting("diagnostics")}description={diagnosticsDescription}control={- <Button render={<Link to="/settings/diagnostics" />} size="xs" variant="outline">+ <Button size="xs" variant="outline" onClick={() => openSettings("diagnostics")}>View diagnostics</Button>}diff --git a/apps/web/src/components/settings/SettingsSidebarNav.tsx b/apps/web/src/components/settings/SettingsSidebarNav.tsxdeleted file mode 100644index 734c2989d..000000000--- a/apps/web/src/components/settings/SettingsSidebarNav.tsx+++ /dev/null@@ -1,297 +0,0 @@-import {- useCallback,- useEffect,- useMemo,- useRef,- useState,- type ComponentType,- type KeyboardEvent,-} from "react";-import {- ArchiveIcon,- BlocksIcon,- BotIcon,- GitBranchIcon,- KeyboardIcon,- Link2Icon,- PaletteIcon,- SearchIcon,- Settings2Icon,- XIcon,-} from "lucide-react";-import { useLocation, useNavigate } from "@tanstack/react-router";--import { Button } from "../ui/button";-import { Input } from "../ui/input";-import { Kbd } from "../ui/kbd";-import {- SidebarContent,- SidebarFooter,- SidebarGroup,- SidebarMenu,- SidebarMenuButton,- SidebarMenuItem,- useSidebar,-} from "../ui/sidebar";-import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";-import { SidebarUtilityMenu } from "../sidebar/SidebarChrome";-import { scrollToSettingsTarget } from "./settingsLayout";-import {- searchSettings,- SETTINGS_SECTION_LABELS,- type SettingsPath,- type SettingsSearchItem,-} from "./settingsSearch";--const SETTINGS_SECTION_ICONS: Readonly<- Record<SettingsPath, ComponentType<{ className?: string }>>-> = {- "/settings/general": Settings2Icon,- "/settings/appearance": PaletteIcon,- "/settings/keybindings": KeyboardIcon,- "/settings/providers": BotIcon,- "/settings/integrations": BlocksIcon,- "/settings/source-control": GitBranchIcon,- "/settings/connections": Link2Icon,- "/settings/archived": ArchiveIcon,-};--export const SETTINGS_NAV_ITEMS: ReadonlyArray<{- label: string;- to: SettingsPath;- icon: ComponentType<{ className?: string }>;-}> = (Object.keys(SETTINGS_SECTION_LABELS) as SettingsPath[]).map((to) => ({- to,- label: SETTINGS_SECTION_LABELS[to],- icon: SETTINGS_SECTION_ICONS[to],-}));--function SettingsSectionIcon({ to }: { to: SettingsPath }) {- const Icon = SETTINGS_SECTION_ICONS[to];- return <Icon className="mt-0.5 size-3.5 shrink-0 text-sidebar-muted-foreground/60" />;-}--export function SettingsSidebarNav({ pathname }: { pathname: string }) {- const navigate = useNavigate();- const currentHash = useLocation({ select: (location) => location.hash });- const { isMobile, setOpenMobile, open, setOpen } = useSidebar();- const searchInputRef = useRef<HTMLInputElement>(null);- const [query, setQuery] = useState("");- const [activeResultIndex, setActiveResultIndex] = useState(0);- const results = useMemo(() => searchSettings(query), [query]);- const isSearching = query.trim().length > 0;- const hasResults = results.length > 0;-- useEffect(() => {- const result = results[activeResultIndex];- if (!result) return;- document- .getElementById(`settings-search-result-${result.id}`)- ?.scrollIntoView({ block: "nearest" });- }, [activeResultIndex, results]);-- useEffect(() => {- const handleKeyDown = (event: globalThis.KeyboardEvent) => {- if (event.key !== "/" || event.metaKey || event.ctrlKey || event.altKey) return;-- const target = event.target;- if (- target instanceof HTMLElement &&- (target.tagName === "INPUT" ||- target.tagName === "TEXTAREA" ||- target.isContentEditable ||- // Keep focus inside open dialogs and popups instead of escaping- // their focus trap into the sidebar search.- target.closest('[role="dialog"], [aria-modal="true"], [data-slot$="popup"]') !== null)- ) {- return;- }-- event.preventDefault();- if (isMobile) {- setOpenMobile(true);- } else if (!open) {- setOpen(true);- }- requestAnimationFrame(() => {- searchInputRef.current?.focus();- searchInputRef.current?.select();- });- };- window.addEventListener("keydown", handleKeyDown);- return () => window.removeEventListener("keydown", handleKeyDown);- }, [isMobile, open, setOpen, setOpenMobile]);-- const handleSectionClick = useCallback(- (to: SettingsPath) => {- if (isMobile) {- setOpenMobile(false);- }- void navigate({ to, hash: "", replace: true, hashScrollIntoView: false });- },- [isMobile, navigate, setOpenMobile],- );- const clearSearch = useCallback(() => {- setQuery("");- setActiveResultIndex(0);- }, []);- const handleSearchResultClick = useCallback(- (item: SettingsSearchItem) => {- clearSearch();- if (isMobile) {- setOpenMobile(false);- }- const targetId = item.targetId ?? item.id;- if (pathname === item.to && currentHash.replace(/^#/, "") === targetId) {- scrollToSettingsTarget(targetId);- return;- }- void navigate({ to: item.to, hash: targetId, replace: true, hashScrollIntoView: false });- },- [clearSearch, currentHash, isMobile, navigate, pathname, setOpenMobile],- );- const handleSearchKeyDown = useCallback(- (event: KeyboardEvent<HTMLInputElement>) => {- if (event.key === "Escape" && isSearching) {- event.preventDefault();- event.stopPropagation();- clearSearch();- return;- }- if (results.length === 0) return;- if (event.key === "ArrowDown") {- event.preventDefault();- setActiveResultIndex((index) => (index + 1) % results.length);- return;- }- if (event.key === "ArrowUp") {- event.preventDefault();- setActiveResultIndex((index) => (index - 1 + results.length) % results.length);- return;- }- if (event.key === "Enter") {- event.preventDefault();- const result = results[activeResultIndex];- if (result) handleSearchResultClick(result);- }- },- [activeResultIndex, clearSearch, handleSearchResultClick, isSearching, results],- );- return (- <>- <SidebarContent className="overflow-x-hidden">- <SidebarGroup className="gap-2 p-[var(--sidebar-content-inset)]">- <div className="flex h-8 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground">- <SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />- <Input- ref={searchInputRef}- nativeInput- unstyled- type="search"- value={query}- onChange={(event) => {- setQuery(event.currentTarget.value);- setActiveResultIndex(0);- }}- onKeyDown={handleSearchKeyDown}- placeholder="Search"- aria-label="Search settings"- role="combobox"- aria-autocomplete="list"- aria-expanded={isSearching && hasResults}- aria-controls={isSearching && hasResults ? "settings-search-results" : undefined}- aria-activedescendant={- isSearching && results[activeResultIndex]- ? `settings-search-result-${results[activeResultIndex].id}`- : undefined- }- className="min-w-0 flex-1 [&_[data-slot=input]]:h-auto [&_[data-slot=input]]:p-0 [&_[data-slot=input]]:leading-normal [&_[data-slot=input]]:text-sm [&_[data-slot=input]]:font-medium [&_[data-slot=input]]:text-sidebar-foreground [&_[data-slot=input]]:placeholder:text-sidebar-muted-foreground"- />- {isSearching ? (- <Button- type="button"- size="icon-micro"- variant="ghost"- className="shrink-0 text-sidebar-muted-foreground hover:bg-sidebar-control-surface hover:text-sidebar-foreground"- aria-label="Clear settings search"- onClick={() => {- clearSearch();- searchInputRef.current?.focus();- }}- >- <XIcon className="size-3" />- </Button>- ) : (- <Kbd className="h-4 min-w-0 rounded-sm px-1.5 text-[10px]">/</Kbd>- )}- </div>- {isSearching && results.length === 0 ? (- <p- role="status"- className="px-2 py-6 text-center text-xs text-sidebar-muted-foreground"- >- No settings found- </p>- ) : null}- <SidebarMenu- className="ps-px"- id={isSearching && hasResults ? "settings-search-results" : undefined}- role={isSearching && hasResults ? "listbox" : undefined}- aria-label={isSearching && hasResults ? "Settings search results" : undefined}- >- {isSearching- ? results.map((item, index) => (- <SidebarMenuItem key={item.id} role="presentation">- <SidebarMenuButton- id={`settings-search-result-${item.id}`}- role="option"- aria-selected={index === activeResultIndex}- tabIndex={-1}- size="sm"- isActive={index === activeResultIndex}- className="h-auto min-h-10 items-start gap-2 rounded-md px-2 py-2 text-left hover:bg-sidebar-row-hover hover:text-sidebar-foreground"- onMouseMove={() => setActiveResultIndex(index)}- onClick={() => handleSearchResultClick(item)}- >- <SettingsSectionIcon to={item.to} />- <span className="min-w-0 flex-1">- <span className="block truncate text-sm font-medium text-sidebar-foreground">- {item.title}- </span>- <span className="block truncate text-[11px] text-sidebar-muted-foreground/75">- {SETTINGS_SECTION_LABELS[item.to]}- </span>- </span>- </SidebarMenuButton>- </SidebarMenuItem>- ))- : SETTINGS_NAV_ITEMS.map((item) => {- const Icon = item.icon;- const isActive = pathname === item.to || pathname.startsWith(`${item.to}/`);- return (- <SidebarMenuItem key={item.to}>- <SidebarMenuButton- isActive={isActive}- onClick={() => handleSectionClick(item.to)}- >- <Icon />- <span className="truncate">{item.label}</span>- </SidebarMenuButton>- </SidebarMenuItem>- );- })}- </SidebarMenu>- </SidebarGroup>- </SidebarContent>- <SidebarFooter className="p-[var(--sidebar-content-inset)]">- <T3ConnectSidebarSignIn />- <div className="flex items-center gap-1">- <div className="min-w-0 flex-1">- <SidebarUtilityMenu />- </div>- <T3ConnectSidebarAvatar />- </div>- </SidebarFooter>- </>- );-}diff --git a/apps/web/src/components/settings/ThemeImportDialog.tsx b/apps/web/src/components/settings/ThemeImportDialog.tsxindex 891294960..bc7416e09 100644--- a/apps/web/src/components/settings/ThemeImportDialog.tsx+++ b/apps/web/src/components/settings/ThemeImportDialog.tsx@@ -525,7 +525,7 @@ export function ThemeImportDialog({<div className="min-w-0"><p className="text-sm font-medium">Theme file</p><p className="truncate text-xs text-muted-foreground">- {fileName ?? "Drop T3 Code or VS Code .json files"}+ {fileName ?? "Drop Akeru Bot or VS Code .json files"}</p></div>{chooseButton()}diff --git a/apps/web/src/components/settings/ThemePreviewCircles.tsx b/apps/web/src/components/settings/ThemePreviewCircles.tsxindex 1ac8fa734..05652bc14 100644--- a/apps/web/src/components/settings/ThemePreviewCircles.tsx+++ b/apps/web/src/components/settings/ThemePreviewCircles.tsx@@ -58,7 +58,7 @@ const STANDARD_THEME_PREVIEW_COLORS: Record<export const STANDARD_THEME_CARDS: ReadonlyArray<ThemeCardDefinition> = [{id: "default",- label: "T3 Code",+ label: "T3 Code (Legacy)",previews: (["light", "dark"] as const).map((mode) => ({mode,colors: STANDARD_THEME_PREVIEW_COLORS[mode],diff --git a/apps/web/src/components/settings/ThemeSettings.tsx b/apps/web/src/components/settings/ThemeSettings.tsxindex 929e00d6c..1f93dea55 100644--- a/apps/web/src/components/settings/ThemeSettings.tsx+++ b/apps/web/src/components/settings/ThemeSettings.tsx@@ -12,6 +12,7 @@ import {import { useCallback, useEffect, useState, type ReactElement } from "react";import { cn } from "../../lib/utils";import {+ BUILT_IN_THEMES,getThemeDefinition,getThemeModes,removeCustomThemes,@@ -19,11 +20,6 @@ import {type ThemeAppearance,type ThemeDefinition,type ThemeHalves,- T3_CHAT_THEME,- EMBER_THEME,- GROVE_THEME,- IRIS_THEME,- OCEAN_THEME,} from "../../themePalette";import {AlertDialog,@@ -50,13 +46,7 @@ import {} from "./ThemePreviewCircles";import { ThemeWireframe } from "./ThemeWireframe";-const MAINTAINER_THEMES: ReadonlyArray<ThemeDefinition> = [- T3_CHAT_THEME,- GROVE_THEME,- OCEAN_THEME,- EMBER_THEME,- IRIS_THEME,-];+const MAINTAINER_THEMES: ReadonlyArray<ThemeDefinition> = BUILT_IN_THEMES;function collectionVariantLabels(themes: ReadonlyArray<ThemeDefinition>): ReadonlyArray<string> {if (themes.length === 0) return [];@@ -849,7 +839,7 @@ export function ThemeLibrary({return (<div className="space-y-3"><p className="px-3 text-[13px] leading-[1.45] text-muted-foreground/80 sm:px-4">- Choose how T3 Code looks. Use a built-in theme or make your own.+ Choose how Akeru Bot looks. Use a built-in theme or make your own.</p><h3 className="px-3 text-sm font-medium tracking-[-0.005em] text-foreground sm:px-4">Color schemediff --git a/apps/web/src/components/settings/providerStatus.ts b/apps/web/src/components/settings/providerStatus.tsindex 06622a761..3bdeb70ce 100644--- a/apps/web/src/components/settings/providerStatus.ts+++ b/apps/web/src/components/settings/providerStatus.ts@@ -39,7 +39,8 @@ export function getProviderSummary(provider: ServerProvider | undefined) {return {headline: "Disabled",detail:- provider.message ?? "This provider is installed but disabled for new sessions in T3 Code.",+ provider.message ??+ "This provider is installed but disabled for new sessions in Akeru Bot.",};}if (!provider.installed) {diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.tsindex 5213cb55a..2c813f401 100644--- a/apps/web/src/components/settings/settingsSearch.ts+++ b/apps/web/src/components/settings/settingsSearch.ts@@ -126,6 +126,11 @@ export const SETTINGS_SEARCH_ITEMS = [title: "Time format",to: "/settings/general",},+ {+ id: "usage-refresh",+ title: "Usage refresh",+ to: "/settings/general",+ },{id: "hide-whitespace-changes",title: "Hide whitespace changes",diff --git a/apps/web/src/components/sidebar/SidebarChrome.test.ts b/apps/web/src/components/sidebar/SidebarChrome.test.tsnew file mode 100644index 000000000..6d6720b86--- /dev/null+++ b/apps/web/src/components/sidebar/SidebarChrome.test.ts@@ -0,0 +1,49 @@+// @effect-diagnostics nodeBuiltinImport:off - This integration guard reads related source files.+import * as NodeFS from "node:fs";++import { describe, expect, it } from "vite-plus/test";++import { formatEnabledPluginStatus } from "./SidebarChrome";++describe("sidebar footer", () => {+ it("describes real enabled state without claiming an account connection", () => {+ expect(formatEnabledPluginStatus(0)).toBe("No plugins enabled");+ expect(formatEnabledPluginStatus(1)).toBe("1 plugin enabled");+ expect(formatEnabledPluginStatus(3)).toBe("3 plugins enabled");+ });++ it("shows the verified remote-access account identity when Clerk is configured", () => {+ const source = NodeFS.readFileSync(+ new URL("../clerk/T3ConnectSidebarSignIn.tsx", import.meta.url),+ "utf8",+ );++ expect(source).toContain("showName");+ expect(source).toContain("Sign in for remote access");+ });++ it("keeps the roster scrollable from touch gestures that start on a bot row", () => {+ const source = NodeFS.readFileSync(+ new URL("../roster/BotRosterSidebar.tsx", import.meta.url),+ "utf8",+ );++ expect(source).toContain("touch-pan-y");+ expect(source).not.toContain("touch-none");+ });++ it("keeps short plugin dialogs and the footer independently scrollable", () => {+ const sidebarSource = NodeFS.readFileSync(+ new URL("./SidebarChrome.tsx", import.meta.url),+ "utf8",+ );+ const pluginsSource = NodeFS.readFileSync(+ new URL("../plugins/PluginsDialog.tsx", import.meta.url),+ "utf8",+ );++ expect(sidebarSource).toContain("overflow-y-auto overscroll-contain");+ expect(pluginsSource).toContain("PLUGIN_DIRECTORY_HEADER_CLASS_NAME");+ expect(pluginsSource).toContain('<DialogPanel className="space-y-4 px-6 py-5">');+ });+});diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsxindex 8fc6b835b..a7562673f 100644--- a/apps/web/src/components/sidebar/SidebarChrome.tsx+++ b/apps/web/src/components/sidebar/SidebarChrome.tsx@@ -1,16 +1,22 @@-import {- ArrowLeftIcon,- ChartNoAxesColumnIcon,- GitPullRequestIcon,- SettingsIcon,-} from "lucide-react";+import { useAtomValue } from "@effect/atom-react";+import { Analytics01Icon, PlugSocketIcon, Settings02Icon } from "@hugeicons/core-free-icons";+import type { EnvironmentId } from "@t3tools/contracts";+import { Link } from "@tanstack/react-router";import type { ReactNode } from "react";import { memo, useCallback } from "react";-import { Link, useCanGoBack, useLocation, useNavigate } from "@tanstack/react-router";+import { loadCatalog } from "../../../../../plugins";import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";+import { openSettings } from "../../settingsDialogStore";+import { openPlugins } from "../../pluginsDialogStore";+import { openUsage } from "../../usageDialogStore";+import { usePrimaryEnvironmentId } from "../../state/environments";+import { environmentMcpServersAtom } from "../../state/mcpServers";+import { AkeruMark } from "../AkeruMark";+import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";+import { PluginLogoImage } from "../plugins/PluginsCatalog";+import { findPluginServer, isBuiltinMcpServer } from "../plugins/pluginRegistry";import { cn } from "../../lib/utils";-import { useEnvironments } from "../../state/environments";import {resolveEnvironmentIdentificationPillLabel,resolveSidebarStageBackdropVariant,@@ -19,6 +25,7 @@ import {useEnvironmentStageLabel,} from "../SidebarStageBackdrop";import { Badge } from "../ui/badge";+import { AppIcon } from "../ui/app-icon";import {SidebarFooter,SidebarHeader,@@ -89,35 +96,107 @@ function SidebarBrand({ onBackdrop }: { onBackdrop: boolean }) {)}to="/">- <T3Wordmark />+ <AkeruMark aria-hidden /><spanclassName={cn("-translate-y-px truncate text-sm font-medium tracking-tight",onBackdrop ? "text-white/70" : "text-muted-foreground",)}>- Code+ Akeru Bot</span></Link>);}-function T3Wordmark() {+const PLUGIN_CATALOG = loadCatalog();++export function formatEnabledPluginStatus(enabledCount: number): string {+ if (enabledCount === 0) return "No plugins enabled";+ return `${enabledCount} ${enabledCount === 1 ? "plugin" : "plugins"} enabled`;+}++function SidebarPluginSummaryForEnvironment({+ environmentId,+ onClick,+}: {+ readonly environmentId: EnvironmentId;+ readonly onClick: () => void;+}) {+ const servers = useAtomValue(environmentMcpServersAtom(environmentId));+ const enabledPlugins = PLUGIN_CATALOG.filter(+ (plugin) => findPluginServer(plugin, servers)?.enabled,+ );+ const enabledCustomCount = servers.filter(+ (server) => server.enabled && !isBuiltinMcpServer(server),+ ).length;+ const enabledCount = enabledPlugins.length + enabledCustomCount;+ const statusLabel = formatEnabledPluginStatus(enabledCount);+return (- <svg- aria-label="T3"- className="h-2.5 w-auto shrink-0"- viewBox="15.5309 37 94.3941 56.96"- xmlns="http://www.w3.org/2000/svg"- >- <path- d="M33.4509 93V47.56H15.5309V37H64.3309V47.56H46.4109V93H33.4509ZM86.7253 93.96C82.832 93.96 78.9653 93.4533 75.1253 92.44C71.2853 91.3733 68.032 89.88 65.3653 87.96L70.4053 78.04C72.5386 79.5867 75.0186 80.8133 77.8453 81.72C80.672 82.6267 83.5253 83.08 86.4053 83.08C89.6586 83.08 92.2186 82.44 94.0853 81.16C95.952 79.88 96.8853 78.12 96.8853 75.88C96.8853 73.7467 96.0586 72.0667 94.4053 70.84C92.752 69.6133 90.0853 69 86.4053 69H80.4853V60.44L96.0853 42.76L97.5253 47.4H68.1653V37H107.365V45.4L91.8453 63.08L85.2853 59.32H89.0453C95.9253 59.32 101.125 60.8667 104.645 63.96C108.165 67.0533 109.925 71.0267 109.925 75.88C109.925 79.0267 109.099 81.9867 107.445 84.76C105.792 87.48 103.259 89.6933 99.8453 91.4C96.432 93.1067 92.0586 93.96 86.7253 93.96Z"- fill="currentColor"- />- </svg>+ <SidebarMenuItem>+ <Tooltip>+ <TooltipTrigger+ render={+ <SidebarMenuButton+ aria-label={`Plugins, ${statusLabel}`}+ className="h-auto min-h-12 gap-2 rounded-xl px-2 py-2 group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:min-h-8! group-data-[collapsible=icon]:justify-center group-data-[collapsible=icon]:p-0!"+ onClick={onClick}+ >+ <AppIcon className="size-[18px] shrink-0" icon={PlugSocketIcon} />+ <span className="flex min-w-0 flex-1 flex-col items-start group-data-[collapsible=icon]:hidden">+ <span className="text-sm font-medium leading-5">Plugins</span>+ <span className="truncate text-xs leading-4 text-sidebar-muted-foreground">+ {statusLabel}+ </span>+ </span>+ {enabledPlugins.length > 0 ? (+ <span+ aria-hidden="true"+ className="flex shrink-0 -space-x-1.5 group-data-[collapsible=icon]:hidden"+ >+ {enabledPlugins.slice(0, 3).map((plugin) => (+ <PluginLogoImage+ className="size-6 rounded-md"+ key={plugin.id}+ plugin={plugin}+ />+ ))}+ </span>+ ) : null}+ </SidebarMenuButton>+ }+ />+ <TooltipPopup side="right">{`Plugins · ${statusLabel}`}</TooltipPopup>+ </Tooltip>+ </SidebarMenuItem>);}+function SidebarPluginSummary({ onClick }: { readonly onClick: () => void }) {+ const environmentId = usePrimaryEnvironmentId();+ if (!environmentId) {+ return (+ <SidebarMenuItem>+ <SidebarMenuButton+ aria-label="Plugins, connect an environment to manage plugins"+ className="h-auto min-h-12 gap-2 rounded-xl px-2 py-2"+ onClick={onClick}+ >+ <AppIcon className="size-[18px] shrink-0" icon={PlugSocketIcon} />+ <span className="flex min-w-0 flex-1 flex-col items-start group-data-[collapsible=icon]:hidden">+ <span className="text-sm font-medium leading-5">Plugins</span>+ <span className="truncate text-xs leading-4 text-sidebar-muted-foreground">+ Connect an environment+ </span>+ </span>+ </SidebarMenuButton>+ </SidebarMenuItem>+ );+ }+ return <SidebarPluginSummaryForEnvironment environmentId={environmentId} onClick={onClick} />;+}+function SidebarUtilityItem({icon,label,@@ -128,12 +207,17 @@ function SidebarUtilityItem({onClick: () => void;}) {return (- <SidebarMenuItem className="shrink-0">+ <SidebarMenuItem className="min-w-0 flex-1 group-data-[collapsible=icon]:flex-none"><Tooltip><TooltipTriggerrender={- <SidebarMenuButton aria-label={label} onClick={onClick} size="icon">+ <SidebarMenuButton+ aria-label={label}+ className="w-full justify-center gap-1.5 text-xs group-data-[collapsible=icon]:size-8! group-data-[collapsible=icon]:p-0!"+ onClick={onClick}+ >{icon}+ <span className="group-data-[collapsible=icon]:hidden">{label}</span></SidebarMenuButton>}/>@@ -143,97 +227,50 @@ function SidebarUtilityItem({);}-export const SidebarUtilityMenu = memo(function SidebarUtilityMenu() {- const navigate = useNavigate();- const canGoBack = useCanGoBack();+export const SidebarChromeFooter = memo(function SidebarChromeFooter() {const { isMobile, setOpenMobile } = useSidebar();- const currentFooterPage = useLocation({- select: (location) =>- /^\/settings(?:\/|$)/.test(location.pathname)- ? "settings"- : location.pathname === "/usage"- ? "usage"- : location.pathname === "/pull-requests"- ? "pull-requests"- : null,- });- const { environments } = useEnvironments();- // The page reads every connected server, so one of them offering pull requests is enough for- // the link to lead somewhere.- const pullRequestsSupported = environments.some(- (environment) => environment.serverConfig?.environment.capabilities.pullRequests === true,- );const closeMobileSidebar = useCallback(() => {- if (isMobile) {- setOpenMobile(false);- }+ if (isMobile) setOpenMobile(false);}, [isMobile, setOpenMobile]);- const handlePullRequestsClick = useCallback(() => {+ const handlePluginsClick = useCallback(() => {closeMobileSidebar();- void navigate({ to: "/pull-requests", search: { involvement: "all", state: "open" } });- }, [closeMobileSidebar, navigate]);+ openPlugins();+ }, [closeMobileSidebar]);const handleSettingsClick = useCallback(() => {closeMobileSidebar();- void navigate({ to: "/settings" });- }, [closeMobileSidebar, navigate]);-+ openSettings();+ }, [closeMobileSidebar]);const handleUsageClick = useCallback(() => {- if (isMobile) {- setOpenMobile(false);- }- void navigate({ to: "/usage" });- }, [isMobile, navigate, setOpenMobile]);-- const handleBackClick = useCallback(() => {closeMobileSidebar();- if (canGoBack) {- window.history.back();- return;- }- void navigate({ to: "/" });- }, [canGoBack, closeMobileSidebar, navigate]);+ openUsage();+ }, [closeMobileSidebar]);return (- <SidebarMenu className="flex-row items-center">- {currentFooterPage ? (- <SidebarMenuItem className="min-w-0 flex-1">- <SidebarMenuButton onClick={handleBackClick}>- <ArrowLeftIcon />- <span>Back</span>- </SidebarMenuButton>- </SidebarMenuItem>- ) : (- <>- <SidebarUtilityItem- icon={<SettingsIcon />}- label="Settings"- onClick={handleSettingsClick}- />- {pullRequestsSupported ? (- <SidebarUtilityItem- icon={<GitPullRequestIcon />}- label="Pull Requests"- onClick={handlePullRequestsClick}- />- ) : null}- <SidebarUtilityItem- icon={<ChartNoAxesColumnIcon />}- label="Usage"- onClick={handleUsageClick}- />- </>- )}- <SidebarUpdatePill />- </SidebarMenu>- );-});--export const SidebarChromeFooter = memo(function SidebarChromeFooter() {- return (- <SidebarFooter className="p-[var(--sidebar-content-inset)]">- <SidebarProviderUpdatePill />- <SidebarUpdateArchitectureWarning />- <SidebarUtilityMenu />+ <SidebarFooter className="max-h-[min(45dvh,22rem)] shrink-0 overflow-y-auto overscroll-contain p-[var(--sidebar-content-inset)]">+ <div className="flex flex-col gap-2 empty:hidden group-data-[collapsible=icon]:hidden">+ <SidebarProviderUpdatePill />+ <SidebarUpdateArchitectureWarning />+ </div>+ <SidebarMenu>+ <SidebarPluginSummary onClick={handlePluginsClick} />+ </SidebarMenu>+ <div className="min-w-0 group-data-[collapsible=icon]:hidden">+ <T3ConnectSidebarSignIn />+ <T3ConnectSidebarAvatar />+ </div>+ <SidebarMenu className="flex-row items-center gap-1 group-data-[collapsible=icon]:flex-col">+ <SidebarUtilityItem+ icon={<AppIcon className="size-4" icon={Settings02Icon} />}+ label="Settings"+ onClick={handleSettingsClick}+ />+ <SidebarUtilityItem+ icon={<AppIcon className="size-4" icon={Analytics01Icon} />}+ label="Usage"+ onClick={handleUsageClick}+ />+ <SidebarUpdatePill />+ </SidebarMenu></SidebarFooter>);});diff --git a/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsxindex dcab7440a..ef067ec42 100644--- a/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx+++ b/apps/web/src/components/sidebar/SidebarProviderUpdatePill.tsx@@ -1,10 +1,10 @@-import { useNavigate } from "@tanstack/react-router";import { useAtomValue } from "@effect/atom-react";import type { ServerProvider } from "@t3tools/contracts";import { CircleCheckIcon, DownloadIcon, LoaderIcon, TriangleAlertIcon, XIcon } from "lucide-react";import { useCallback, useEffect, useState, type CSSProperties } from "react";import { primaryServerProvidersAtom } from "../../state/server";+import { openSettings } from "../../settingsDialogStore";import {getProviderUpdateSidebarPillView,type ProviderUpdateSidebarPillView,@@ -40,7 +40,6 @@ function latestProviderCheckedAt(}export function SidebarProviderUpdatePill() {- const navigate = useNavigate();const providers = useAtomValue(primaryServerProvidersAtom);const [dismissedKeys, setDismissedKeys] = useState<ReadonlySet<string>>(() => new Set());const [renderedView, setRenderedView] = useState<ProviderUpdateSidebarPillView | null>(null);@@ -63,8 +62,8 @@ export function SidebarProviderUpdatePill() {}, [effectiveVisibleAfterIso, visibleAfterIso]);const openProviderSettings = useCallback(() => {- void navigate({ to: "/settings/providers" });- }, [navigate]);+ openSettings("providers");+ }, []);const displayedView = renderedView ?? view;const dismissAfterVisibleMs = displayedView?.dismissAfterVisibleMs;const viewKey = displayedView?.key ?? null;diff --git a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx b/apps/web/src/components/sidebar/SidebarUpdatePill.tsxindex f576fdd4e..3db27758c 100644--- a/apps/web/src/components/sidebar/SidebarUpdatePill.tsx+++ b/apps/web/src/components/sidebar/SidebarUpdatePill.tsx@@ -193,7 +193,7 @@ function SidebarUpdateControl() {.downloadUpdate().then((result) => {if (result.completed) {- showDesktopUpdateDownloadedToast(bridge, result.state);+ showDesktopUpdateDownloadedToast();}if (!shouldToastDesktopUpdateActionResult(result)) return;const actionError = getDesktopUpdateActionError(result);diff --git a/apps/web/src/components/ui/dialog-styles.ts b/apps/web/src/components/ui/dialog-styles.tsindex 15e9e8880..ec619c1f7 100644--- a/apps/web/src/components/ui/dialog-styles.ts+++ b/apps/web/src/components/ui/dialog-styles.ts@@ -2,9 +2,9 @@ const DIALOG_BACKDROP_CLASS ="dialog-backdrop fixed inset-0 z-50 transition-all duration-200 data-ending-style:opacity-0 data-starting-style:opacity-0";const DIALOG_POPUP_CLASS =- "dialog-glass -translate-y-[calc(1.25rem*var(--nested-dialogs))] relative flex min-h-0 w-full min-w-0 scale-[calc(1-0.1*var(--nested-dialogs))] flex-col rounded-2xl border opacity-[calc(1-0.1*var(--nested-dialogs))] outline-none transition-[scale,opacity,translate] duration-200 ease-in-out will-change-transform data-nested:data-ending-style:translate-y-8 data-nested:data-starting-style:translate-y-8 data-nested-dialog-open:origin-top data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0";+ "dialog-glass -translate-y-[calc(1.25rem*var(--nested-dialogs))] relative flex min-h-0 w-full min-w-0 scale-[calc(1-0.1*var(--nested-dialogs))] flex-col rounded-2xl border outline-none transition-[scale,opacity,translate] duration-200 ease-in-out will-change-transform data-nested:data-ending-style:translate-y-8 data-nested:data-starting-style:translate-y-8 data-nested-dialog-open:origin-top data-ending-style:scale-98 data-starting-style:scale-98 data-ending-style:opacity-0 data-starting-style:opacity-0";const DIALOG_MOBILE_SHEET_CLASS =- "max-sm:max-w-none max-sm:rounded-none max-sm:border-x-0 max-sm:border-t max-sm:border-b-0 max-sm:opacity-[calc(1-min(var(--nested-dialogs),1))] max-sm:data-ending-style:translate-y-4 max-sm:data-starting-style:translate-y-4";+ "max-sm:max-w-none max-sm:rounded-none max-sm:border-x-0 max-sm:border-t max-sm:border-b-0 max-sm:data-ending-style:translate-y-4 max-sm:data-starting-style:translate-y-4";export { DIALOG_BACKDROP_CLASS, DIALOG_MOBILE_SHEET_CLASS, DIALOG_POPUP_CLASS };diff --git a/apps/web/src/components/ui/sidebar.test.tsx b/apps/web/src/components/ui/sidebar.test.tsxindex e2d29d607..5bb0a9ba0 100644--- a/apps/web/src/components/ui/sidebar.test.tsx+++ b/apps/web/src/components/ui/sidebar.test.tsx@@ -2,6 +2,7 @@ import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vite-plus/test";import {+ Sidebar,SidebarMenuAction,SidebarMenuButton,SidebarMenuSubButton,@@ -48,6 +49,22 @@ describe("sidebar interactive cursors", () => {expect(html).toContain("[-webkit-app-region:no-drag]");expect(html).toContain("size-[var(--workspace-titlebar-control-size)]!");+ expect(html).toContain('stroke-width="1.55"');+ expect(html).toContain("size-[19px]");+ });++ it("uses the roster spring curve and respects reduced motion", () => {+ const html = renderToStaticMarkup(+ <SidebarProvider defaultOpen={false}>+ <Sidebar collapsible="icon">+ <div />+ </Sidebar>+ </SidebarProvider>,+ );++ expect(html).toContain("duration-[320ms]");+ expect(html).toContain("ease-[cubic-bezier(0.22,1.18,0.36,1)]");+ expect(html).toContain("motion-reduce:transition-none");});it("uses shared geometry and icon constraints for menu buttons by default", () => {diff --git a/apps/web/src/components/ui/sidebar.tsx b/apps/web/src/components/ui/sidebar.tsxindex ce6e4cc78..cae959c49 100644--- a/apps/web/src/components/ui/sidebar.tsx+++ b/apps/web/src/components/ui/sidebar.tsx@@ -281,7 +281,7 @@ function Sidebar({{/* This is what handles the sidebar gap on desktop */}<divclassName={cn(- "relative w-(--sidebar-width) bg-transparent transition-[width] duration-200 ease-linear",+ "relative w-(--sidebar-width) bg-transparent transition-[width] duration-[320ms] ease-[cubic-bezier(0.22,1.18,0.36,1)] motion-reduce:transition-none","group-data-[collapsible=offcanvas]:w-0","group-data-[side=right]:rotate-180",variant === "floating" || variant === "inset"@@ -292,7 +292,7 @@ function Sidebar({/><divclassName={cn(- "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-200 ease-linear md:flex",+ "fixed inset-y-0 z-10 hidden h-svh w-(--sidebar-width) transition-[left,right,width] duration-[320ms] ease-[cubic-bezier(0.22,1.18,0.36,1)] motion-reduce:transition-none md:flex",side === "left"? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]": "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",@@ -339,7 +339,22 @@ function SidebarTrigger({ className, onClick, ...props }: React.ComponentProps<tvariant="ghost"{...props}>- {isOpen ? <PanelLeftCloseIcon /> : <PanelLeftIcon />}+ <span className="relative size-[19px]" aria-hidden>+ <PanelLeftCloseIcon+ className={cn(+ "absolute inset-0 size-[19px] transition-[opacity,transform] duration-150 ease-out motion-reduce:transition-none",+ isOpen ? "scale-100 opacity-100" : "-rotate-12 scale-75 opacity-0",+ )}+ strokeWidth={1.55}+ />+ <PanelLeftIcon+ className={cn(+ "absolute inset-0 size-[19px] transition-[opacity,transform] duration-150 ease-out motion-reduce:transition-none",+ isOpen ? "rotate-12 scale-75 opacity-0" : "scale-100 opacity-100",+ )}+ strokeWidth={1.55}+ />+ </span><span className="sr-only">Toggle Sidebar</span></Button>);diff --git a/apps/web/src/components/ui/toast.tsx b/apps/web/src/components/ui/toast.tsxindex 69fd0ebf3..b00d3e69e 100644--- a/apps/web/src/components/ui/toast.tsx+++ b/apps/web/src/components/ui/toast.tsx@@ -103,7 +103,7 @@ function errorDescriptionClampClass(type: unknown, description: unknown): string/** Dismiss-only: circular control overlapping the card corner (iOS notification–style). */const toastCornerDismissClass = "absolute z-20 -top-1.5 -right-1.5";const toastCornerOrbClass = cn(- "inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full border border-border/60 bg-popover/92 text-muted-foreground shadow-sm outline-none backdrop-blur-sm",+ "inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-full border border-border/60 bg-popover text-muted-foreground shadow-sm outline-none","transition-[color,background-color,box-shadow] hover:bg-popover hover:text-foreground","focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background",);diff --git a/apps/web/src/components/usage/UsageCharts.tsx b/apps/web/src/components/usage/UsageCharts.tsxnew file mode 100644index 000000000..b4680978c--- /dev/null+++ b/apps/web/src/components/usage/UsageCharts.tsx@@ -0,0 +1,186 @@+import type {+ SubscriptionProviderId,+ UsagePlanWindow,+ UsageProviderKind,+ UsageProviderPlanLimits,+} from "@t3tools/contracts";+import { enumerateDays, formatDayShort, formatTokens } from "@t3tools/shared/usageFormat";+import type { DailyTotals } from "@t3tools/shared/usageMerge";++import { Line } from "../dither-kit/area";+import { LineChart } from "../dither-kit/area-chart";+import { Bar } from "../dither-kit/bar";+import { BarChart } from "../dither-kit/bar-chart";+import { BlockLegend } from "../dither-kit/block-legend";+import type { ChartConfig } from "../dither-kit/chart-context";+import type { DitherColor } from "../dither-kit/palette";+import { Grid } from "../dither-kit/grid";+import { Tooltip } from "../dither-kit/tooltip";+import { XAxis } from "../dither-kit/x-axis";+import { YAxis } from "../dither-kit/y-axis";+import { ClaudeAI, CursorIcon, type Icon } from "../Icons";+import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";++export const PLAN_PROVIDER_PRESENTATION: Record<+ SubscriptionProviderId,+ {+ readonly label: string;+ readonly icon: Icon | string;+ readonly color: DitherColor;+ }+> = {+ "openai-codex": { label: "ChatGPT", icon: "/provider-icons/openai.svg", color: "green" },+ anthropic: { label: "Claude", icon: ClaudeAI, color: "orange" },+ cursor: { label: "Cursor", icon: CursorIcon, color: "blue" },+ xai: { label: "Grok", icon: "/provider-icons/xai.svg", color: "grey" },+ "kimi-for-coding": {+ label: "Kimi For Coding",+ icon: "/provider-icons/kimi-for-coding.svg",+ color: "purple",+ },+};++export const PLAN_PROVIDER_ORDER: readonly SubscriptionProviderId[] = [+ "openai-codex",+ "anthropic",+ "cursor",+ "xai",+ "kimi-for-coding",+];++function formatReset(resetsAt: string | null): string {+ if (resetsAt === null) return "Reset time unknown";+ const deltaMs = Date.parse(resetsAt) - Date.now();+ if (Number.isNaN(deltaMs) || deltaMs <= 0) return "Resets soon";+ const hours = Math.round(deltaMs / (60 * 60 * 1000));+ if (hours < 48) return `Resets in ${hours}h`;+ return `Resets in ${Math.round(hours / 24)}d`;+}++function remainingPercent(window: UsagePlanWindow): number {+ return Math.min(100, Math.max(0, 100 - window.usedPercent));+}++function ProviderMark({ icon }: { readonly icon: Icon | string }) {+ if (typeof icon !== "string") {+ const Mark = icon;+ return <Mark className="size-4 shrink-0" />;+ }+ return <img src={icon} alt="" className="size-4 shrink-0 brightness-0 dark:invert" />;+}++export function UsagePlanMeters(props: { readonly limits: UsageProviderPlanLimits }) {+ const presentation = PLAN_PROVIDER_PRESENTATION[props.limits.provider];+ const title =+ props.limits.plan === null+ ? presentation.label+ : `${presentation.label} · ${props.limits.plan}`;+ const data = props.limits.windows.map((window) => ({+ label: window.label,+ left: remainingPercent(window),+ }));++ return (+ <section className="flex min-w-0 flex-col gap-3">+ <h2 className="flex items-center gap-2 text-sm font-medium text-foreground">+ <ProviderMark icon={presentation.icon} />+ {title}+ </h2>+ {props.limits.windows.length === 0 ? (+ <p className="text-sm text-muted-foreground">+ {props.limits.message ?? "No limit data yet."}+ </p>+ ) : (+ <>+ <BarChart+ data={data}+ config={{ left: { label: "Left", color: presentation.color } }}+ animate={false}+ bloom="off"+ className="h-48 w-full"+ margins={{ top: 8, right: 8, bottom: 22, left: 36 }}+ >+ <Grid vertical={false} />+ <XAxis dataKey="label" />+ <YAxis tickFormatter={(value) => `${Math.round(value)}%`} tickCount={5} />+ <Tooltip valueFormatter={(value) => `${Math.round(value)}% left`} />+ <Bar dataKey="left" variant="gradient" />+ </BarChart>+ <ul className="flex flex-col gap-1 text-sm text-muted-foreground">+ {props.limits.windows.map((window) => (+ <li+ key={`${window.kind}:${window.label}`}+ className="flex items-baseline justify-between gap-3"+ >+ <span className="text-foreground">+ {window.label} {Math.round(remainingPercent(window))}% left+ </span>+ <span className="tabular-nums">{formatReset(window.resetsAt)}</span>+ </li>+ ))}+ </ul>+ </>+ )}+ </section>+ );+}++const ACTIVITY_COLOR: Record<UsageProviderKind, DitherColor> = {+ claude: "orange",+ codex: "green",+};++export function UsageActivityChart(props: {+ readonly sinceDay: string;+ readonly untilDay: string;+ readonly daily: readonly DailyTotals[];+ readonly providers: readonly {+ readonly provider: UsageProviderKind;+ readonly costUsd: number;+ readonly totalTokens: number;+ }[];+}) {+ const active = providersWithUsage(props.providers);+ const days = enumerateDays(props.sinceDay, props.untilDay);+ const byDay = new Map(props.daily.map((entry) => [entry.day, entry]));+ const data = days.map((day) => {+ const totals = byDay.get(day);+ const row: Record<string, string | number> = { label: formatDayShort(day) };+ for (const provider of PROVIDER_ORDER) {+ row[provider] = totals?.byProvider.get(provider)?.totalTokens ?? 0;+ }+ return row;+ });+ const config = Object.fromEntries(+ active.map((provider) => [+ provider,+ { label: PROVIDER_PRESENTATION[provider].label, color: ACTIVITY_COLOR[provider] },+ ]),+ ) as ChartConfig;++ if (active.length === 0 || days.length === 0) {+ return <p className="text-sm text-muted-foreground">No activity in this window.</p>;+ }++ return (+ <div className="flex min-w-0 flex-col gap-3">+ <LineChart+ data={data}+ config={config}+ animate={false}+ bloom="off"+ className="h-52 w-full"+ margins={{ top: 8, right: 8, bottom: 22, left: 44 }}+ >+ <Grid vertical={false} />+ <XAxis dataKey="label" maxTicks={6} />+ <YAxis tickFormatter={formatTokens} tickCount={4} />+ <Tooltip valueFormatter={(value) => formatTokens(value)} />+ {active.map((provider) => (+ <Line key={provider} dataKey={provider} />+ ))}+ </LineChart>+ <BlockLegend config={config} align="start" />+ </div>+ );+}diff --git a/apps/web/src/components/usage/UsageDialog.tsx b/apps/web/src/components/usage/UsageDialog.tsxnew file mode 100644index 000000000..1a26b52e1--- /dev/null+++ b/apps/web/src/components/usage/UsageDialog.tsx@@ -0,0 +1,40 @@+import { useEffect } from "react";++import { Dialog, DialogPopup } from "~/components/ui/dialog";+import { useClientSettings } from "~/hooks/useSettings";+import { useUsage } from "~/state/usage";+import { closeUsage, useUsageDialogStore } from "~/usageDialogStore";++import { UsagePage } from "./UsagePage";++export function UsageDialog() {+ const open = useUsageDialogStore((state) => state.open);+ const { refresh } = useUsage();+ const refreshMinutes = useClientSettings((settings) => settings.usageRefreshMinutes);++ useEffect(() => {+ if (!open) return;+ const intervalMs = Math.max(1, refreshMinutes) * 60 * 1000;+ const timer = globalThis.setInterval(() => {+ refresh();+ }, intervalMs);+ return () => globalThis.clearInterval(timer);+ }, [open, refresh, refreshMinutes]);++ return (+ <Dialog+ open={open}+ onOpenChange={(nextOpen) => {+ if (!nextOpen) closeUsage();+ }}+ >+ <DialogPopup+ showCloseButton={false}+ bottomStickOnMobile={false}+ className="h-[min(48rem,90dvh)] max-w-5xl flex-col overflow-hidden"+ >+ {open ? <UsagePage /> : null}+ </DialogPopup>+ </Dialog>+ );+}diff --git a/apps/web/src/components/usage/UsagePage.test.tsx b/apps/web/src/components/usage/UsagePage.test.tsxindex 8e86b521e..6abdba28a 100644--- a/apps/web/src/components/usage/UsagePage.test.tsx+++ b/apps/web/src/components/usage/UsagePage.test.tsx@@ -1,182 +1,185 @@import { USAGE_CONTRACT_VERSION } from "@t3tools/contracts";import { mergeUsage } from "@t3tools/shared/usageMerge";+import type { ReactNode } from "react";import { renderToStaticMarkup } from "react-dom/server";import { beforeEach, describe, expect, it, vi } from "vite-plus/test";const testState = vi.hoisted(() => ({useUsage: vi.fn(),- metric: "cost" as "cost" | "tokens",- breakdown: "time" as "model" | "time",}));-vi.mock("react", async (importOriginal) => {- const actual = await importOriginal<typeof import("react")>();- return {- ...actual,- useState: vi.fn((initial: unknown) => [- typeof initial === "function"- ? {- days: 1,- window: {- sinceDay: "2026-08-10",- untilDay: "2026-08-11",- timeZone: "UTC",- resolution: "hour",- sinceTime: "2026-08-10T12:37:00.000Z",- untilTime: "2026-08-11T12:37:00.000Z",- },- }- : initial === "cost"- ? testState.metric- : initial === "model"- ? testState.breakdown- : initial,- vi.fn(),- ]),- };-});--vi.mock("../../env", () => ({ isElectron: false }));vi.mock("../../state/usage", () => ({ useUsage: testState.useUsage }));vi.mock("../ui/button", () => ({ Button: "button" }));-vi.mock("../ui/scroll-area", () => ({ ScrollArea: "div" }));-vi.mock("../ui/select", () => ({- Select: "div",- SelectItem: "div",- SelectPopup: "div",- SelectTrigger: "div",- SelectValue: "div",-}));-vi.mock("../ui/sidebar", () => ({ SidebarInset: "div" }));-vi.mock("../ui/toggle-group", () => ({ Toggle: "button", ToggleGroup: "div" }));-vi.mock("../WorkspaceBreadcrumb", () => ({- WorkspaceBreadcrumb: "div",- WorkspaceBreadcrumbItem: "div",- WorkspaceBreadcrumbSeparator: "span",+vi.mock("../ui/dialog", () => ({+ DialogHeader: "header",+ DialogPanel: "div",+ DialogTitle: "h1",+ DialogClose: (props: { children?: ReactNode }) => <button type="button">{props.children}</button>,}));-vi.mock("../WorkspacePageContainer", () => ({ WorkspacePageContainer: "main" }));-vi.mock("../WorkspacePageHeader", () => ({ WorkspacePageHeader: "header" }));-vi.mock("./UsageProviderChart", () => ({ UsageProviderChart: "div" }));-vi.mock("./usageProviders", async (importOriginal) => {- const actual = await importOriginal<typeof import("./usageProviders")>();+vi.mock("./UsageCharts", async (importOriginal) => {+ const actual = await importOriginal<typeof import("./UsageCharts")>();return {...actual,- PROVIDER_PRESENTATION: {- codex: { color: "white", label: "Codex", mark: "span" },- claude: { color: "orange", label: "Claude Code", mark: "span" },- },+ UsagePlanMeters: (props: {+ limits: { provider: string; windows: { label: string; usedPercent: number }[] };+ }) => (+ <div>+ {props.limits.provider}{" "}+ {props.limits.windows+ .map((window) => `${window.label} ${Math.round(100 - window.usedPercent)}% left`)+ .join(" ")}+ </div>+ ),+ UsageActivityChart: () => <div>activity-chart</div>,};});import { UsagePage } from "./UsagePage";-const providerTotals = (codex: number, claude: number) =>- new Map([- ["codex", { costUsd: codex, totalTokens: codex * 1_000 }],- ["claude", { costUsd: claude, totalTokens: claude * 1_000 }],- ] as const);--const modelTotals = Object.freeze([- {- model: "expensive-model",- provider: "claude" as const,- costUsd: 10,- totalTokens: 100,- records: 1,- costShare: 10 / 16,- },+const connectedPlanLimits = [{- model: "token-heavy-model",- provider: "codex" as const,- costUsd: 5,- totalTokens: 1_000,- records: 1,- costShare: 5 / 16,+ provider: "openai-codex" as const,+ status: "ok" as const,+ plan: "Pro",+ message: null,+ windows: [+ { kind: "weekly" as const, label: "Weekly", usedPercent: 45, resetsAt: null },+ { kind: "session" as const, label: "Spark 5-hour", usedPercent: 0, resetsAt: null },+ ],},{- model: "token-heavy-cheaper-model",- provider: "codex" as const,- costUsd: 1,- totalTokens: 1_000,- records: 1,- costShare: 1 / 16,+ provider: "anthropic" as const,+ status: "failed" as const,+ plan: null,+ message: "Run claude and sign in.",+ windows: [],},-]);+];beforeEach(() => {- testState.metric = "cost";- testState.breakdown = "time";testState.useUsage.mockReturnValue({merged: {...mergeUsage([], USAGE_CONTRACT_VERSION),- models: modelTotals,- hourly: [- {- day: "2026-08-10",- hourStart: "2026-08-10T13:37:00.000Z",- costUsd: 13,- totalTokens: 13_000,- byProvider: providerTotals(7, 6),- },- {- day: "2026-08-11",- hourStart: "2026-08-11T11:37:00.000Z",- costUsd: 11,- totalTokens: 11_000,- byProvider: providerTotals(6, 5),- },- ],+ planLimits: connectedPlanLimits,},- environments: [],+ environments: [+ {+ environmentId: "env-1",+ label: "This Mac",+ isPending: false,+ error: null,+ summary: { contractVersion: USAGE_CONTRACT_VERSION },+ },+ ],isPending: false,isPartial: false,refresh: vi.fn(),});});-describe("UsagePage hourly breakdown", () => {- it("keeps recent activity visible first without empty hourly rows", () => {+describe("UsagePage", () => {+ it("shows remaining plan for connected providers only", () => {const markup = renderToStaticMarkup(<UsagePage />);- const body = markup.match(/<tbody>(.*?)<\/tbody>/)?.[1] ?? "";- expect(body.match(/<tr/g)).toHaveLength(2);- expect(body).toContain("$11.00");- expect(body).toContain("$13.00");- expect(body.indexOf("$11.00")).toBeLessThan(body.indexOf("$13.00"));+ expect(markup).toContain("Weekly 55% left");+ expect(markup).toContain("Spark 5-hour 100% left");+ expect(markup).toContain("openai-codex");+ expect(markup).not.toContain("Run claude and sign in");+ expect(markup).not.toContain("anthropic");});- it("keeps chronological ordering when the token metric is selected", () => {- testState.metric = "tokens";+ it("stays quiet while the first scan is still in flight", () => {+ testState.useUsage.mockReturnValue({+ merged: mergeUsage([], USAGE_CONTRACT_VERSION),+ environments: [+ {+ environmentId: "env-1",+ label: "This Mac",+ isPending: true,+ error: null,+ summary: null,+ },+ ],+ isPending: true,+ isPartial: false,+ refresh: vi.fn(),+ });const markup = renderToStaticMarkup(<UsagePage />);- const body = markup.match(/<tbody>(.*?)<\/tbody>/)?.[1] ?? "";- expect(body).toMatch(/\$11\.00.*\$13\.00/);+ expect(markup).not.toContain("Reading plan limits");+ expect(markup).not.toContain("Weekly 55% left");+ expect(markup).not.toContain("Connect a subscription");+ expect(markup).not.toContain("Connect an environment");+ expect(markup).toContain("Activity");+ expect(markup).not.toContain("animate-spin");});-});-describe("UsagePage model breakdown", () => {- it("sorts models by cost when the cost metric is selected", () => {- testState.breakdown = "model";+ it("keeps arrived plan limits visible while another environment is still reporting", () => {+ testState.useUsage.mockReturnValue({+ merged: {+ ...mergeUsage([], USAGE_CONTRACT_VERSION),+ planLimits: connectedPlanLimits,+ },+ environments: [+ {+ environmentId: "env-1",+ label: "This Mac",+ isPending: false,+ error: null,+ summary: { contractVersion: USAGE_CONTRACT_VERSION },+ },+ {+ environmentId: "env-2",+ label: "Office",+ isPending: true,+ error: null,+ summary: null,+ },+ ],+ isPending: false,+ isPartial: true,+ refresh: vi.fn(),+ });const markup = renderToStaticMarkup(<UsagePage />);- const body = markup.match(/<tbody>(.*?)<\/tbody>/)?.[1] ?? "";- expect(body).toMatch(/expensive-model.*token-heavy-model.*token-heavy-cheaper-model/);+ expect(markup).toContain("Weekly 55% left");+ expect(markup).not.toContain("Reading plan limits");+ expect(markup).toContain("Activity");+ expect(markup).toContain("activity-chart");+ expect(markup).not.toContain("animate-spin");});- it("sorts models by token usage when the token metric is selected", () => {- testState.metric = "tokens";- testState.breakdown = "model";+ it("shows a connected Claude card when windows have not arrived yet", () => {+ testState.useUsage.mockReturnValue({+ merged: {+ ...mergeUsage([], USAGE_CONTRACT_VERSION),+ planLimits: [+ {+ provider: "anthropic" as const,+ status: "ok" as const,+ plan: null,+ message: null,+ windows: [],+ },+ ],+ },+ environments: [+ {+ environmentId: "env-1",+ label: "This Mac",+ isPending: false,+ error: null,+ summary: { contractVersion: USAGE_CONTRACT_VERSION },+ },+ ],+ isPending: false,+ isPartial: false,+ refresh: vi.fn(),+ });const markup = renderToStaticMarkup(<UsagePage />);- const body = markup.match(/<tbody>(.*?)<\/tbody>/)?.[1] ?? "";-- expect(body).toMatch(/token-heavy-model.*token-heavy-cheaper-model.*expensive-model/);- expect(modelTotals.map((model) => model.model)).toEqual([- "expensive-model",- "token-heavy-model",- "token-heavy-cheaper-model",- ]);+ expect(markup).toContain("anthropic");});});diff --git a/apps/web/src/components/usage/UsagePage.tsx b/apps/web/src/components/usage/UsagePage.tsxindex 7474bb9d6..125a546b6 100644--- a/apps/web/src/components/usage/UsagePage.tsx+++ b/apps/web/src/components/usage/UsagePage.tsx@@ -1,481 +1,108 @@-import type { UsageProviderKind } from "@t3tools/contracts";import { CheckIcon, RefreshCwIcon, XIcon } from "lucide-react";-import { useMemo, useState } from "react";+import { useState } from "react";-import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";+import { formatTokens, formatUsd, makeWindow } from "@t3tools/shared/usageFormat";-import { isElectron } from "../../env";-import { cn } from "../../lib/utils";import { useUsage, type EnvironmentUsageStatus } from "../../state/usage";-import {- enumerateDays,- enumerateHourStarts,- formatCount,- formatDateTimeShort,- formatDayShort,- formatHourShort,- formatPercent,- formatTokens,- formatUsd,- makeWindow,-} from "@t3tools/shared/usageFormat";import { Button } from "../ui/button";-import { ScrollArea } from "../ui/scroll-area";-import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";-import { SidebarInset } from "../ui/sidebar";-import { Toggle, ToggleGroup } from "../ui/toggle-group";-import {- WorkspaceBreadcrumb,- WorkspaceBreadcrumbItem,- WorkspaceBreadcrumbSeparator,-} from "../WorkspaceBreadcrumb";-import { WorkspacePageContainer } from "../WorkspacePageContainer";-import { WorkspacePageHeader } from "../WorkspacePageHeader";-import { UsageProviderChart, type UsageChartMetric } from "./UsageProviderChart";-import { PROVIDER_ORDER, PROVIDER_PRESENTATION, providersWithUsage } from "./usageProviders";--const WINDOW_OPTIONS = [- { days: 1, label: "Past 24h" },- { days: 7, label: "7 days" },- { days: 30, label: "30 days" },- { days: 90, label: "90 days" },-] as const;+import { DialogClose, DialogHeader, DialogPanel, DialogTitle } from "../ui/dialog";+import { PLAN_PROVIDER_ORDER, UsageActivityChart, UsagePlanMeters } from "./UsageCharts";+import { PROVIDER_PRESENTATION } from "./usageProviders";export function UsagePage() {- const [windowSelection, setWindowSelection] = useState(() => ({- days: 30,- window: makeWindow(30),- }));- const [metric, setMetric] = useState<UsageChartMetric>("cost");- const [breakdown, setBreakdown] = useState<"model" | "time">("model");- const { days: windowDays, window } = windowSelection;- const isPast24Hours = windowDays === 1;- const { merged, environments, isPending, isPartial, refresh } = useUsage(window);-- // Hold the content until every environment is terminal. Rendering merged- // totals while devices are still answering makes every number on the page- // jump as each one lands.- const settling = isPending || isPartial;-- const days = useMemo(- () => enumerateDays(window.sinceDay, window.untilDay),- [window.sinceDay, window.untilDay],- );- const hours = useMemo(- () =>- window.sinceTime === undefined || window.untilTime === undefined- ? []- : enumerateHourStarts(window.sinceTime, window.untilTime),- [window.sinceTime, window.untilTime],- );- // Newest first: the window can run 90 periods, so the interesting end- // belongs at the top of the table.- const breakdownPeriods = useMemo<readonly (DailyTotals | HourlyTotals)[]>(- () => (isPast24Hours ? merged.hourly : merged.daily).toReversed(),- [isPast24Hours, merged.daily, merged.hourly],- );- const breakdownModels = useMemo(- () =>- breakdown === "model" && metric === "tokens"- ? merged.models.toSorted(- (left, right) => right.totalTokens - left.totalTokens || right.costUsd - left.costUsd,- )- : merged.models,- [breakdown, merged.models, metric],- );- const activeProviders = useMemo(() => providersWithUsage(merged.providers), [merged.providers]);- const timeValueColumnWidth = `${60 / (activeProviders.length + 2)}%`;+ const [window] = useState(() => makeWindow(30));+ const { merged, environments, isPending, refresh } = useUsage(window);+ const planLimits = PLAN_PROVIDER_ORDER.map((provider) =>+ merged.planLimits.find((entry) => entry.provider === provider && entry.status === "ok"),+ ).filter((entry) => entry !== undefined);- const selectWindow = (days: number) => {- setWindowSelection({- days,- window: makeWindow(days, undefined, days === 1 ? "hour" : "day"),- });- };- const refreshWindow = () => {- const nextWindow = makeWindow(windowDays, undefined, isPast24Hours ? "hour" : "day");- if (- nextWindow.sinceDay === window.sinceDay &&- nextWindow.untilDay === window.untilDay &&- nextWindow.sinceTime === window.sinceTime &&- nextWindow.untilTime === window.untilTime- ) {- refresh();- } else {- setWindowSelection({ days: windowDays, window: nextWindow });- }- };- const windowLabel =- isPast24Hours && window.sinceTime !== undefined && window.untilTime !== undefined- ? `${formatDateTimeShort(window.sinceTime, window.timeZone)} to ${formatDateTimeShort(window.untilTime, window.timeZone)}`- : `${formatDayShort(window.sinceDay)} to ${formatDayShort(window.untilDay)}`;- const topbarContent = (- <div className="flex w-full min-w-0 items-center gap-3">- <WorkspaceBreadcrumb ariaLabel="Usage breadcrumb" className="min-w-0">- <WorkspaceBreadcrumbItem current>- <h1>Usage</h1>- </WorkspaceBreadcrumbItem>- <WorkspaceBreadcrumbSeparator className="hidden md:flex" />- <WorkspaceBreadcrumbItem className="hidden min-w-0 shrink md:flex">- <span className="truncate">{windowLabel}</span>- </WorkspaceBreadcrumbItem>- </WorkspaceBreadcrumb>- <div className="ms-auto hidden min-w-0 items-center justify-end gap-2 lg:flex">- <ToggleGroup- aria-label="Usage metric"- variant="segmented"- value={[metric]}- onValueChange={(next) => {- const value = next[0];- if (value === "cost" || value === "tokens") setMetric(value);- }}- >- {(["cost", "tokens"] as const).map((option) => (- <Toggle key={option} value={option}>- {option === "cost" ? "Cost" : "Tokens"}- </Toggle>- ))}- </ToggleGroup>- <ToggleGroup- aria-label="Usage period"- variant="segmented"- value={[String(windowDays)]}- onValueChange={(next) => {- const value = next[0];- if (value) selectWindow(Number(value));- }}- >- {WINDOW_OPTIONS.map((option) => (- <Toggle key={option.days} value={String(option.days)}>- {option.label}- </Toggle>- ))}- </ToggleGroup>- <Button onClick={refreshWindow} aria-label="Refresh usage" size="icon-sm" variant="ghost">- <RefreshCwIcon className="size-3.5" />- </Button>- </div>- <div className="ms-auto flex min-w-0 items-center justify-end gap-1 lg:hidden">- <Select- value={metric}- onValueChange={(value) => {- if (value === "cost" || value === "tokens") setMetric(value);- }}- >- <SelectTrigger- aria-label="Usage metric"- size="compact"- variant="ghost"- className="w-auto min-w-0"- >- <SelectValue>{metric === "cost" ? "Cost" : "Tokens"}</SelectValue>- </SelectTrigger>- <SelectPopup align="end" alignItemWithTrigger={false}>- <SelectItem value="cost">Cost</SelectItem>- <SelectItem value="tokens">Tokens</SelectItem>- </SelectPopup>- </Select>- <Select value={String(windowDays)} onValueChange={(value) => selectWindow(Number(value))}>- <SelectTrigger- aria-label="Usage period"- size="compact"+ return (+ <>+ <DialogHeader className="flex flex-row items-center justify-between gap-3 border-b px-5 py-3">+ <DialogTitle>Usage</DialogTitle>+ <div className="flex items-center gap-1">+ <Button+ onClick={() => refresh()}+ aria-label="Refresh usage"+ size="icon"variant="ghost"- className="w-auto min-w-0"+ disabled={isPending}>- <SelectValue>- {WINDOW_OPTIONS.find((option) => option.days === windowDays)?.label}- </SelectValue>- </SelectTrigger>- <SelectPopup align="end" alignItemWithTrigger={false}>- {WINDOW_OPTIONS.map((option) => (- <SelectItem key={option.days} value={String(option.days)}>- {option.label}- </SelectItem>+ <RefreshCwIcon />+ </Button>+ <DialogClose aria-label="Close" render={<Button size="icon" variant="ghost" />}>+ <XIcon />+ </DialogClose>+ </div>+ </DialogHeader>++ <DialogPanel className="space-y-6 p-5">+ {environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}+ <UsageCoverageNotice+ environments={environments}+ duplicateSources={merged.duplicateSources}+ staleEnvironments={merged.staleEnvironments}+ />+ {planLimits.length > 0 ? (+ <div className="grid gap-10 lg:grid-cols-2">+ {planLimits.map((limits) => (+ <UsagePlanMeters key={limits.provider} limits={limits} />))}- </SelectPopup>- </Select>- <Button onClick={refreshWindow} aria-label="Refresh usage" size="icon-sm" variant="ghost">- <RefreshCwIcon className="size-3.5" />- </Button>- </div>- </div>- );-- return (- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">- <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">- <WorkspacePageHeader electron={isElectron}>{topbarContent}</WorkspacePageHeader>-- <ScrollArea className="min-h-0 flex-1">- <WorkspacePageContainer width="wide">- {settling ? (- <>- {environments.length > 1 ? <UsageDeviceStrip environments={environments} /> : null}- <UsageSkeleton />- </>- ) : (- <>- <UsageCoverageNotice- environments={environments}- duplicateSources={merged.duplicateSources}- staleEnvironments={merged.staleEnvironments}+ </div>+ ) : isPending ? null : environments.length === 0 ? (+ <p className="text-sm text-muted-foreground">Connect an environment to see usage.</p>+ ) : (+ <p className="text-sm text-muted-foreground">+ Connect a subscription in Settings to see plan limits.+ </p>+ )}++ <section className="flex flex-col gap-4 border-t border-border pt-6">+ <h2 className="text-sm font-medium text-foreground">Activity</h2>+ {isPending && merged.totalTokens === 0 ? (+ <p className="text-sm text-muted-foreground">Reading transcripts…</p>+ ) : (+ <>+ <UsageActivityChart+ sinceDay={window.sinceDay}+ untilDay={window.untilDay}+ daily={merged.daily}+ providers={merged.providers}+ />+ <div className="grid grid-cols-2 gap-x-6 gap-y-3 md:grid-cols-4">+ <Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />+ <Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />+ <Metric label="Output" value={formatTokens(merged.outputTokens)} />+ <Metric+ label="Cache savings"+ value={formatUsd(merged.costQuality.cacheSavingsUsd)}/>-- <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">- <div className="flex min-w-0 flex-col gap-5">- <div className="flex flex-col gap-1">- <span className="text-4xl font-semibold text-foreground tabular-nums">- {metric === "cost"- ? formatUsd(merged.costUsd)- : formatTokens(merged.totalTokens)}+ </div>+ {merged.models.length > 0 ? (+ <ul className="flex flex-col gap-1.5 text-sm">+ {merged.models.slice(0, 8).map((model) => (+ <li+ key={`${model.provider}:${model.model}`}+ className="flex items-baseline justify-between gap-3"+ >+ <span className="min-w-0 truncate text-foreground">+ {PROVIDER_PRESENTATION[model.provider].label} · {model.model}</span>- <span className="text-xs text-muted-foreground">- {metric === "cost"- ? `${formatCount(merged.sessions)} sessions · API estimate`- : `${formatCount(merged.sessions)} sessions`}+ <span className="shrink-0 text-muted-foreground tabular-nums">+ {formatTokens(model.totalTokens)}</span>- </div>-- {activeProviders.map((provider) => {- const totals = merged.providers.find((entry) => entry.provider === provider);- const share =- metric === "cost" ? (totals?.costShare ?? 0) : (totals?.tokenShare ?? 0);- const providerSessions = totals?.sessions ?? 0;- const sessionLabel = `${formatCount(providerSessions)} ${- providerSessions === 1 ? "session" : "sessions"- }`;- return (- <div key={provider} className="flex flex-col gap-1">- <div className="flex items-baseline justify-between gap-4">- <span className="flex min-w-0 items-center gap-2 text-sm text-foreground">- <span- aria-hidden- className="size-2 shrink-0 rounded-full"- style={{- backgroundColor: PROVIDER_PRESENTATION[provider].color,- }}- />- <ProviderMark provider={provider} className="size-4" />- <span className="flex min-w-0 items-baseline gap-1.5">- <span className="truncate">- {PROVIDER_PRESENTATION[provider].label}- </span>- <span className="shrink-0 whitespace-nowrap text-[11px] text-muted-foreground tabular-nums">- {sessionLabel}- </span>- </span>- </span>- <span className="shrink-0 text-sm font-medium text-foreground tabular-nums">- {metric === "cost"- ? formatUsd(totals?.costUsd ?? 0)- : formatTokens(totals?.totalTokens ?? 0)}- </span>- </div>- <span className="text-xs text-muted-foreground">- {metric === "cost"- ? `${formatPercent(share)} of cost · ${formatTokens(totals?.totalTokens ?? 0)} tokens`- : `${formatPercent(share)} of tokens · ${formatUsd(totals?.costUsd ?? 0)}`}- </span>- </div>- );- })}- </div>-- <div className="flex min-w-0 flex-col gap-3">- <h2 className="text-sm font-medium text-foreground">- {isPast24Hours ? "Hourly" : "Daily"}{" "}- {metric === "tokens" ? "processed tokens" : "cost"}- </h2>- <UsageProviderChart- providers={activeProviders}- days={days}- daily={merged.daily}- hours={hours}- hourly={merged.hourly}- metric={metric}- referenceTime={window.untilTime}- resolution={isPast24Hours ? "hour" : "day"}- timeZone={window.timeZone}- />- </div>- </section>-- <section className="flex flex-col gap-2">- <h2 className="text-sm font-medium text-foreground">Totals</h2>- <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">- <Metric label="Processed tokens" value={formatTokens(merged.totalTokens)} />- <Metric label="Cached input" value={formatTokens(merged.cachedInputTokens)} />- <Metric- label="Uncached input"- value={formatTokens(merged.uncachedInputTokens)}- />- <Metric label="Output" value={formatTokens(merged.outputTokens)} />- <Metric- label="Cache savings"- value={formatUsd(merged.costQuality.cacheSavingsUsd)}- />- </div>- </section>-- <section className="flex flex-col gap-3">- <div className="flex items-center justify-between gap-3">- <h2 className="text-sm font-medium text-foreground">Breakdown</h2>- <ToggleGroup- aria-label="Usage breakdown"- variant="segmented"- value={[breakdown]}- onValueChange={(next) => {- const value = next[0];- if (value === "model" || value === "time") setBreakdown(value);- }}- >- {(- [- { value: "model", label: "Model" },- { value: "time", label: isPast24Hours ? "Hour" : "Day" },- ] as const- ).map((option) => (- <Toggle key={option.value} value={option.value}>- {option.label}- </Toggle>- ))}- </ToggleGroup>- </div>-- {breakdown === "model" ? (- <table className="w-full table-fixed text-sm">- <colgroup>- <col className="w-2/5" />- <col className="w-1/5" />- <col className="w-1/5" />- <col className="w-1/5" />- </colgroup>- <thead>- <tr className="border-b border-border text-left text-xs text-muted-foreground">- <th className="py-2 font-normal">Model</th>- <th className="py-2 text-right font-normal">Cost</th>- <th className="py-2 text-right font-normal">Share</th>- <th className="py-2 text-right font-normal">Tokens</th>- </tr>- </thead>- <tbody>- {breakdownModels.length === 0 ? (- <tr>- <td colSpan={4} className="py-6 text-center text-muted-foreground">- No activity in this window.- </td>- </tr>- ) : (- breakdownModels.map((model) => (- <tr- key={`${model.provider}:${model.model}`}- className="border-b border-border/50 transition-colors hover:bg-muted/50"- >- <td className="py-2 text-foreground">- <span className="flex items-center gap-2">- <ProviderMark provider={model.provider} className="size-3.5" />- {model.model}- </span>- </td>- <td className="py-2 text-right text-foreground tabular-nums">- {formatUsd(model.costUsd)}- </td>- <td className="py-2 text-right text-muted-foreground tabular-nums">- {formatPercent(model.costShare)}- </td>- <td className="py-2 text-right text-muted-foreground tabular-nums">- {formatTokens(model.totalTokens)}- </td>- </tr>- ))- )}- </tbody>- </table>- ) : (- <table className="w-full table-fixed text-sm">- <colgroup>- <col className="w-2/5" />- {activeProviders.map((provider) => (- <col key={provider} style={{ width: timeValueColumnWidth }} />- ))}- <col style={{ width: timeValueColumnWidth }} />- <col style={{ width: timeValueColumnWidth }} />- </colgroup>- <thead>- <tr className="border-b border-border text-left text-xs text-muted-foreground">- <th className="py-2 font-normal">{isPast24Hours ? "Hour" : "Day"}</th>- {activeProviders.map((provider) => (- <th key={provider} className="py-2 text-right font-normal">- {PROVIDER_PRESENTATION[provider].label}- </th>- ))}- <th className="py-2 text-right font-normal">Total</th>- <th className="py-2 text-right font-normal">Tokens</th>- </tr>- </thead>- <tbody>- {breakdownPeriods.length === 0 ? (- <tr>- <td- colSpan={activeProviders.length + 3}- className="py-6 text-center text-muted-foreground"- >- No activity in this window.- </td>- </tr>- ) : (- breakdownPeriods.map((period) => (- <tr- key={"hourStart" in period ? period.hourStart : period.day}- className="border-b border-border/50 transition-colors hover:bg-muted/50"- >- <td className="py-2 text-foreground">- {"hourStart" in period- ? formatHourShort(period.hourStart, window.timeZone)- : formatDayShort(period.day)}- </td>- {activeProviders.map((provider) => (- <td- key={provider}- className="py-2 text-right text-muted-foreground tabular-nums"- >- {formatUsd(period.byProvider.get(provider)?.costUsd ?? 0)}- </td>- ))}- <td className="py-2 text-right text-foreground tabular-nums">- {formatUsd(period.costUsd)}- </td>- <td className="py-2 text-right text-muted-foreground tabular-nums">- {formatTokens(period.totalTokens)}- </td>- </tr>- ))- )}- </tbody>- </table>- )}- </section>- </>- )}- </WorkspacePageContainer>- </ScrollArea>- </div>- </SidebarInset>+ </li>+ ))}+ </ul>+ ) : null}+ </>+ )}+ </section>+ </DialogPanel>+ </>);}-/** Brand mark for the harness a row belongs to. */-function ProviderMark({- provider,- className,-}: {- readonly provider: UsageProviderKind;- readonly className: string;-}) {- const Mark = PROVIDER_PRESENTATION[provider].mark;- return <Mark className={cn("shrink-0", className)} aria-hidden />;-}-function Metric({ label, value }: { readonly label: string; readonly value: string }) {return (<div className="flex min-w-0 flex-col gap-0.5">@@ -485,12 +112,6 @@ function Metric({ label, value }: { readonly label: string; readonly value: stri);}-/**- * Says plainly when the totals are incomplete: an environment that failed, or- * one whose transcripts another environment already reported. Environments- * that are still answering never reach this notice; the page shows the- * loading skeleton until every one is terminal.- */function UsageCoverageNotice({environments,duplicateSources,@@ -528,11 +149,6 @@ function UsageCoverageNotice({);}-/**- * Per-device progress while the page waits for every environment to answer.- * Only rendered with two or more devices; a lone device has nothing to- * enumerate.- */function UsageDeviceStrip({environments,}: {@@ -583,65 +199,3 @@ function UsageDeviceStrip({</div>);}--/**- * Static stand-in with the loaded page's shape. No shimmer; blocks fill in- * exactly once when the last device answers.- */-function UsageSkeleton() {- return (- <>- <section className="grid gap-6 lg:grid-cols-[minmax(0,18rem)_minmax(0,1fr)]">- <div className="flex flex-col gap-5">- <div className="flex flex-col gap-1">- <div className="h-10 w-36 rounded-sm bg-muted" />- <div className="h-4 w-32 rounded-sm bg-muted" />- </div>- {PROVIDER_ORDER.map((provider) => (- <div key={provider} className="flex flex-col gap-1">- <div className="flex min-h-5 items-center justify-between gap-4">- <span className="flex items-center gap-2">- <span className="size-2 shrink-0 rounded-full bg-muted" />- <span className="size-4 shrink-0 rounded-full bg-muted" />- <div className="h-3.5 w-20 rounded-sm bg-muted" />- </span>- <div className="h-3.5 w-14 rounded-sm bg-muted" />- </div>- <div className="h-4 w-36 rounded-sm bg-muted" />- </div>- ))}- </div>-- <div className="flex flex-col gap-3">- <div className="h-5 w-24 rounded-sm bg-muted" />- <div className="flex flex-col gap-1">- <div className="ml-16 h-56 rounded-sm bg-muted/35" />- <div className="ml-16 h-4 rounded-sm bg-muted/35" />- </div>- </div>- </section>-- <section className="flex flex-col gap-2">- <h2 className="text-sm font-medium text-foreground">Totals</h2>- <div className="grid grid-cols-2 gap-x-6 gap-y-4 py-1 md:grid-cols-5">- {["Processed tokens", "Cached input", "Uncached input", "Output", "Cache savings"].map(- (label) => (- <div key={label} className="flex flex-col gap-0.5">- <span className="text-xs text-muted-foreground">{label}</span>- <div className="h-6 w-16 rounded-sm bg-muted" />- </div>- ),- )}- </div>- </section>-- <section className="flex flex-col gap-3">- <div className="flex items-center justify-between gap-3">- <h2 className="text-sm font-medium text-foreground">Breakdown</h2>- <div className="h-7 w-28 rounded-lg bg-input/40" />- </div>- <div className="h-44 rounded-sm bg-muted/35" />- </section>- </>- );-}diff --git a/apps/web/src/components/usage/UsageProviderChart.test.ts b/apps/web/src/components/usage/UsageProviderChart.test.tsdeleted file mode 100644index 09961213b..000000000--- a/apps/web/src/components/usage/UsageProviderChart.test.ts+++ /dev/null@@ -1,134 +0,0 @@-import { describe, expect, it } from "vite-plus/test";--import { buildDayColumns, niceScale } from "./UsageProviderChart";-import { providersWithUsage } from "./usageProviders";--describe("niceScale", () => {- it("never puts the peak above the top of the scale", () => {- // Regression: an earlier version stopped at the last step below the peak,- // so the tallest day was drawn past the plot and clipped.- for (const peak of [1122.71, 999, 1, 0.04, 1_400_000_000, 37.5, 5000, 100.001]) {- const { max } = niceScale(peak, 4);- expect(max, `peak ${peak}`).toBeGreaterThanOrEqual(peak);- }- });-- it("starts at zero and ends at the maximum", () => {- const { max, ticks } = niceScale(1122.71, 4);-- expect(ticks[0]).toBe(0);- expect(ticks[ticks.length - 1]).toBeCloseTo(max, 6);- });-- it("uses evenly spaced 1/2/5 steps", () => {- const { ticks } = niceScale(1122.71, 4);- const steps = ticks.slice(1).map((tick, index) => tick - (ticks[index] ?? 0));-- for (const step of steps) expect(step).toBeCloseTo(steps[0] ?? 0, 6);- const [first = 0] = steps;- const normalized = first / 10 ** Math.floor(Math.log10(first));- expect([1, 2, 5, 10]).toContain(Math.round(normalized));- });-- it("keeps the tick count near the requested resolution", () => {- const { ticks } = niceScale(1122.71, 4);- expect(ticks.length).toBeGreaterThanOrEqual(3);- expect(ticks.length).toBeLessThanOrEqual(7);- });-- it("degrades to a single zero tick with no data", () => {- expect(niceScale(0, 4)).toEqual({ max: 0, ticks: [0] });- });-});--describe("buildDayColumns", () => {- const days = ["2026-08-01", "2026-08-02", "2026-08-03"];- const byDay = new Map([- [- "2026-08-01",- {- day: "2026-08-01",- costUsd: 30,- totalTokens: 300,- byProvider: new Map([- ["codex" as const, { costUsd: 10, totalTokens: 100 }],- ["claude" as const, { costUsd: 20, totalTokens: 200 }],- ]),- },- ],- // 2026-08-02 is deliberately absent: a day with no activity.- [- "2026-08-03",- {- day: "2026-08-03",- costUsd: 5,- totalTokens: 50,- byProvider: new Map([["claude" as const, { costUsd: 5, totalTokens: 50 }]]),- },- ],- ]);-- it("plots each day on its own", () => {- expect(buildDayColumns(days, byDay, "cost").map((column) => column.total)).toEqual([30, 0, 5]);- });-- it("reads the requested metric", () => {- expect(buildDayColumns(days, byDay, "tokens").map((column) => column.total)).toEqual([- 300, 0, 50,- ]);- });-- it("keeps band values absolute rather than cumulative", () => {- // Regression: the bands were once stack offsets, which drew Claude Code- // permanently above Codex regardless of which provider spent more.- const [first] = buildDayColumns(days, byDay, "cost");-- expect(first?.bands).toEqual([- { provider: "codex", value: 10 },- { provider: "claude", value: 20 },- ]);- });-- it("reports the total as the sum of its bands", () => {- for (const column of buildDayColumns(days, byDay, "cost")) {- const sum = column.bands.reduce((running, band) => running + band.value, 0);- expect(column.total).toBeCloseTo(sum, 9);- }- });-});--describe("providersWithUsage", () => {- it("omits providers with no cost or tokens", () => {- expect(- providersWithUsage([- { provider: "codex", costUsd: 0, totalTokens: 0 },- { provider: "claude", costUsd: 0, totalTokens: 200 },- ]),- ).toEqual(["claude"]);- });-});--describe("hourly chart columns", () => {- it("zero-fills inactive hours and preserves hourly provider values", () => {- const byHour = new Map([- [- "2026-08-11T09:37:00.000Z",- {- day: "2026-08-11",- hourStart: "2026-08-11T09:37:00.000Z",- costUsd: 4,- totalTokens: 40,- byProvider: new Map([["codex" as const, { costUsd: 4, totalTokens: 40 }]]),- },- ],- ]);-- expect(- buildDayColumns(- ["2026-08-11T08:37:00.000Z", "2026-08-11T09:37:00.000Z", "2026-08-11T10:37:00.000Z"],- byHour,- "cost",- ).map((column) => column.total),- ).toEqual([0, 4, 0]);- });-});diff --git a/apps/web/src/components/usage/UsageProviderChart.tsx b/apps/web/src/components/usage/UsageProviderChart.tsxdeleted file mode 100644index 26d49e664..000000000--- a/apps/web/src/components/usage/UsageProviderChart.tsx+++ /dev/null@@ -1,470 +0,0 @@-import type { UsageProviderKind } from "@t3tools/contracts";-import { useCallback, useLayoutEffect, useMemo, useRef, useState } from "react";--import type { DailyTotals, HourlyTotals } from "@t3tools/shared/usageMerge";-import {- formatDayShort,- formatHourShort,- formatRelativeHourShort,- formatTokens,- formatUsd,-} from "@t3tools/shared/usageFormat";-import { PROVIDER_ORDER, PROVIDER_PRESENTATION } from "./usageProviders";--const VIEW_WIDTH = 960;-const VIEW_HEIGHT = 260;-const TICK_COUNT = 4;-const PLOT_TOP = 8;--export type UsageChartMetric = "tokens" | "cost";--interface UsageProviderChartProps {- readonly providers: readonly UsageProviderKind[];- readonly days: readonly string[];- readonly daily: readonly DailyTotals[];- readonly hours: readonly string[];- readonly hourly: readonly HourlyTotals[];- readonly metric: UsageChartMetric;- readonly referenceTime: string | undefined;- readonly resolution: "day" | "hour";- readonly timeZone: string;-}--/** One day's per-provider values, shared by the paths and the hover readout. */-export interface DayColumn {- readonly bands: readonly {- readonly provider: UsageProviderKind;- readonly value: number;- }[];- readonly total: number;-}--interface Point {- readonly x: number;- readonly y: number;-}--function valueFor(- totals: DailyTotals | HourlyTotals | undefined,- provider: UsageProviderKind,- metric: UsageChartMetric,-): number {- const entry = totals?.byProvider.get(provider);- if (entry === undefined) return 0;- return metric === "tokens" ? entry.totalTokens : entry.costUsd;-}--function buildPeriodColumns(- periods: readonly string[],- byPeriod: ReadonlyMap<string, DailyTotals | HourlyTotals>,- metric: UsageChartMetric,-): readonly DayColumn[] {- return periods.map((period) => {- const entry = byPeriod.get(period);- const bands = PROVIDER_ORDER.map((provider) => ({- provider,- value: valueFor(entry, provider, metric),- }));- return { bands, total: bands.reduce((sum, band) => sum + band.value, 0) };- });-}--/** Shape-preserving cubic tangents that cannot overshoot spiky usage data. */-function monotoneTangents(points: readonly Point[]): readonly number[] {- const count = points.length;- if (count < 2) return [0];-- const slopes: number[] = [];- for (let index = 0; index < count - 1; index += 1) {- const dx = (points[index + 1]?.x ?? 0) - (points[index]?.x ?? 0);- const dy = (points[index + 1]?.y ?? 0) - (points[index]?.y ?? 0);- slopes.push(dx === 0 ? 0 : dy / dx);- }-- const tangents: number[] = Array.from({ length: count }, () => 0);- tangents[0] = slopes[0] ?? 0;- tangents[count - 1] = slopes[count - 2] ?? 0;- for (let index = 1; index < count - 1; index += 1) {- const previous = slopes[index - 1] ?? 0;- const next = slopes[index] ?? 0;- tangents[index] = previous * next <= 0 ? 0 : (previous + next) / 2;- }-- for (let index = 0; index < count - 1; index += 1) {- const slope = slopes[index] ?? 0;- if (slope === 0) {- tangents[index] = 0;- tangents[index + 1] = 0;- continue;- }- const a = (tangents[index] ?? 0) / slope;- const b = (tangents[index + 1] ?? 0) / slope;- const magnitude = a * a + b * b;- if (magnitude > 9) {- const scale = 3 / Math.sqrt(magnitude);- tangents[index] = scale * a * slope;- tangents[index + 1] = scale * b * slope;- }- }-- return tangents;-}--interface CurveSegment {- readonly from: Point;- readonly c1: Point;- readonly c2: Point;- readonly to: Point;-}--function smoothCurve(points: readonly Point[]): readonly CurveSegment[] {- if (points.length < 2) return [];- const tangents = monotoneTangents(points);- const segments: CurveSegment[] = [];-- for (let index = 0; index < points.length - 1; index += 1) {- const from = points[index];- const to = points[index + 1];- if (from === undefined || to === undefined) continue;- const dx = to.x - from.x;- segments.push({- from,- c1: { x: from.x + dx / 3, y: from.y + ((tangents[index] ?? 0) * dx) / 3 },- c2: { x: to.x - dx / 3, y: to.y - ((tangents[index + 1] ?? 0) * dx) / 3 },- to,- });- }- return segments;-}--function curvePath(segments: readonly CurveSegment[]): string {- const first = segments[0];- if (first === undefined) return "";- let path = `M${first.from.x.toFixed(2)},${first.from.y.toFixed(2)}`;- for (const segment of segments) {- path += ` C${segment.c1.x.toFixed(2)},${segment.c1.y.toFixed(2)} ${segment.c2.x.toFixed(2)},${segment.c2.y.toFixed(2)} ${segment.to.x.toFixed(2)},${segment.to.y.toFixed(2)}`;- }- return path;-}--/**- * Builds a scale whose maximum is a readable 1/2/5 x 10^n step at or above the- * peak.- *- * Rounding the maximum *up* is the point: stopping at the last step below the- * peak leaves the tallest day drawn past the top of the plot, where it is- * clipped.- */-export function niceScale(peak: number, count: number): { max: number; ticks: readonly number[] } {- if (peak <= 0) return { max: 0, ticks: [0] };-- const rawStep = peak / count;- const magnitude = 10 ** Math.floor(Math.log10(rawStep));- const normalized = rawStep / magnitude;- const step = (normalized > 5 ? 10 : normalized > 2 ? 5 : normalized > 1 ? 2 : 1) * magnitude;-- const max = Math.ceil(peak / step) * step;- const ticks: number[] = [];- for (let value = 0; value <= max + step * 1e-6; value += step) ticks.push(value);- return { max, ticks };-}--/**- * Turns the merged daily totals into one column per day.- *- * Values are absolute, not cumulative: each provider is drawn from the same- * zero baseline so the chart never implies that one provider is always larger.- *- * The chart paths and the hover readout both consume this, so the number under- * the cursor is by construction the number that was plotted rather than a- * second derivation that can drift from it.- */-export function buildDayColumns(- days: readonly string[],- byDay: ReadonlyMap<string, DailyTotals>,- metric: UsageChartMetric,-): readonly DayColumn[] {- return buildPeriodColumns(days, byDay, metric);-}--export function UsageProviderChart({- providers,- days,- daily,- hours,- hourly,- metric,- referenceTime,- resolution,- timeZone,-}: UsageProviderChartProps) {- const periods = resolution === "hour" ? hours : days;- const byPeriod = useMemo(- () =>- resolution === "hour"- ? new Map(hourly.map((entry) => [entry.hourStart, entry]))- : new Map(daily.map((entry) => [entry.day, entry])),- [daily, hourly, resolution],- );- const [hoverIndex, setHoverIndex] = useState<number | null>(null);- const plotRef = useRef<HTMLDivElement | null>(null);- const tooltipRef = useRef<HTMLDivElement | null>(null);- const hoverPositionRef = useRef<{ x: number; y: number } | null>(null);-- const { paths, ticks, stepX, toY, series } = useMemo(() => {- if (periods.length === 0) {- return {- paths: [],- series: [] as readonly DayColumn[],- stepX: 0,- ticks: [0] as readonly number[],- toY: () => VIEW_HEIGHT,- };- }-- const columns = buildPeriodColumns(periods, byPeriod, metric);- // The scale tops out at the largest single provider-period, not the sum:- // layered series each measure from zero, so a combined peak would leave- // the plot permanently half empty.- const peak = columns.reduce(- (max, column) => column.bands.reduce((inner, band) => Math.max(inner, band.value), max),- 0,- );- const { max, ticks: tickValues } = niceScale(peak, TICK_COUNT);- const step = periods.length === 1 ? 0 : VIEW_WIDTH / (periods.length - 1);- // Leave room above the top gridline so the constant-width stroke is not- // clipped when a series reaches the peak.- const toY = (value: number) =>- max === 0 ? VIEW_HEIGHT : VIEW_HEIGHT - (value / max) * (VIEW_HEIGHT - PLOT_TOP);-- const built = providers.map((provider) => {- const providerIndex = PROVIDER_ORDER.indexOf(provider);- const line = curvePath(- smoothCurve(- columns.map((column, periodIndex) => ({- x: periodIndex * step,- y: toY(column.bands[providerIndex]?.value ?? 0),- })),- ),- );- return {- provider,- total: columns.reduce((sum, column) => sum + (column.bands[providerIndex]?.value ?? 0), 0),- area: line === "" ? "" : `${line} L${VIEW_WIDTH},${VIEW_HEIGHT} L0,${VIEW_HEIGHT} Z`,- line,- };- });-- // Paint the heavier series first so the lighter one is not buried.- return {- paths: built.toSorted((a, b) => b.total - a.total),- series: columns,- stepX: step,- ticks: tickValues,- toY,- };- }, [byPeriod, metric, periods, providers]);-- const format = metric === "tokens" ? formatTokens : formatUsd;-- const positionTooltip = useCallback(() => {- const plot = plotRef.current;- const tooltip = tooltipRef.current;- const hoverPosition = hoverPositionRef.current;- if (plot === null || tooltip === null || hoverPosition === null) return;-- const gap = 12;- const tooltipWidth = tooltip.offsetWidth;- const tooltipHeight = tooltip.offsetHeight;- const plotWidth = plot.clientWidth;- const plotHeight = plot.clientHeight;- const preferredLeft =- hoverPosition.x + gap + tooltipWidth <= plotWidth- ? hoverPosition.x + gap- : hoverPosition.x - gap - tooltipWidth;- const preferredTop =- hoverPosition.y + gap + tooltipHeight <= plotHeight- ? hoverPosition.y + gap- : hoverPosition.y - gap - tooltipHeight;- const left = Math.min(Math.max(0, preferredLeft), Math.max(0, plotWidth - tooltipWidth));- const top = Math.min(Math.max(0, preferredTop), Math.max(0, plotHeight - tooltipHeight));- plot.style.setProperty("--usage-tooltip-left", `${left}px`);- plot.style.setProperty("--usage-tooltip-top", `${top}px`);- }, []);-- useLayoutEffect(() => {- if (hoverIndex === null) return;- positionTooltip();-- const plot = plotRef.current;- const tooltip = tooltipRef.current;- if (plot === null || tooltip === null || typeof ResizeObserver === "undefined") return;-- const observer = new ResizeObserver(positionTooltip);- observer.observe(plot);- observer.observe(tooltip);- return () => observer.disconnect();- }, [hoverIndex, positionTooltip]);-- const handleMove = useCallback(- (event: React.MouseEvent<HTMLDivElement>) => {- const plot = plotRef.current;- if (plot === null || periods.length === 0) return;- const bounds = plot.getBoundingClientRect();- if (bounds.width === 0) return;- const localX = Math.min(bounds.width, Math.max(0, event.clientX - bounds.left));- const localY = Math.min(bounds.height, Math.max(0, event.clientY - bounds.top));- const fraction = localX / bounds.width;- const index = Math.round(fraction * (periods.length - 1));- hoverPositionRef.current = { x: localX, y: localY };- positionTooltip();- setHoverIndex(Math.min(periods.length - 1, Math.max(0, index)));- },- [periods.length, positionTooltip],- );-- const hoveredPeriod = hoverIndex === null ? undefined : periods[hoverIndex];- const hoveredColumn = hoverIndex === null ? undefined : series[hoverIndex];- const formatPeriod = (period: string) =>- resolution === "hour" ? formatHourShort(period, timeZone) : formatDayShort(period);- const formatTooltipPeriod = (period: string) =>- resolution === "hour" && referenceTime !== undefined- ? formatRelativeHourShort(period, referenceTime, timeZone)- : formatPeriod(period);-- return (- <div className="flex flex-col gap-1">- <div className="flex gap-2">- {/* Axis labels sit outside the plot so they stay aligned to gridlines. */}- <div className="relative h-56 w-14 shrink-0">- {ticks.map((tick) => (- <span- key={tick}- className="absolute right-0 -translate-y-1/2 text-[10px] text-muted-foreground tabular-nums"- style={{ top: `${(toY(tick) / VIEW_HEIGHT) * 100}%` }}- >- {tick === 0 ? "0" : format(tick)}- </span>- ))}- </div>-- <div- ref={plotRef}- className="relative h-56 flex-1"- onMouseMove={handleMove}- onMouseLeave={() => {- hoverPositionRef.current = null;- setHoverIndex(null);- }}- >- <svg- className="h-full w-full"- viewBox={`0 0 ${VIEW_WIDTH} ${VIEW_HEIGHT}`}- preserveAspectRatio="none"- role="img"- aria-label={`${resolution === "hour" ? "Hourly" : "Daily"} ${metric === "tokens" ? "processed tokens" : "cost"} by provider`}- >- {ticks.map((tick) => {- const y = toY(tick);- return (- <line- key={tick}- x1={0}- x2={VIEW_WIDTH}- y1={y}- y2={y}- stroke="currentColor"- strokeWidth={1}- className="text-border"- vectorEffect="non-scaling-stroke"- />- );- })}-- {/* Fills first, then every stroke, so no series covers another's line. */}- {paths.map(({ provider, area }) => (- <path- key={provider}- d={area}- fill={PROVIDER_PRESENTATION[provider].color}- fillOpacity={0.12}- />- ))}- {paths.map(({ provider, line }) => (- <path- key={provider}- d={line}- fill="none"- stroke={PROVIDER_PRESENTATION[provider].color}- strokeWidth={2}- vectorEffect="non-scaling-stroke"- />- ))}-- {hoverIndex === null ? null : (- <line- x1={hoverIndex * stepX}- x2={hoverIndex * stepX}- y1={PLOT_TOP}- y2={VIEW_HEIGHT}- stroke="currentColor"- strokeWidth={1}- className="text-muted-foreground"- vectorEffect="non-scaling-stroke"- />- )}- </svg>-- {hoveredPeriod === undefined ? null : (- <div- ref={tooltipRef}- className="surface-glass pointer-events-none absolute z-10 min-w-36 max-w-full rounded-xl border border-border/50 px-2.5 py-2 text-xs shadow-lg"- style={{- left: "var(--usage-tooltip-left, 0px)",- top: "var(--usage-tooltip-top, 0px)",- }}- >- <div className="mb-1 text-muted-foreground">{formatTooltipPeriod(hoveredPeriod)}</div>- {providers.map((provider) => {- const { label, mark: Mark } = PROVIDER_PRESENTATION[provider];- return (- <div key={provider} className="flex items-center justify-between gap-3">- <span className="flex items-center gap-1.5 text-muted-foreground">- <Mark className="size-3 shrink-0" aria-hidden />- {label}- </span>- <span className="text-foreground tabular-nums">- {format(- hoveredColumn?.bands.find((band) => band.provider === provider)?.value ?? 0,- )}- </span>- </div>- );- })}- <div className="mt-1 flex items-center justify-between gap-3 border-t border-border pt-1">- <span className="text-muted-foreground">Total</span>- <span className="text-foreground tabular-nums">- {format(hoveredColumn?.total ?? 0)}- </span>- </div>- </div>- )}- </div>- </div>-- <div className="flex justify-between pl-16 text-[10px] text-muted-foreground uppercase">- <span>{periods[0] === undefined ? "" : formatPeriod(periods[0])}</span>- <span>- {periods[Math.floor(periods.length / 2)] === undefined- ? ""- : formatPeriod(periods[Math.floor(periods.length / 2)] ?? "")}- </span>- <span>- {periods[periods.length - 1] === undefined- ? ""- : formatPeriod(periods[periods.length - 1] ?? "")}- </span>- </div>- </div>- );-}diff --git a/apps/web/src/connection/platform.ts b/apps/web/src/connection/platform.tsindex daead0bc6..1332bf7ff 100644--- a/apps/web/src/connection/platform.ts+++ b/apps/web/src/connection/platform.ts@@ -118,7 +118,7 @@ function clientMetadata() {const desktop = window.desktopBridge !== undefined;const platform = navigator.platform.trim();return {- label: desktop ? "T3 Code Desktop" : "T3 Code Web",+ label: desktop ? "Akeru Bot Desktop" : "Akeru Bot Web",deviceType: "desktop" as const,...(platform === "" ? {} : { os: platform }),surface: desktop ? ("desktop" as const) : ("web" as const),@@ -185,7 +185,7 @@ const capabilitiesLayer = Layer.effectContext(if (session === null) {return yield* new ConnectionBlockedError({reason: "authentication",- detail: "Sign in to T3 Connect to connect this environment.",+ detail: "Sign in to connect this environment.",});}const token = yield* session.readClerkToken().pipe(@@ -200,7 +200,7 @@ const capabilitiesLayer = Layer.effectContext(if (token === null) {return yield* new ConnectionBlockedError({reason: "authentication",- detail: "The T3 Connect session is unavailable.",+ detail: "The remote access session is unavailable.",});}return token;diff --git a/apps/web/src/connection/runtime.ts b/apps/web/src/connection/runtime.tsindex b63d01999..e771b3f95 100644--- a/apps/web/src/connection/runtime.ts+++ b/apps/web/src/connection/runtime.ts@@ -1,7 +1,6 @@import { Connection } from "@t3tools/client-runtime/connection";import { shellSnapshotLoaderLayer } from "@t3tools/client-runtime/state/shell";import { threadSnapshotLoaderLayer } from "@t3tools/client-runtime/state/threads";-import { pullRequestDiffLoaderLayer } from "@t3tools/client-runtime/state/pull-requests";import * as Layer from "effect/Layer";import { Atom } from "effect/unstable/reactivity";@@ -16,11 +15,7 @@ const providedConnectionPlatformLayer = connectionPlatformLayer.pipe(Layer.provide(runtimeContextLayer),);-const snapshotLoaderLayer = Layer.mergeAll(- threadSnapshotLoaderLayer,- shellSnapshotLoaderLayer,- pullRequestDiffLoaderLayer,-);+const snapshotLoaderLayer = Layer.mergeAll(threadSnapshotLoaderLayer, shellSnapshotLoaderLayer);type ConnectionLayerSource =| typeof Connection.layerdiff --git a/apps/web/src/hooks/useHandleNewThread.ts b/apps/web/src/hooks/useHandleNewThread.tsindex ed88a2033..439cef3fb 100644--- a/apps/web/src/hooks/useHandleNewThread.ts+++ b/apps/web/src/hooks/useHandleNewThread.ts@@ -4,7 +4,12 @@ import {scopeProjectRef,scopeThreadRef,} from "@t3tools/client-runtime/environment";-import { DEFAULT_RUNTIME_MODE, type ScopedProjectRef, type ThreadId } from "@t3tools/contracts";+import {+ DEFAULT_RUNTIME_MODE,+ type RuntimeMode,+ type ScopedProjectRef,+ type ThreadId,+} from "@t3tools/contracts";import { useParams, useRouter } from "@tanstack/react-router";import { useCallback, useMemo } from "react";import {@@ -73,6 +78,7 @@ export function useNewThreadHandler() {worktreePath?: string | null;envMode?: DraftThreadEnvMode;startFromOrigin?: boolean;+ runtimeMode?: RuntimeMode;replace?: boolean;/*** Move the viewed draft's typed content (prompt + images) into the@@ -126,6 +132,7 @@ export function useNewThreadHandler() {const carryModelSelection =composerModelSelection ?? carrySourceShell?.modelSelection ?? null;const carryRuntimeMode =+ options?.runtimeMode ??carrySourceComposer?.runtimeMode ??carrySourceShell?.runtimeMode ??carrySourceDraft?.runtimeMode ??diff --git a/apps/web/src/hooks/useTheme.test.ts b/apps/web/src/hooks/useTheme.test.tsindex ab87388ff..045e8f6d5 100644--- a/apps/web/src/hooks/useTheme.test.ts+++ b/apps/web/src/hooks/useTheme.test.ts@@ -70,6 +70,26 @@ describe("theme failure handling", () => {}});+ it("uses Akeru Paper for a fresh profile", async () => {+ vi.stubGlobal("window", { localStorage: createStorage() });++ const { readThemePreference } = await import("./useTheme");++ expect(readThemePreference()).toBe("akeru-paper");+ });++ it("migrates the old system default to Akeru Paper", async () => {+ vi.stubGlobal("window", {+ localStorage: createStorage({+ getItem: (key) => (key === "t3code:theme" ? "system" : null),+ }),+ });++ const { readThemePreference } = await import("./useTheme");++ expect(readThemePreference()).toBe("akeru-paper");+ });+it("reads the persisted T3 Chat theme preference", async () => {vi.stubGlobal("window", {localStorage: createStorage({diff --git a/apps/web/src/hooks/useTheme.ts b/apps/web/src/hooks/useTheme.tsindex 8696e41b7..8807532f5 100644--- a/apps/web/src/hooks/useTheme.ts+++ b/apps/web/src/hooks/useTheme.ts@@ -35,8 +35,9 @@ type DesktopThemeBridge = Pick<DesktopBridge, "setTheme">;const STORAGE_KEY = "t3code:theme";const MEDIA_QUERY = "(prefers-color-scheme: dark)";+const DEFAULT_THEME = "akeru-paper";const DEFAULT_THEME_SNAPSHOT: ThemeSnapshot = {- theme: "system",+ theme: DEFAULT_THEME,systemDark: false,followSystem: true,appearanceMode: "system",@@ -125,7 +126,7 @@ function readStoredFollowSystem(theme: Theme): boolean {// Fall back to the legacy theme value when the separate preference is unavailable.}- return theme === "system";+ return theme === "system" || theme === DEFAULT_THEME;}function isThemePreferenceMode(value: string | null): value is ThemePreferenceMode {@@ -174,7 +175,7 @@ export function readThemePreference(): Theme {});}if (raw !== null && isKnownThemePreference(raw)) {- return canonicalThemePreference(raw);+ return raw === "system" ? DEFAULT_THEME : canonicalThemePreference(raw);}return DEFAULT_THEME_SNAPSHOT.theme;}diff --git a/apps/web/src/index.css b/apps/web/src/index.cssindex d43475f90..01c0e6b5c 100644--- a/apps/web/src/index.css+++ b/apps/web/src/index.css@@ -1,4 +1,6 @@@import "tailwindcss";+@import "@fontsource-variable/geist";+@import "@fontsource-variable/geist-mono";@custom-variant dark (&:is(.dark, .dark *));@custom-variant light (&:not(.dark, .dark *));@@ -137,9 +139,12 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobilthe variables and Settings -> Appearance can override them at runtime. Thedefault stacks are mirrored in `appearanceFonts.ts`. */@theme {- --font-sans: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;+ --font-brand-serif: Georgia, "Times New Roman", serif;+ --font-sans:+ "Geist Variable", -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;--font-mono:- ui-monospace, "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace;+ "Geist Mono Variable", "SF Mono", "SFMono-Regular", Menlo, Consolas, "Liberation Mono",+ monospace;}@theme inline {@@ -310,9 +315,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil}@utility dialog-glass {- background: color-mix(in srgb, var(--background) var(--glass-opacity), transparent);- -webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));- backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));+ background: var(--popover);border-color: color-mix(in srgb, var(--contrast-foreground) 10%, transparent);box-shadow: 0 24px 64px -24px rgb(0 0 0 / 65%);@@ -322,10 +325,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobilinset 0 1px rgb(255 255 255 / 4%),0 24px 72px -20px rgb(0 0 0 / 90%);}-- @supports not ((-webkit-backdrop-filter: blur(1px)) or (backdrop-filter: blur(1px))) {- background: var(--popover) !important;- }}@utility dialog-backdrop {@@ -339,18 +338,8 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil}@utility dropdown-glass {- background: color-mix(- in srgb,- var(--popover) 18%,- color-mix(in srgb, var(--popover) var(--glass-opacity), transparent)- );- -webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));- backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));+ background: var(--popover);border: 1px solid color-mix(in srgb, var(--contrast-foreground) 10%, transparent);-- @supports not ((-webkit-backdrop-filter: blur(1px)) or (backdrop-filter: blur(1px))) {- background: var(--popover) !important;- }}@utility topbar-scroll-fade {@@ -854,11 +843,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobilrgb(0 0 0 / 18%) var(--chat-composer-attachment-overlap),transparent calc(var(--chat-composer-attachment-overlap) + 10px)),- color-mix(- in srgb,- var(--chat-composer-attached-surface) var(--glass-opacity),- transparent- );+ var(--chat-composer-attached-surface);box-shadow: 0 14px 32px -18px rgb(0 0 0 / 75%);}}@@ -893,9 +878,7 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobilborder-radius: 16px 16px 0 0;background:linear-gradient(var(--chat-composer-attached-tint), var(--chat-composer-attached-tint)),- color-mix(in srgb, var(--chat-composer-attached-surface) var(--glass-opacity), transparent);- -webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));- backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));+ var(--chat-composer-attached-surface);-webkit-mask-image: linear-gradient(to top,transparent 0 var(--chat-composer-attachment-overlap),@@ -908,12 +891,6 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil);box-shadow: 0 12px 28px -18px rgb(0 0 0 / 40%);content: "";-- @supports not ((-webkit-backdrop-filter: blur(1px)) or (backdrop-filter: blur(1px))) {- background:- linear-gradient(var(--chat-composer-attached-tint), var(--chat-composer-attached-tint)),- var(--chat-composer-attached-surface) !important;- }}.chat-composer-drawer-slot + .chat-composer-drawer-slot::before,@@ -2032,6 +2009,15 @@ body {--surface-grain-size: 256px 256px;}+html[data-theme-id="akeru-paper"] {+ @variant dark {+ --surface-grain: none;+ --glass-opacity: 100%;+ --glass-blur: 0px;+ --glass-saturation: 1;+ }+}+/* The live T3 Chat texture is a 128px grayscale tile with a constant 7/255alpha. Keep our procedural texture cheap while matching that scale andstrength for the branded preset. */@@ -2155,6 +2141,19 @@ code {color: var(--contrast-muted-foreground);}+.chat-markdown .katex-display {+ overflow-x: auto;+ overflow-y: hidden;+ padding-block: 0.25rem;+}++.chat-markdown-mermaid svg {+ width: auto;+ max-width: 100%;+ height: auto;+ margin-inline: auto;+}+.chat-markdown ul {/* Reset for nested uls under a widened ol — --list-gutter is an inheritedcustom property, so without this a task-list under a 3+ digit ordered@@ -2521,3 +2520,222 @@ code {transform: scaleX(0.9);}}++/* Bot avatars. State-driven and transform-only. Working uses weighted+ squash-and-stretch. Needs-you calls twice, then holds. Success hops once.+ Never use fill-box: a blinking <g> shrinks its origin every frame and the+ avatar strobes. Body motion is the 100×100 viewBox; eyes use their own. */+.bot-avatar {+ overflow: visible;+}++.bot-avatar .bot-body {+ transform-box: view-box;+ transform-origin: 50px 100px;+}++.bot-avatar .bot-eyes {+ display: inline;+ overflow: visible;+ transform-box: view-box;+ transform-origin: 50% 50%;+}++.bot-avatar[data-bot-state="idle"] .bot-eyes {+ animation: bot-blink 6.4s linear infinite;+ animation-delay: var(--bot-blink-delay, 0ms);+}++.bot-avatar[data-bot-state="idle"]:hover .bot-body,+[data-bot-hover]:hover .bot-avatar[data-bot-state="idle"] .bot-body {+ animation: bot-hover 240ms cubic-bezier(0.2, 0, 0, 1);+}++.bot-avatar[data-bot-state="working"] .bot-body {+ animation: bot-work 960ms cubic-bezier(0.45, 0, 0.55, 1) infinite;+}++.bot-avatar[data-bot-state="needs-you"] .bot-body {+ animation: bot-call 2.4s linear infinite;+}++.bot-avatar[data-bot-state="success"] .bot-body {+ animation: bot-success 680ms linear both;+}++.bot-avatar[data-bot-state="success"] .bot-eyes {+ animation: bot-success-eyes 680ms cubic-bezier(0.2, 0.8, 0.2, 1) both;+}++.bot-status-shimmer {+ color: transparent;+ background-image: linear-gradient(+ 100deg,+ color-mix(in srgb, var(--foreground) 48%, transparent) 20%,+ var(--foreground) 48%,+ color-mix(in srgb, var(--foreground) 48%, transparent) 76%+ );+ background-position: 120% 0;+ background-size: 240% 100%;+ background-clip: text;+ animation: bot-status-shimmer 1.8s linear infinite;+}++@keyframes bot-status-shimmer {+ to {+ background-position: -120% 0;+ }+}++@keyframes bot-work {+ 0%,+ 100% {+ transform: translateY(0) rotate(0deg) scale(1, 1);+ }++ 12% {+ transform: translateY(1%) rotate(-2deg) scale(1.03, 0.97);+ }++ 28% {+ transform: translateY(-2%) rotate(-5deg) scale(0.97, 1.04);+ }++ 50% {+ transform: translateY(0) rotate(0deg) scale(1.02, 0.98);+ }++ 62% {+ transform: translateY(1%) rotate(2deg) scale(1.03, 0.97);+ }++ 78% {+ transform: translateY(-2%) rotate(5deg) scale(0.97, 1.04);+ }+}++@keyframes bot-call {+ 0%,+ 70%,+ 100% {+ transform: translateY(0) rotate(0deg) scale(1, 1);+ }++ 6% {+ transform: translateY(1%) rotate(0deg) scale(1.06, 0.92);+ animation-timing-function: cubic-bezier(0.4, 0, 1, 1);+ }++ 14% {+ transform: translateY(-7%) rotate(-3deg) scale(0.95, 1.08);+ animation-timing-function: cubic-bezier(0, 0, 0.2, 1);+ }++ 24% {+ transform: translateY(0) rotate(2deg) scale(1.04, 0.95);+ }++ 32% {+ transform: translateY(0) rotate(0deg) scale(1, 1);+ }++ 44% {+ transform: translateY(1%) rotate(0deg) scale(1.04, 0.95);+ }++ 52% {+ transform: translateY(-4%) rotate(3deg) scale(0.98, 1.05);+ }++ 62% {+ transform: translateY(0) rotate(-1deg) scale(1.02, 0.98);+ }+}++@keyframes bot-success {+ 0% {+ transform: translateY(0) rotate(0deg) scale(1, 1);+ }++ 12% {+ transform: translateY(1%) rotate(0deg) scale(1.1, 0.88);+ animation-timing-function: cubic-bezier(0.4, 0, 1, 1);+ }++ 32% {+ transform: translateY(-12%) rotate(-4deg) scale(0.94, 1.08);+ animation-timing-function: cubic-bezier(0, 0, 0.2, 1);+ }++ 48% {+ transform: translateY(-10%) rotate(4deg) scale(0.96, 1.06);+ }++ 65% {+ transform: translateY(0) rotate(0deg) scale(1.08, 0.9);+ }++ 80% {+ transform: translateY(-3%) rotate(0deg) scale(0.98, 1.03);+ }++ 100% {+ transform: translateY(0) rotate(0deg) scale(1, 1);+ }+}++@keyframes bot-success-eyes {+ 0%,+ 10% {+ transform: translateY(4%) scaleY(0.2);+ }++ 30% {+ transform: translateY(-2%) scaleY(1);+ }++ 46% {+ transform: translateY(0) scaleY(1.08);+ }++ 100% {+ transform: translateY(0) scaleY(1);+ }+}++@keyframes bot-blink {+ 0%,+ 93%,+ 95.25%,+ 100% {+ transform: scaleY(1);+ }++ 94% {+ transform: scaleY(0.08);+ }+}++@keyframes bot-hover {+ 0%,+ 100% {+ transform: translateY(0) scale(1, 1);+ }++ 50% {+ transform: translateY(-2px) scale(1.03, 0.98);+ }+}++@media (prefers-reduced-motion: reduce) {+ .bot-avatar .bot-eyes,+ .bot-avatar .bot-body,+ .bot-status-shimmer {+ animation: none;+ }++ .bot-status-shimmer {+ color: var(--foreground);+ background: none;+ }+}diff --git a/apps/web/src/lib/diffFileContents.ts b/apps/web/src/lib/diffFileContents.tsindex 2dc4e5558..89c52d1e6 100644--- a/apps/web/src/lib/diffFileContents.ts+++ b/apps/web/src/lib/diffFileContents.ts@@ -5,9 +5,6 @@ import {} from "@t3tools/client-runtime/state/runtime";import type {EnvironmentId,- PullRequestDiffFileContentsInput,- PullRequestDiffFileContentsResult,- PullRequestRef,ReviewDiffFileContentsInput,ReviewDiffFileContentsResult,ReviewDiffPreviewSourceKind,@@ -25,26 +22,14 @@ interface GitDiffFileContentsSource {readonly cacheKey: string;}-interface PullRequestDiffFileContentsSource {- readonly environmentId: EnvironmentId;- readonly reference: PullRequestRef;- readonly commit: string | null;- readonly cacheKey: string;-}-type GetDiffFileContents<E> = (request: {readonly environmentId: EnvironmentId;readonly input: ReviewDiffFileContentsInput;}) => Promise<AtomCommandResult<ReviewDiffFileContentsResult, E>>;-type GetPullRequestDiffFileContents<E> = (request: {- readonly environmentId: EnvironmentId;- readonly input: PullRequestDiffFileContentsInput;-}) => Promise<AtomCommandResult<PullRequestDiffFileContentsResult, E>>;-function createDiffFileContentsLoader(load: (input: {- readonly changeType: PullRequestDiffFileContentsInput["changeType"];+ readonly changeType: ReviewDiffFileContentsInput["changeType"];readonly oldPath: string;readonly newPath: string;}) => Promise<{ readonly oldContents: string; readonly newContents: string }>,@@ -99,26 +84,3 @@ export function createGitDiffFileContentsLoader<E>(return result.value;}, source.cacheKey);}--/** Loads host-backed PR files, which may name revisions this checkout has never fetched. */-export function createPullRequestDiffFileContentsLoader<E>(- getDiffFileContents: GetPullRequestDiffFileContents<E>,- source: PullRequestDiffFileContentsSource,-): FileDiffContentsLoader {- return createDiffFileContentsLoader(async ({ changeType, oldPath, newPath }) => {- const result = await getDiffFileContents({- environmentId: source.environmentId,- input: {- ...source.reference,- ...(source.commit === null ? {} : { commit: source.commit }),- changeType,- oldPath,- newPath,- },- });- if (result._tag !== "Success") {- throw squashAtomCommandFailure(result);- }- return result.value;- }, source.cacheKey);-}diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsxindex 3cdc8188b..c5468585d 100644--- a/apps/web/src/main.tsx+++ b/apps/web/src/main.tsx@@ -53,3 +53,7 @@ ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render()}</React.StrictMode>,);++if (import.meta.env.DEV) {+ void import("react-grab");+}diff --git a/apps/web/src/pluginsDialogStore.test.ts b/apps/web/src/pluginsDialogStore.test.tsnew file mode 100644index 000000000..a3436ff08--- /dev/null+++ b/apps/web/src/pluginsDialogStore.test.ts@@ -0,0 +1,24 @@+import { afterEach, describe, expect, it } from "vite-plus/test";+import {+ closePlugins,+ isLegacyPluginsPath,+ openPlugins,+ usePluginsDialogStore,+} from "./pluginsDialogStore";++afterEach(closePlugins);++describe("plugins dialog store", () => {+ it("opens and closes independently from settings", () => {+ expect(usePluginsDialogStore.getState().open).toBe(false);+ openPlugins();+ expect(usePluginsDialogStore.getState().open).toBe(true);+ closePlugins();+ expect(usePluginsDialogStore.getState().open).toBe(false);+ });++ it("recognizes the old Settings plugins path", () => {+ expect(isLegacyPluginsPath("/settings/plugins")).toBe(true);+ expect(isLegacyPluginsPath("/settings/providers")).toBe(false);+ });+});diff --git a/apps/web/src/pluginsDialogStore.ts b/apps/web/src/pluginsDialogStore.tsnew file mode 100644index 000000000..54cdeedba--- /dev/null+++ b/apps/web/src/pluginsDialogStore.ts@@ -0,0 +1,25 @@+import { create } from "zustand";++interface PluginsDialogState {+ readonly open: boolean;+ readonly openPlugins: () => void;+ readonly closePlugins: () => void;+}++export const usePluginsDialogStore = create<PluginsDialogState>((set) => ({+ open: false,+ openPlugins: () => set({ open: true }),+ closePlugins: () => set({ open: false }),+}));++export function openPlugins(): void {+ usePluginsDialogStore.getState().openPlugins();+}++export function closePlugins(): void {+ usePluginsDialogStore.getState().closePlugins();+}++export function isLegacyPluginsPath(pathname: string): boolean {+ return pathname.replace(/^\/settings\/?/, "").split("/")[0] === "plugins";+}diff --git a/apps/web/src/reactGrabBoundary.test.ts b/apps/web/src/reactGrabBoundary.test.tsindex 9481e2dd9..881ae41ef 100644--- a/apps/web/src/reactGrabBoundary.test.ts+++ b/apps/web/src/reactGrabBoundary.test.ts@@ -4,9 +4,9 @@ import packageJson from "../package.json" with { type: "json" };import mainSource from "./main.tsx?raw";describe("React Grab runtime boundary", () => {- it("keeps the host renderer free of the React Grab overlay", () => {- expect(mainSource).not.toMatch(/import\(["']react-grab["']\)/);+ it("loads the React Grab overlay only in development", () => {+ expect(mainSource).toMatch(/import\.meta\.env\.DEV[\s\S]*import\(["']react-grab["']\)/);expect(packageJson.dependencies).not.toHaveProperty("react-grab");- expect(packageJson.devDependencies).not.toHaveProperty("react-grab");+ expect(packageJson.devDependencies).toHaveProperty("react-grab");});});diff --git a/apps/web/src/reviewCommentContext.ts b/apps/web/src/reviewCommentContext.tsindex 41f75eb38..00882af94 100644--- a/apps/web/src/reviewCommentContext.ts+++ b/apps/web/src/reviewCommentContext.ts@@ -1,7 +1,16 @@import type { FileDiffMetadata, SelectedLineRange, SelectionSide } from "@pierre/diffs";-import type { PullRequestReviewPosition } from "@t3tools/contracts";import * as Schema from "effect/Schema";+type PullRequestReviewPosition =+ | { readonly kind: "added"; readonly newLine: number }+ | { readonly kind: "deleted"; readonly oldLine: number }+ | {+ readonly kind: "context";+ readonly oldLine: number;+ readonly newLine: number;+ readonly side?: "left" | "right";+ };+const ReviewCommentSelectionSchema = Schema.Struct({start: Schema.Number,side: Schema.Literals(["additions", "deletions"]),diff --git a/apps/web/src/routeTree.gen.ts b/apps/web/src/routeTree.gen.tsindex f7c47ace6..e32076ace 100644--- a/apps/web/src/routeTree.gen.ts+++ b/apps/web/src/routeTree.gen.ts@@ -15,19 +15,11 @@ import { Route as PairRouteImport } from './routes/pair'import { Route as ConnectRouteImport } from './routes/connect'import { Route as ChatRouteImport } from './routes/_chat'import { Route as ChatIndexRouteImport } from './routes/_chat.index'-import { Route as SettingsSourceControlRouteImport } from './routes/settings.source-control'-import { Route as SettingsProvidersRouteImport } from './routes/settings.providers'-import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybindings'-import { Route as SettingsIntegrationsRouteImport } from './routes/settings.integrations'-import { Route as SettingsGeneralRouteImport } from './routes/settings.general'-import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'-import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'-import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'-import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'import { Route as ProjectsProjectKeyRouteImport } from './routes/projects.$projectKey'import { Route as ConnectCallbackRouteImport } from './routes/connect_.callback'-import { Route as ChatPullRequestsRouteImport } from './routes/_chat.pull-requests'+import { Route as ChatGroupsGroupIdRouteImport } from './routes/_chat.groups.$groupId'import { Route as ChatDraftDraftIdRouteImport } from './routes/_chat.draft.$draftId'+import { Route as ChatBotsBotIdRouteImport } from './routes/_chat.bots.$botId'import { Route as ChatEnvironmentIdThreadIdRouteImport } from './routes/_chat.$environmentId.$threadId'const UsageRoute = UsageRouteImport.update({@@ -59,51 +51,6 @@ const ChatIndexRoute = ChatIndexRouteImport.update({path: '/',getParentRoute: () => ChatRoute,} as any)-const SettingsSourceControlRoute = SettingsSourceControlRouteImport.update({- id: '/source-control',- path: '/source-control',- getParentRoute: () => SettingsRoute,-} as any)-const SettingsProvidersRoute = SettingsProvidersRouteImport.update({- id: '/providers',- path: '/providers',- getParentRoute: () => SettingsRoute,-} as any)-const SettingsKeybindingsRoute = SettingsKeybindingsRouteImport.update({- id: '/keybindings',- path: '/keybindings',- getParentRoute: () => SettingsRoute,-} as any)-const SettingsIntegrationsRoute = SettingsIntegrationsRouteImport.update({- id: '/integrations',- path: '/integrations',- getParentRoute: () => SettingsRoute,-} as any)-const SettingsGeneralRoute = SettingsGeneralRouteImport.update({- id: '/general',- path: '/general',- getParentRoute: () => SettingsRoute,-} as any)-const SettingsDiagnosticsRoute = SettingsDiagnosticsRouteImport.update({- id: '/diagnostics',- path: '/diagnostics',- getParentRoute: () => SettingsRoute,-} as any)-const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({- id: '/connections',- path: '/connections',- getParentRoute: () => SettingsRoute,-} as any)-const SettingsArchivedRoute = SettingsArchivedRouteImport.update({- id: '/archived',- path: '/archived',- getParentRoute: () => SettingsRoute,-} as any)-const SettingsAppearanceRoute = SettingsAppearanceRouteImport.update({- id: '/appearance',- path: '/appearance',- getParentRoute: () => SettingsRoute,-} as any)const ProjectsProjectKeyRoute = ProjectsProjectKeyRouteImport.update({id: '/projects/$projectKey',path: '/projects/$projectKey',@@ -114,9 +61,9 @@ const ConnectCallbackRoute = ConnectCallbackRouteImport.update({path: '/connect/callback',getParentRoute: () => rootRouteImport,} as any)-const ChatPullRequestsRoute = ChatPullRequestsRouteImport.update({- id: '/pull-requests',- path: '/pull-requests',+const ChatGroupsGroupIdRoute = ChatGroupsGroupIdRouteImport.update({+ id: '/groups/$groupId',+ path: '/groups/$groupId',getParentRoute: () => ChatRoute,} as any)const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({@@ -124,6 +71,11 @@ const ChatDraftDraftIdRoute = ChatDraftDraftIdRouteImport.update({path: '/draft/$draftId',getParentRoute: () => ChatRoute,} as any)+const ChatBotsBotIdRoute = ChatBotsBotIdRouteImport.update({+ id: '/bots/$botId',+ path: '/bots/$botId',+ getParentRoute: () => ChatRoute,+} as any)const ChatEnvironmentIdThreadIdRoute =ChatEnvironmentIdThreadIdRouteImport.update({id: '/$environmentId/$threadId',@@ -135,66 +87,42 @@ export interface FileRoutesByFullPath {'/': typeof ChatIndexRoute'/connect': typeof ConnectRoute'/pair': typeof PairRoute- '/settings': typeof SettingsRouteWithChildren+ '/settings': typeof SettingsRoute'/usage': typeof UsageRoute- '/pull-requests': typeof ChatPullRequestsRoute'/connect/callback': typeof ConnectCallbackRoute'/projects/$projectKey': typeof ProjectsProjectKeyRoute- '/settings/appearance': typeof SettingsAppearanceRoute- '/settings/archived': typeof SettingsArchivedRoute- '/settings/connections': typeof SettingsConnectionsRoute- '/settings/diagnostics': typeof SettingsDiagnosticsRoute- '/settings/general': typeof SettingsGeneralRoute- '/settings/integrations': typeof SettingsIntegrationsRoute- '/settings/keybindings': typeof SettingsKeybindingsRoute- '/settings/providers': typeof SettingsProvidersRoute- '/settings/source-control': typeof SettingsSourceControlRoute'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute+ '/bots/$botId': typeof ChatBotsBotIdRoute'/draft/$draftId': typeof ChatDraftDraftIdRoute+ '/groups/$groupId': typeof ChatGroupsGroupIdRoute}export interface FileRoutesByTo {'/connect': typeof ConnectRoute'/pair': typeof PairRoute- '/settings': typeof SettingsRouteWithChildren+ '/settings': typeof SettingsRoute'/usage': typeof UsageRoute- '/pull-requests': typeof ChatPullRequestsRoute'/connect/callback': typeof ConnectCallbackRoute'/projects/$projectKey': typeof ProjectsProjectKeyRoute- '/settings/appearance': typeof SettingsAppearanceRoute- '/settings/archived': typeof SettingsArchivedRoute- '/settings/connections': typeof SettingsConnectionsRoute- '/settings/diagnostics': typeof SettingsDiagnosticsRoute- '/settings/general': typeof SettingsGeneralRoute- '/settings/integrations': typeof SettingsIntegrationsRoute- '/settings/keybindings': typeof SettingsKeybindingsRoute- '/settings/providers': typeof SettingsProvidersRoute- '/settings/source-control': typeof SettingsSourceControlRoute'/': typeof ChatIndexRoute'/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute+ '/bots/$botId': typeof ChatBotsBotIdRoute'/draft/$draftId': typeof ChatDraftDraftIdRoute+ '/groups/$groupId': typeof ChatGroupsGroupIdRoute}export interface FileRoutesById {__root__: typeof rootRouteImport'/_chat': typeof ChatRouteWithChildren'/connect': typeof ConnectRoute'/pair': typeof PairRoute- '/settings': typeof SettingsRouteWithChildren+ '/settings': typeof SettingsRoute'/usage': typeof UsageRoute- '/_chat/pull-requests': typeof ChatPullRequestsRoute'/connect_/callback': typeof ConnectCallbackRoute'/projects/$projectKey': typeof ProjectsProjectKeyRoute- '/settings/appearance': typeof SettingsAppearanceRoute- '/settings/archived': typeof SettingsArchivedRoute- '/settings/connections': typeof SettingsConnectionsRoute- '/settings/diagnostics': typeof SettingsDiagnosticsRoute- '/settings/general': typeof SettingsGeneralRoute- '/settings/integrations': typeof SettingsIntegrationsRoute- '/settings/keybindings': typeof SettingsKeybindingsRoute- '/settings/providers': typeof SettingsProvidersRoute- '/settings/source-control': typeof SettingsSourceControlRoute'/_chat/': typeof ChatIndexRoute'/_chat/$environmentId/$threadId': typeof ChatEnvironmentIdThreadIdRoute+ '/_chat/bots/$botId': typeof ChatBotsBotIdRoute'/_chat/draft/$draftId': typeof ChatDraftDraftIdRoute+ '/_chat/groups/$groupId': typeof ChatGroupsGroupIdRoute}export interface FileRouteTypes {fileRoutesByFullPath: FileRoutesByFullPath@@ -204,41 +132,25 @@ export interface FileRouteTypes {| '/pair'| '/settings'| '/usage'- | '/pull-requests'| '/connect/callback'| '/projects/$projectKey'- | '/settings/appearance'- | '/settings/archived'- | '/settings/connections'- | '/settings/diagnostics'- | '/settings/general'- | '/settings/integrations'- | '/settings/keybindings'- | '/settings/providers'- | '/settings/source-control'| '/$environmentId/$threadId'+ | '/bots/$botId'| '/draft/$draftId'+ | '/groups/$groupId'fileRoutesByTo: FileRoutesByToto:| '/connect'| '/pair'| '/settings'| '/usage'- | '/pull-requests'| '/connect/callback'| '/projects/$projectKey'- | '/settings/appearance'- | '/settings/archived'- | '/settings/connections'- | '/settings/diagnostics'- | '/settings/general'- | '/settings/integrations'- | '/settings/keybindings'- | '/settings/providers'- | '/settings/source-control'| '/'| '/$environmentId/$threadId'+ | '/bots/$botId'| '/draft/$draftId'+ | '/groups/$groupId'id:| '__root__'| '/_chat'@@ -246,28 +158,20 @@ export interface FileRouteTypes {| '/pair'| '/settings'| '/usage'- | '/_chat/pull-requests'| '/connect_/callback'| '/projects/$projectKey'- | '/settings/appearance'- | '/settings/archived'- | '/settings/connections'- | '/settings/diagnostics'- | '/settings/general'- | '/settings/integrations'- | '/settings/keybindings'- | '/settings/providers'- | '/settings/source-control'| '/_chat/'| '/_chat/$environmentId/$threadId'+ | '/_chat/bots/$botId'| '/_chat/draft/$draftId'+ | '/_chat/groups/$groupId'fileRoutesById: FileRoutesById}export interface RootRouteChildren {ChatRoute: typeof ChatRouteWithChildrenConnectRoute: typeof ConnectRoutePairRoute: typeof PairRoute- SettingsRoute: typeof SettingsRouteWithChildren+ SettingsRoute: typeof SettingsRouteUsageRoute: typeof UsageRouteConnectCallbackRoute: typeof ConnectCallbackRouteProjectsProjectKeyRoute: typeof ProjectsProjectKeyRoute@@ -317,69 +221,6 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ChatIndexRouteImportparentRoute: typeof ChatRoute}- '/settings/source-control': {- id: '/settings/source-control'- path: '/source-control'- fullPath: '/settings/source-control'- preLoaderRoute: typeof SettingsSourceControlRouteImport- parentRoute: typeof SettingsRoute- }- '/settings/providers': {- id: '/settings/providers'- path: '/providers'- fullPath: '/settings/providers'- preLoaderRoute: typeof SettingsProvidersRouteImport- parentRoute: typeof SettingsRoute- }- '/settings/keybindings': {- id: '/settings/keybindings'- path: '/keybindings'- fullPath: '/settings/keybindings'- preLoaderRoute: typeof SettingsKeybindingsRouteImport- parentRoute: typeof SettingsRoute- }- '/settings/integrations': {- id: '/settings/integrations'- path: '/integrations'- fullPath: '/settings/integrations'- preLoaderRoute: typeof SettingsIntegrationsRouteImport- parentRoute: typeof SettingsRoute- }- '/settings/general': {- id: '/settings/general'- path: '/general'- fullPath: '/settings/general'- preLoaderRoute: typeof SettingsGeneralRouteImport- parentRoute: typeof SettingsRoute- }- '/settings/diagnostics': {- id: '/settings/diagnostics'- path: '/diagnostics'- fullPath: '/settings/diagnostics'- preLoaderRoute: typeof SettingsDiagnosticsRouteImport- parentRoute: typeof SettingsRoute- }- '/settings/connections': {- id: '/settings/connections'- path: '/connections'- fullPath: '/settings/connections'- preLoaderRoute: typeof SettingsConnectionsRouteImport- parentRoute: typeof SettingsRoute- }- '/settings/archived': {- id: '/settings/archived'- path: '/archived'- fullPath: '/settings/archived'- preLoaderRoute: typeof SettingsArchivedRouteImport- parentRoute: typeof SettingsRoute- }- '/settings/appearance': {- id: '/settings/appearance'- path: '/appearance'- fullPath: '/settings/appearance'- preLoaderRoute: typeof SettingsAppearanceRouteImport- parentRoute: typeof SettingsRoute- }'/projects/$projectKey': {id: '/projects/$projectKey'path: '/projects/$projectKey'@@ -394,11 +235,11 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ConnectCallbackRouteImportparentRoute: typeof rootRouteImport}- '/_chat/pull-requests': {- id: '/_chat/pull-requests'- path: '/pull-requests'- fullPath: '/pull-requests'- preLoaderRoute: typeof ChatPullRequestsRouteImport+ '/_chat/groups/$groupId': {+ id: '/_chat/groups/$groupId'+ path: '/groups/$groupId'+ fullPath: '/groups/$groupId'+ preLoaderRoute: typeof ChatGroupsGroupIdRouteImportparentRoute: typeof ChatRoute}'/_chat/draft/$draftId': {@@ -408,6 +249,13 @@ declare module '@tanstack/react-router' {preLoaderRoute: typeof ChatDraftDraftIdRouteImportparentRoute: typeof ChatRoute}+ '/_chat/bots/$botId': {+ id: '/_chat/bots/$botId'+ path: '/bots/$botId'+ fullPath: '/bots/$botId'+ preLoaderRoute: typeof ChatBotsBotIdRouteImport+ parentRoute: typeof ChatRoute+ }'/_chat/$environmentId/$threadId': {id: '/_chat/$environmentId/$threadId'path: '/$environmentId/$threadId'@@ -419,54 +267,28 @@ declare module '@tanstack/react-router' {}interface ChatRouteChildren {- ChatPullRequestsRoute: typeof ChatPullRequestsRouteChatIndexRoute: typeof ChatIndexRouteChatEnvironmentIdThreadIdRoute: typeof ChatEnvironmentIdThreadIdRoute+ ChatBotsBotIdRoute: typeof ChatBotsBotIdRouteChatDraftDraftIdRoute: typeof ChatDraftDraftIdRoute+ ChatGroupsGroupIdRoute: typeof ChatGroupsGroupIdRoute}const ChatRouteChildren: ChatRouteChildren = {- ChatPullRequestsRoute: ChatPullRequestsRoute,ChatIndexRoute: ChatIndexRoute,ChatEnvironmentIdThreadIdRoute: ChatEnvironmentIdThreadIdRoute,+ ChatBotsBotIdRoute: ChatBotsBotIdRoute,ChatDraftDraftIdRoute: ChatDraftDraftIdRoute,+ ChatGroupsGroupIdRoute: ChatGroupsGroupIdRoute,}const ChatRouteWithChildren = ChatRoute._addFileChildren(ChatRouteChildren)-interface SettingsRouteChildren {- SettingsAppearanceRoute: typeof SettingsAppearanceRoute- SettingsArchivedRoute: typeof SettingsArchivedRoute- SettingsConnectionsRoute: typeof SettingsConnectionsRoute- SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute- SettingsGeneralRoute: typeof SettingsGeneralRoute- SettingsIntegrationsRoute: typeof SettingsIntegrationsRoute- SettingsKeybindingsRoute: typeof SettingsKeybindingsRoute- SettingsProvidersRoute: typeof SettingsProvidersRoute- SettingsSourceControlRoute: typeof SettingsSourceControlRoute-}--const SettingsRouteChildren: SettingsRouteChildren = {- SettingsAppearanceRoute: SettingsAppearanceRoute,- SettingsArchivedRoute: SettingsArchivedRoute,- SettingsConnectionsRoute: SettingsConnectionsRoute,- SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,- SettingsGeneralRoute: SettingsGeneralRoute,- SettingsIntegrationsRoute: SettingsIntegrationsRoute,- SettingsKeybindingsRoute: SettingsKeybindingsRoute,- SettingsProvidersRoute: SettingsProvidersRoute,- SettingsSourceControlRoute: SettingsSourceControlRoute,-}--const SettingsRouteWithChildren = SettingsRoute._addFileChildren(- SettingsRouteChildren,-)-const rootRouteChildren: RootRouteChildren = {ChatRoute: ChatRouteWithChildren,ConnectRoute: ConnectRoute,PairRoute: PairRoute,- SettingsRoute: SettingsRouteWithChildren,+ SettingsRoute: SettingsRoute,UsageRoute: UsageRoute,ConnectCallbackRoute: ConnectCallbackRoute,ProjectsProjectKeyRoute: ProjectsProjectKeyRoute,diff --git a/apps/web/src/routes/RootRouteErrorView.test.tsx b/apps/web/src/routes/RootRouteErrorView.test.tsxnew file mode 100644index 000000000..fd30d5dc0--- /dev/null+++ b/apps/web/src/routes/RootRouteErrorView.test.tsx@@ -0,0 +1,69 @@+import { Children, isValidElement, type ReactElement, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it, vi } from "vite-plus/test";++import { Button } from "../components/ui/button";+import { errorDetails, errorMessage, RootRouteErrorView } from "./RootRouteErrorView";++interface ActionElementProps {+ readonly children?: ReactNode;+ readonly onClick?: () => void;+}++function findButtons(node: ReactNode): ReactElement<ActionElementProps>[] {+ if (!isValidElement<ActionElementProps>(node)) return [];+ const match = node.type === Button ? [node] : [];+ return [...match, ...Children.toArray(node.props.children).flatMap(findButtons)];+}++describe("RootRouteErrorView", () => {+ it("puts recovery guidance before the technical error", () => {+ const markup = renderToStaticMarkup(+ <RootRouteErrorView+ error={new TypeError("bots.filter is not a function")}+ reload={() => {}}+ reset={() => {}}+ />,+ );++ expect(markup).toContain('aria-labelledby="root-error-title"');+ expect(markup).toContain("<h1");+ expect(markup).toContain("This view failed to load");+ expect(markup).toContain("Retry this view. If it fails again, reload Akeru Bot.");+ expect(markup).toContain("bots.filter is not a function");+ expect(markup).toContain("Technical details");+ expect(markup).toContain('tabindex="0"');+ expect(markup).toContain('aria-hidden="true"');+ expect(markup).not.toContain('role="alert"');+ expect(markup).not.toContain("AlertCircle");+ expect(markup).not.toContain("background-size:64px");+ expect(markup.indexOf("Retry this view")).toBeLessThan(markup.indexOf("Technical details"));+ });++ it("offers retry and full reload as separate recovery actions", () => {+ const reset = vi.fn();+ const reload = vi.fn();+ const view = RootRouteErrorView({ error: new Error("Failed to load"), reload, reset });+ const [retryButton, reloadButton] = findButtons(view);++ expect(Children.toArray(retryButton?.props.children)).toContain("Retry");+ expect(Children.toArray(reloadButton?.props.children)).toContain("Reload app");++ retryButton?.props.onClick?.();+ reloadButton?.props.onClick?.();++ expect(reset).toHaveBeenCalledOnce();+ expect(reload).toHaveBeenCalledOnce();+ });++ it("provides useful fallbacks for unknown and unserializable errors", () => {+ const circular: { self?: unknown } = {};+ circular.self = circular;++ expect(errorMessage(new Error("boom"))).toBe("boom");+ expect(errorMessage("failed to connect")).toBe("failed to connect");+ expect(errorMessage(" ")).toBe("An unexpected error stopped this view from loading.");+ expect(errorDetails("failed to connect")).toBe("failed to connect");+ expect(errorDetails(circular)).toBe("No additional error details are available.");+ });+});diff --git a/apps/web/src/routes/RootRouteErrorView.tsx b/apps/web/src/routes/RootRouteErrorView.tsxnew file mode 100644index 000000000..306233bdc--- /dev/null+++ b/apps/web/src/routes/RootRouteErrorView.tsx@@ -0,0 +1,91 @@+import type { ErrorComponentProps } from "@tanstack/react-router";++import { APP_DISPLAY_NAME } from "../branding";+import { AkeruMark } from "../components/AkeruMark";+import { Button } from "../components/ui/button";++function reloadApp() {+ window.location.reload();+}++interface RootRouteErrorViewProps extends ErrorComponentProps {+ readonly reload?: () => void;+}++export function RootRouteErrorView({ error, reset, reload = reloadApp }: RootRouteErrorViewProps) {+ const details = errorDetails(error);++ return (+ <main+ aria-labelledby="root-error-title"+ className="flex h-full min-h-0 flex-col bg-background text-foreground"+ >+ <header className="flex h-[var(--workspace-topbar-height)] shrink-0 items-center gap-1.5 pl-[var(--workspace-controls-left)] pr-[var(--workspace-controls-right)]">+ <AkeruMark aria-hidden className="text-foreground" />+ <span className="truncate text-sm font-medium tracking-tight text-muted-foreground">+ {APP_DISPLAY_NAME}+ </span>+ </header>++ <section className="flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 py-12">+ <div className="flex w-full max-w-md flex-col items-center text-center">+ <h1 className="text-xl font-medium tracking-tight" id="root-error-title">+ This view failed to load+ </h1>+ <p className="mt-2 text-sm leading-6 text-muted-foreground">+ Retry this view. If it fails again, reload Akeru Bot.+ </p>++ <div className="mt-5 flex flex-wrap justify-center gap-2">+ <Button onClick={() => reset()} size="sm">+ Retry+ </Button>+ <Button onClick={reload} size="sm" variant="outline">+ Reload app+ </Button>+ </div>++ <details className="group mt-5 w-full text-left">+ <summary className="flex cursor-pointer list-none items-center justify-center rounded-[var(--control-radius)] px-2 py-1.5 text-xs font-medium text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1 focus-visible:ring-offset-background [&::-webkit-details-marker]:hidden">+ Technical details+ </summary>+ <pre+ className="mt-2 max-h-52 overflow-auto rounded-lg border border-border bg-card px-3 py-2.5 font-mono text-xs leading-5 whitespace-pre-wrap text-muted-foreground"+ tabIndex={0}+ >+ {details}+ </pre>+ </details>+ </div>+ </section>+ </main>+ );+}++export function errorMessage(error: unknown): string {+ if (error instanceof Error && error.message.trim().length > 0) {+ return error.message;+ }++ if (typeof error === "string" && error.trim().length > 0) {+ return error;+ }++ return "An unexpected error stopped this view from loading.";+}++export function errorDetails(error: unknown): string {+ if (error instanceof Error) {+ return error.stack ?? error.message;+ }++ if (typeof error === "string") {+ return error;+ }++ try {+ return JSON.stringify(error, null, 2);+ } catch {+ return "No additional error details are available.";+ }+}diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex 7c715dff9..c2d14d3ba 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -1,13 +1,7 @@import { type ServerLifecycleWelcomePayload } from "@t3tools/contracts";import { scopedProjectKey, scopeProjectRef } from "@t3tools/client-runtime/environment";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";-import {- Outlet,- createRootRoute,- type ErrorComponentProps,- useLocation,- useNavigate,-} from "@tanstack/react-router";+import { Outlet, createRootRoute, useLocation, useNavigate } from "@tanstack/react-router";import { useEffect, useEffectEvent, useRef, useState } from "react";import { APP_BASE_NAME, APP_DISPLAY_NAME, APP_STAGE_LABEL } from "../branding";@@ -21,7 +15,10 @@ import { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptimport { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";import { SlowRpcRequestToastCoordinator } from "../components/SlowRpcRequestToastCoordinator";import { ThemeEditorHost } from "../components/settings/ThemeEditorHost";-import { Button } from "../components/ui/button";+import { SettingsDialog } from "../components/settings/SettingsDialog";+import { PluginsDialog } from "../components/plugins/PluginsDialog";+import { UsageDialog } from "../components/usage/UsageDialog";+import { RootRouteErrorView } from "./RootRouteErrorView";import {AnchoredToastProvider,stackedThreadToast,@@ -146,6 +143,9 @@ function RootRouteView() {{primaryEnvironmentAuthenticated ? <PlanAgentSelectionHeal /> : null}{primaryEnvironmentAuthenticated ? <ProviderUpdateLaunchNotification /> : null}{appShell}+ <SettingsDialog />+ <PluginsDialog />+ <UsageDialog />{/* Above the router: a theme draft is judged by walking the app, so theeditor has to survive navigation away from settings. */}<ThemeEditorHost />@@ -251,77 +251,6 @@ function HostedStaticEnvironmentBootstrap() {return null;}-function RootRouteErrorView({ error, reset }: ErrorComponentProps) {- const message = errorMessage(error);- const details = errorDetails(error);-- return (- <div className="relative flex min-h-screen items-center justify-center overflow-hidden bg-background px-4 py-10 text-foreground sm:px-6">- <div className="pointer-events-none absolute inset-0 opacity-80">- <div className="absolute inset-x-0 top-0 h-44 bg-[radial-gradient(44rem_16rem_at_top,color-mix(in_srgb,var(--color-red-500)_16%,transparent),transparent)]" />- <div className="absolute inset-0 bg-[linear-gradient(145deg,color-mix(in_srgb,var(--background)_90%,var(--color-black))_0%,var(--background)_55%)]" />- </div>-- <section className="relative w-full max-w-xl rounded-2xl border border-border/80 bg-card/90 p-6 shadow-2xl shadow-black/20 backdrop-blur-md sm:p-8">- <p className="text-[11px] font-semibold tracking-[0.18em] text-muted-foreground uppercase">- {APP_DISPLAY_NAME}- </p>- <h1 className="mt-3 text-2xl font-semibold tracking-tight sm:text-3xl">- Something went wrong.- </h1>- <p className="mt-2 text-sm leading-relaxed text-muted-foreground">{message}</p>-- <div className="mt-5 flex flex-wrap gap-2">- <Button size="sm" onClick={() => reset()}>- Try again- </Button>- <Button size="sm" variant="outline" onClick={() => window.location.reload()}>- Reload app- </Button>- </div>-- <details className="group mt-5 overflow-hidden rounded-lg border border-border/70 bg-background/55">- <summary className="cursor-pointer list-none px-3 py-2 text-xs font-medium text-muted-foreground">- <span className="group-open:hidden">Show error details</span>- <span className="hidden group-open:inline">Hide error details</span>- </summary>- <pre className="max-h-56 overflow-auto border-t border-border/70 bg-background/80 px-3 py-2 text-xs text-foreground/85">- {details}- </pre>- </details>- </section>- </div>- );-}--function errorMessage(error: unknown): string {- if (error instanceof Error && error.message.trim().length > 0) {- return error.message;- }-- if (typeof error === "string" && error.trim().length > 0) {- return error;- }-- return "An unexpected router error occurred.";-}--function errorDetails(error: unknown): string {- if (error instanceof Error) {- return error.stack ?? error.message;- }-- if (typeof error === "string") {- return error;- }-- try {- return JSON.stringify(error, null, 2);- } catch {- return "No additional error details are available.";- }-}-function AuthenticatedTracingBootstrap() {useEffect(() => {void configureClientTracing();diff --git a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx b/apps/web/src/routes/_chat.$environmentId.$threadId.tsxindex 5ac4665cf..926031245 100644--- a/apps/web/src/routes/_chat.$environmentId.$threadId.tsx+++ b/apps/web/src/routes/_chat.$environmentId.$threadId.tsx@@ -1,97 +1,16 @@import { createFileRoute, useNavigate } from "@tanstack/react-router";import { useEffect } from "react";-import ChatView from "../components/ChatView";-import { threadHasStarted } from "../components/ChatView.logic";-import { finalizePromotedDraftThreadByRef, useComposerDraftStore } from "../composerDraftStore";-import { resolveThreadRouteRef, resolveThreadRouteRenderState } from "../threadRoutes";-import { resolveThreadSyncPhase } from "../threadSync";-import { SidebarInset } from "~/components/ui/sidebar";-import {- useEnvironmentThreadRefs,- useThreadDetail,- useThreadShell,- useThreadStatus,-} from "../state/entities";-import { useEnvironmentQuery } from "../state/query";-import { environmentShell } from "../state/shell";--function ChatThreadRouteView() {+function RemovedThreadRoute() {const navigate = useNavigate();- const threadRef = Route.useParams({- select: (params) => resolveThreadRouteRef(params),- });- const shell = useEnvironmentQuery(- threadRef === null ? null : environmentShell.stateAtom(threadRef.environmentId),- );- const serverThreadShell = useThreadShell(threadRef);- const serverThreadDetail = useThreadDetail(threadRef);- const serverThreadStatus = useThreadStatus(threadRef);- const environmentThreadRefs = useEnvironmentThreadRefs(threadRef?.environmentId ?? null);- const bootstrapComplete = shell.data?.snapshot._tag === "Some";- const environmentHasServerThreads = environmentThreadRefs.length > 0;- const draftThreadExists = useComposerDraftStore((store) =>- threadRef ? store.getDraftThreadByRef(threadRef) !== null : false,- );- const draftThread = useComposerDraftStore((store) =>- threadRef ? store.getDraftThreadByRef(threadRef) : null,- );- const environmentHasDraftThreads = useComposerDraftStore((store) => {- if (!threadRef) {- return false;- }- return store.hasDraftThreadsInEnvironment(threadRef.environmentId);- });- const renderState = resolveThreadRouteRenderState({- bootstrapComplete,- serverThreadShellExists: serverThreadShell !== null,- serverThreadDetailExists: serverThreadDetail !== null,- serverThreadDetailDeleted: serverThreadStatus === "deleted",- draftThreadExists,- });- const threadSyncPhase = resolveThreadSyncPhase({- detailExists: serverThreadDetail !== null,- shellExists: serverThreadShell !== null,- status: serverThreadStatus,- });- const serverThreadStarted = threadHasStarted(serverThreadDetail);- const environmentHasAnyThreads = environmentHasServerThreads || environmentHasDraftThreads;useEffect(() => {- if (!threadRef || !bootstrapComplete) {- return;- }-- if (renderState === "missing" && environmentHasAnyThreads) {- void navigate({ to: "/", replace: true });- }- }, [bootstrapComplete, environmentHasAnyThreads, navigate, renderState, threadRef]);-- useEffect(() => {- if (!threadRef || !serverThreadStarted || !draftThread) {- return;- }- finalizePromotedDraftThreadByRef(threadRef);- }, [draftThread, serverThreadStarted, threadRef]);-- if (!threadRef) {- return null;- }+ void navigate({ to: "/", replace: true });+ }, [navigate]);- return (- <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground md:h-dvh">- {renderState === "ready" || (renderState === "loading" && serverThreadShell !== null) ? (- <ChatView- environmentId={threadRef.environmentId}- threadId={threadRef.threadId}- routeKind="server"- threadSyncPhase={threadSyncPhase}- />- ) : null}- </SidebarInset>- );+ return null;}export const Route = createFileRoute("/_chat/$environmentId/$threadId")({- component: ChatThreadRouteView,+ component: RemovedThreadRoute,});diff --git a/apps/web/src/routes/_chat.bots.$botId.tsx b/apps/web/src/routes/_chat.bots.$botId.tsxnew file mode 100644index 000000000..528046ebe--- /dev/null+++ b/apps/web/src/routes/_chat.bots.$botId.tsx@@ -0,0 +1,63 @@+import { BotId } from "@t3tools/contracts";+import { createFileRoute } from "@tanstack/react-router";++import { BotThreadLanding } from "../components/roster/BotThreadLanding";+import { BotDetailsPanel } from "../components/roster/BotDetailsPanel";+import { useRosterStore } from "../components/roster/rosterStore";+import { toastManager } from "../components/ui/toast";+import { botEnvironment } from "../state/bots";+import { usePrimaryEnvironmentId } from "../state/environments";+import { useAtomCommand } from "../state/use-atom-command";++function BotThreadRouteView() {+ const { botId } = Route.useParams();+ const environmentId = usePrimaryEnvironmentId();+ const updateBot = useAtomCommand(botEnvironment.update, { reportFailure: false });+ const bot = useRosterStore((state) =>+ state.bots.find((candidate) => candidate.id === botId && candidate.archivedAt === null),+ );++ return (+ <>+ <BotThreadLanding botId={botId} />+ {bot ? (+ <BotDetailsPanel+ key={bot.id}+ bot={bot}+ onSaveBot={async ({+ name,+ label,+ description,+ engine,+ sandbox,+ disabledMcpServerIds,+ }) => {+ if (!environmentId) return false;+ const result = await updateBot({+ environmentId,+ input: {+ botId: BotId.make(bot.id),+ name,+ label,+ description,+ engine,+ sandbox,+ disabledMcpServerIds,+ },+ });+ if (result._tag === "Failure") {+ toastManager.add({ type: "error", title: "Could not save bot settings" });+ return false;+ }+ toastManager.add({ type: "success", title: "Bot settings saved" });+ return true;+ }}+ />+ ) : null}+ </>+ );+}++export const Route = createFileRoute("/_chat/bots/$botId")({+ component: BotThreadRouteView,+});diff --git a/apps/web/src/routes/_chat.draft.$draftId.tsx b/apps/web/src/routes/_chat.draft.$draftId.tsxindex d067c6a8d..1aa222918 100644--- a/apps/web/src/routes/_chat.draft.$draftId.tsx+++ b/apps/web/src/routes/_chat.draft.$draftId.tsx@@ -1,97 +1,16 @@import { createFileRoute, useNavigate } from "@tanstack/react-router";import { useEffect } from "react";-import ChatView from "../components/ChatView";-import {- resolveDraftPromotionNavigationTarget,- threadHasStarted,-} from "../components/ChatView.logic";-import {- DraftId,- markPromotedDraftThreadByRef,- useBackgroundDraftSubmissionPending,- useComposerDraftStore,-} from "../composerDraftStore";-import { SidebarInset } from "../components/ui/sidebar";-import { waitForDraftHeroTransition } from "../components/chat/draftHeroTransition";-import { buildThreadRouteParams } from "../threadRoutes";-import { useThread, useThreadRefs } from "../state/entities";-function DraftChatThreadRouteView() {+function RemovedDraftRoute() {const navigate = useNavigate();- const { draftId: rawDraftId } = Route.useParams();- const draftId = DraftId.make(rawDraftId);- const draftSession = useComposerDraftStore((store) => store.getDraftSession(draftId));- const threadRefs = useThreadRefs();- const inferredThreadRef = draftSession- ? (threadRefs.find(- (ref) =>- ref.environmentId === draftSession.environmentId &&- ref.threadId === draftSession.threadId,- ) ?? null)- : null;- const serverThreadRef = draftSession?.promotedTo ?? inferredThreadRef;- const serverThread = useThread(serverThreadRef);- const serverThreadStarted = threadHasStarted(serverThread);- const backgroundSubmissionPending = useBackgroundDraftSubmissionPending(serverThreadRef);- const canonicalThreadRef = resolveDraftPromotionNavigationTarget({- serverThreadRef,- serverThreadStarted,- backgroundSubmissionPending,- });useEffect(() => {- if (!inferredThreadRef || draftSession?.promotedTo) {- return;- }- markPromotedDraftThreadByRef(inferredThreadRef);- }, [draftSession?.promotedTo, inferredThreadRef]);-- useEffect(() => {- if (!canonicalThreadRef) {- return;- }-- let cancelled = false;- void waitForDraftHeroTransition().then(() => {- if (cancelled) {- return;- }- void navigate({- to: "/$environmentId/$threadId",- params: buildThreadRouteParams(canonicalThreadRef),- replace: true,- });- });-- return () => {- cancelled = true;- };- }, [canonicalThreadRef, navigate]);-- useEffect(() => {- if (draftSession || canonicalThreadRef) {- return;- }void navigate({ to: "/", replace: true });- }, [canonicalThreadRef, draftSession, navigate]);-- if (!draftSession) {- return null;- }+ }, [navigate]);- return (- <SidebarInset className="h-svh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground md:h-dvh">- <ChatView- draftId={draftId}- environmentId={draftSession.environmentId}- threadId={draftSession.threadId}- routeKind="draft"- forceExpandedMobileComposer- />- </SidebarInset>- );+ return null;}export const Route = createFileRoute("/_chat/draft/$draftId")({- component: DraftChatThreadRouteView,+ component: RemovedDraftRoute,});diff --git a/apps/web/src/routes/_chat.groups.$groupId.tsx b/apps/web/src/routes/_chat.groups.$groupId.tsxnew file mode 100644index 000000000..9a65a2ebc--- /dev/null+++ b/apps/web/src/routes/_chat.groups.$groupId.tsx@@ -0,0 +1,12 @@+import { createFileRoute } from "@tanstack/react-router";++import { GroupThreadLanding } from "../components/roster/GroupThreadLanding";++function GroupThreadRouteView() {+ const { groupId } = Route.useParams();+ return <GroupThreadLanding groupId={groupId} />;+}++export const Route = createFileRoute("/_chat/groups/$groupId")({+ component: GroupThreadRouteView,+});diff --git a/apps/web/src/routes/_chat.index.tsx b/apps/web/src/routes/_chat.index.tsxindex ba96e8986..557f3fe4c 100644--- a/apps/web/src/routes/_chat.index.tsx+++ b/apps/web/src/routes/_chat.index.tsx@@ -1,23 +1,17 @@-import { scopeProjectRef } from "@t3tools/client-runtime/environment";-import { createFileRoute, Link } from "@tanstack/react-router";-import { LinkIcon, PlusIcon, RotateCcwIcon } from "lucide-react";-import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { createFileRoute, useNavigate } from "@tanstack/react-router";+import { LinkIcon, PlusIcon } from "lucide-react";+import { useEffect } from "react";-import { openCommandPalette } from "../commandPaletteBus";-import { sortScopedProjectsForSidebar } from "../components/Sidebar.logic";+import { APP_DISPLAY_NAME } from "~/branding";+import { hasCloudPublicConfig } from "~/cloud/publicConfig";+import { resolveRosterBotId } from "../components/roster/roster.logic";+import { useRosterStore } from "../components/roster/rosterStore";import { Button } from "../components/ui/button";import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../components/ui/empty";import { SidebarInset } from "../components/ui/sidebar";import { WorkspacePageHeader } from "../components/WorkspacePageHeader";-import { useNewThreadHandler } from "../hooks/useHandleNewThread";-import {- useAllEnvironmentShellsBootstrapped,- useProjects,- useThreadShells,-} from "../state/entities";+import { openSettings } from "../settingsDialogStore";import { useEnvironments } from "../state/environments";-import { APP_DISPLAY_NAME } from "~/branding";-import { hasCloudPublicConfig } from "~/cloud/publicConfig";function ChatIndexRouteView() {const { authGateState } = Route.useRouteContext();@@ -27,111 +21,31 @@ function ChatIndexRouteView() {return <HostedStaticOnboardingState />;}- return <IndexDraftLanding />;+ return <BotIndexRedirect />;}-/**- * Landing on the index route drops straight into a draft thread for the most- * recently active project, so the first screen is a prompt instead of a dead- * end. Falls back to an add-project hero when no project exists yet.- */-function IndexDraftLanding() {- const projects = useProjects();- const threads = useThreadShells();- const bootstrapped = useAllEnvironmentShellsBootstrapped();- const handleNewThread = useNewThreadHandler();- const startingRef = useRef(false);- const [startState, setStartState] = useState({ failed: false, retryRequest: 0 });-- const mostRecentProject = useMemo(- () =>- bootstrapped- ? (sortScopedProjectsForSidebar(projects, threads, "updated_at")[0] ?? null)- : null,- [bootstrapped, projects, threads],- );+function BotIndexRedirect() {+ const navigate = useNavigate();+ const botId = useRosterStore((state) => resolveRosterBotId(state.selectedBotId, state.bots));useEffect(() => {- if (mostRecentProject === null || startingRef.current) {- return;- }- startingRef.current = true;- void handleNewThread(scopeProjectRef(mostRecentProject.environmentId, mostRecentProject.id), {- replace: true,- }).catch(() => {- startingRef.current = false;- setStartState((state) => ({ ...state, failed: true }));- });- }, [handleNewThread, mostRecentProject, startState.retryRequest]);+ if (botId === null) return;+ void navigate({ to: "/bots/$botId", params: { botId }, replace: true });+ }, [botId, navigate]);- if (!bootstrapped) {- return null;- }- if (mostRecentProject !== null) {- return startState.failed ? (- <DraftStartError- onRetry={() => {- setStartState((state) => ({- failed: false,- retryRequest: state.retryRequest + 1,- }));- }}- />- ) : null;- }- return <NoProjectsHero />;-}+ if (botId !== null) return null;-function DraftStartError({ onRetry }: { readonly onRetry: () => void }) {return (- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">+ <SidebarInset className="h-dvh min-h-0 overflow-hidden bg-background text-foreground"><Empty className="flex-1">- <EmptyHeader className="max-w-md">- <EmptyTitle className="text-foreground text-xl">Couldn’t start a new thread</EmptyTitle>- <EmptyDescription className="mt-2 text-sm text-muted-foreground/78">- The project is still available. Try opening the draft again.- </EmptyDescription>- <div className="mt-5 flex justify-center">- <Button size="sm" onClick={onRetry}>- <RotateCcwIcon className="size-4" />- Try again- </Button>- </div>+ <EmptyHeader>+ <EmptyTitle>Create a bot to start chatting</EmptyTitle></EmptyHeader></Empty></SidebarInset>);}-function NoProjectsHero() {- const openAddProject = useCallback(() => openCommandPalette({ open: "add-project" }), []);-- return (- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground">- <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">- <Empty className="flex-1">- <div className="w-full max-w-lg px-8 py-12">- <EmptyHeader className="max-w-none">- <EmptyTitle className="text-foreground text-2xl sm:text-3xl">- What should we work on?- </EmptyTitle>- <EmptyDescription className="mt-2 text-sm text-muted-foreground/78">- Add a project to start your first thread.- </EmptyDescription>- <div className="mt-6 flex justify-center">- <Button size="sm" onClick={openAddProject}>- <PlusIcon className="size-4" />- Add project- </Button>- </div>- </EmptyHeader>- </div>- </Empty>- </div>- </SidebarInset>- );-}-export const Route = createFileRoute("/_chat/")({component: ChatIndexRouteView,});@@ -161,11 +75,11 @@ function HostedStaticOnboardingState() {</EmptyTitle><EmptyDescription className="mt-2 text-sm leading-relaxed text-muted-foreground/78">{cloudEnabled- ? "Sign in to T3 Connect to connect a linked environment through its managed tunnel, or add a reachable backend manually."+ ? "Sign in to connect a linked environment through its managed tunnel, or add a reachable backend manually.": "Add a reachable backend manually to start working from this browser."}</EmptyDescription><div className="mt-6 flex justify-center">- <Button render={<Link to="/settings/connections" />} size="sm">+ <Button size="sm" onClick={() => openSettings("connections")}><PlusIcon className="size-4" />{cloudEnabled ? "Open Connections" : "Add environment"}</Button>diff --git a/apps/web/src/routes/_chat.tsx b/apps/web/src/routes/_chat.tsxindex e084e22c2..aa959ff00 100644--- a/apps/web/src/routes/_chat.tsx+++ b/apps/web/src/routes/_chat.tsx@@ -1,186 +1,7 @@import { Outlet, createFileRoute, redirect } from "@tanstack/react-router";-import { useAtomValue } from "@effect/atom-react";-import { useEffect, useMemo } from "react";--import { isCommandPaletteOpen } from "../commandPaletteBus";-import { useClientSettings, useLegacySidebarEnabled } from "../hooks/useSettings";-import { openCommandPalette } from "../commandPaletteBus";-import { useProjects } from "../state/entities";-import { usePrimaryEnvironmentId } from "../state/environments";-import { selectProjectGroupingSettings } from "../logicalProject";-import { buildSidebarProjectSnapshots } from "../sidebarProjectGrouping";-import { dispatchPreviewAction } from "../components/preview/previewActionBus";-import { useHandleNewThread } from "../hooks/useHandleNewThread";-import { startNewThreadFromContext } from "../lib/chatThreadActions";-import { isPreviewFocused } from "../lib/previewFocus";-import { isTerminalFocused } from "../lib/terminalFocus";-import { resolveShortcutCommand } from "../keybindings";-import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";-import { isPreviewSupportedInRuntime } from "../previewStateStore";-import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore";-import { useThreadSelectionStore } from "../threadSelectionStore";-import { stackedThreadToast, toastManager } from "~/components/ui/toast";-import { primaryServerKeybindingsAtom } from "~/state/server";--function ChatRouteGlobalShortcuts() {- const clearSelection = useThreadSelectionStore((state) => state.clearSelection);- const selectedThreadKeysSize = useThreadSelectionStore((state) => state.selectedThreadKeys.size);- const { activeDraftThread, activeThread, defaultProjectRef, handleNewThread, routeThreadRef } =- useHandleNewThread();- const keybindings = useAtomValue(primaryServerKeybindingsAtom);- const legacySidebarEnabled = useLegacySidebarEnabled();- const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);- const projects = useProjects();- const primaryEnvironmentId = usePrimaryEnvironmentId();- const projectGroupCount = useMemo(- () =>- buildSidebarProjectSnapshots({- projects,- settings: projectGroupingSettings,- primaryEnvironmentId,- resolveEnvironmentLabel: () => null,- }).length,- [primaryEnvironmentId, projectGroupingSettings, projects],- );- const terminalOpen = useTerminalUiStateStore((state) =>- routeThreadRef- ? selectThreadTerminalUiState(state.terminalUiStateByThreadKey, routeThreadRef).terminalOpen- : false,- );- // The `previewOpen` shortcut-context flag here uses the store-only value;- // the URL-aware arbitration lives inside ChatView's `onTogglePreview`,- // which we invoke via the action bus to avoid duplicating the rule.- const previewOpen = useRightPanelStore((state) =>- routeThreadRef- ? selectActiveRightPanel(state.byThreadKey, routeThreadRef) === "preview"- : false,- );- useEffect(() => {- const onWindowKeyDown = (event: KeyboardEvent) => {- if (event.defaultPrevented) return;- const command = resolveShortcutCommand(event, keybindings, {- context: {- terminalFocus: isTerminalFocused(),- terminalOpen,- previewFocus: isPreviewFocused(),- previewOpen,- },- });-- if (isCommandPaletteOpen()) {- return;- }-- if (event.key === "Escape" && selectedThreadKeysSize > 0) {- event.preventDefault();- clearSelection();- return;- }-- if (command === "chat.newLocal") {- event.preventDefault();- event.stopPropagation();- void startNewThreadFromContext({- activeDraftThread,- activeThread: activeThread ?? undefined,- defaultProjectRef,- handleNewThread,- });- return;- }-- if (command === "chat.new") {- event.preventDefault();- event.stopPropagation();- // The default sidebar routes creation through the command palette- // whenever there is a real choice to make; the legacy sidebar (and- // single-project setups) keep the immediate contextual create.- if (!legacySidebarEnabled && projectGroupCount > 1) {- openCommandPalette({ open: "new-thread-in" });- return;- }- void startNewThreadFromContext({- activeDraftThread,- activeThread: activeThread ?? undefined,- defaultProjectRef,- handleNewThread,- });- return;- }-- if (command === "preview.toggle") {- event.preventDefault();- event.stopPropagation();- if (!routeThreadRef) return;- if (!isPreviewSupportedInRuntime()) {- toastManager.add(- stackedThreadToast({- type: "info",- title: "Preview is desktop-only",- description: "Open T3 Code in the desktop app to use the in-app preview.",- }),- );- return;- }- dispatchPreviewAction("toggle-panel");- return;- }-- // The remaining preview commands only fire when the panel is the- // currently-focused tenant. The `when: previewFocus` rule already- // gates this, but defend against the keybinding being misconfigured.- if (- command === "preview.refresh" ||- command === "preview.focusUrl" ||- command === "preview.zoomIn" ||- command === "preview.zoomOut" ||- command === "preview.resetZoom"- ) {- event.preventDefault();- event.stopPropagation();- const action =- command === "preview.refresh"- ? "refresh"- : command === "preview.focusUrl"- ? "focus-url"- : command === "preview.zoomIn"- ? "zoom-in"- : command === "preview.zoomOut"- ? "zoom-out"- : "reset-zoom";- dispatchPreviewAction(action);- }- };-- window.addEventListener("keydown", onWindowKeyDown);- return () => {- window.removeEventListener("keydown", onWindowKeyDown);- };- }, [- activeDraftThread,- activeThread,- clearSelection,- handleNewThread,- keybindings,- defaultProjectRef,- previewOpen,- projectGroupCount,- routeThreadRef,- selectedThreadKeysSize,- legacySidebarEnabled,- terminalOpen,- ]);-- return null;-}function ChatRouteLayout() {- return (- <>- <ChatRouteGlobalShortcuts />- <Outlet />- </>- );+ return <Outlet />;}export const Route = createFileRoute("/_chat")({diff --git a/apps/web/src/routes/settings.appearance.tsx b/apps/web/src/routes/settings.appearance.tsxdeleted file mode 100644index 60c33fff3..000000000--- a/apps/web/src/routes/settings.appearance.tsx+++ /dev/null@@ -1,11 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";--import { AppearanceSettingsPanel } from "../components/settings/SettingsPanels";--function SettingsAppearanceRoute() {- return <AppearanceSettingsPanel />;-}--export const Route = createFileRoute("/settings/appearance")({- component: SettingsAppearanceRoute,-});diff --git a/apps/web/src/routes/settings.archived.tsx b/apps/web/src/routes/settings.archived.tsxdeleted file mode 100644index 3ad690afc..000000000--- a/apps/web/src/routes/settings.archived.tsx+++ /dev/null@@ -1,7 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";--import { ArchivedThreadsPanel } from "../components/settings/SettingsPanels";--export const Route = createFileRoute("/settings/archived")({- component: ArchivedThreadsPanel,-});diff --git a/apps/web/src/routes/settings.connections.tsx b/apps/web/src/routes/settings.connections.tsxdeleted file mode 100644index 275eda6c5..000000000--- a/apps/web/src/routes/settings.connections.tsx+++ /dev/null@@ -1,7 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";--import { ConnectionsSettings } from "../components/settings/ConnectionsSettings";--export const Route = createFileRoute("/settings/connections")({- component: ConnectionsSettings,-});diff --git a/apps/web/src/routes/settings.diagnostics.tsx b/apps/web/src/routes/settings.diagnostics.tsxdeleted file mode 100644index e86e5c5cb..000000000--- a/apps/web/src/routes/settings.diagnostics.tsx+++ /dev/null@@ -1,7 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";--import { DiagnosticsSettingsPanel } from "../components/settings/DiagnosticsSettings";--export const Route = createFileRoute("/settings/diagnostics")({- component: DiagnosticsSettingsPanel,-});diff --git a/apps/web/src/routes/settings.general.tsx b/apps/web/src/routes/settings.general.tsxdeleted file mode 100644index c907a4915..000000000--- a/apps/web/src/routes/settings.general.tsx+++ /dev/null@@ -1,11 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";--import { GeneralSettingsPanel } from "../components/settings/SettingsPanels";--function SettingsGeneralRoute() {- return <GeneralSettingsPanel />;-}--export const Route = createFileRoute("/settings/general")({- component: SettingsGeneralRoute,-});diff --git a/apps/web/src/routes/settings.integrations.tsx b/apps/web/src/routes/settings.integrations.tsxdeleted file mode 100644index 3fa49ae93..000000000--- a/apps/web/src/routes/settings.integrations.tsx+++ /dev/null@@ -1,11 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";--import { IntegrationsSettingsPanel } from "../components/settings/IntegrationsSettings";--function SettingsIntegrationsRoute() {- return <IntegrationsSettingsPanel />;-}--export const Route = createFileRoute("/settings/integrations")({- component: SettingsIntegrationsRoute,-});diff --git a/apps/web/src/routes/settings.keybindings.tsx b/apps/web/src/routes/settings.keybindings.tsxdeleted file mode 100644index f44784078..000000000--- a/apps/web/src/routes/settings.keybindings.tsx+++ /dev/null@@ -1,7 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";--import { KeybindingsSettingsPanel } from "../components/settings/KeybindingsSettings";--export const Route = createFileRoute("/settings/keybindings")({- component: KeybindingsSettingsPanel,-});diff --git a/apps/web/src/routes/settings.providers.tsx b/apps/web/src/routes/settings.providers.tsxdeleted file mode 100644index deab01472..000000000--- a/apps/web/src/routes/settings.providers.tsx+++ /dev/null@@ -1,11 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";--import { ProviderSettingsPanel } from "../components/settings/ProviderSettingsPanel";--function SettingsProvidersRoute() {- return <ProviderSettingsPanel />;-}--export const Route = createFileRoute("/settings/providers")({- component: SettingsProvidersRoute,-});diff --git a/apps/web/src/routes/settings.source-control.tsx b/apps/web/src/routes/settings.source-control.tsxdeleted file mode 100644index bb09b3fd3..000000000--- a/apps/web/src/routes/settings.source-control.tsx+++ /dev/null@@ -1,7 +0,0 @@-import { createFileRoute } from "@tanstack/react-router";--import { SourceControlSettingsPanel } from "../components/settings/SourceControlSettings";--export const Route = createFileRoute("/settings/source-control")({- component: SourceControlSettingsPanel,-});diff --git a/apps/web/src/routes/settings.tsx b/apps/web/src/routes/settings.tsxindex 5e921fca5..d122ebf59 100644--- a/apps/web/src/routes/settings.tsx+++ b/apps/web/src/routes/settings.tsx@@ -1,99 +1,13 @@-import { RotateCcwIcon } from "lucide-react";-import {- Outlet,- createFileRoute,- redirect,- useCanGoBack,- useLocation,- useNavigate,-} from "@tanstack/react-router";-import { useCallback, useEffect, useState } from "react";+import { createFileRoute, redirect } from "@tanstack/react-router";-import { useSettingsRestore } from "../components/settings/SettingsPanels";-import { SettingsBreadcrumb } from "../components/settings/SettingsBreadcrumb";-import { Button } from "../components/ui/button";-import { SidebarInset } from "../components/ui/sidebar";-import { WorkspacePageHeader } from "../components/WorkspacePageHeader";-import { isElectron } from "../env";--function RestoreDefaultsButton({ onRestored }: { onRestored: () => void }) {- const { changedSettingLabels, restoreDefaults } = useSettingsRestore(onRestored);-- return (- <Button- size="xs"- variant="ghost"- disabled={changedSettingLabels.length === 0}- onClick={() => void restoreDefaults()}- >- <RotateCcwIcon className="mx-1 size-3.5" />- Restore defaults- </Button>- );-}--function SettingsContentLayout() {- const location = useLocation();- const navigate = useNavigate();- const canGoBack = useCanGoBack();- const [restoreSignal, setRestoreSignal] = useState(0);- const showRestoreDefaults = location.pathname === "/settings/general";- const handleRestored = () => setRestoreSignal((value) => value + 1);- const navigateBackWithinApp = useCallback(() => {- if (canGoBack) {- window.history.back();- return;- }- void navigate({ to: "/" });- }, [canGoBack, navigate]);-- useEffect(() => {- const onKeyDown = (event: KeyboardEvent) => {- if (event.defaultPrevented) return;- if (event.key === "Escape") {- event.preventDefault();-- const activeElement = document.activeElement;- if (activeElement instanceof HTMLElement) {- activeElement.blur();- }-- navigateBackWithinApp();- }- };-- window.addEventListener("keydown", onKeyDown);- return () => {- window.removeEventListener("keydown", onKeyDown);- };- }, [navigateBackWithinApp]);-- return (- <SidebarInset className="h-dvh min-h-0 overflow-hidden overscroll-y-none bg-background text-foreground isolate">- <div className="flex min-h-0 min-w-0 flex-1 flex-col bg-background text-foreground">- <WorkspacePageHeader electron={isElectron}>- <div className="flex w-full items-center gap-3">- <SettingsBreadcrumb pathname={location.pathname} />- {showRestoreDefaults ? (- <div className="ms-auto flex items-center gap-2">- <RestoreDefaultsButton onRestored={handleRestored} />- </div>- ) : null}- </div>- </WorkspacePageHeader>-- <div key={restoreSignal} className="min-h-0 flex flex-1 flex-col">- <Outlet />- </div>- </div>- </SidebarInset>- );-}--function SettingsRouteLayout() {- return <SettingsContentLayout />;-}+import { isLegacyPluginsPath, openPlugins } from "../pluginsDialogStore";+import { openSettings, settingsSectionFromPathname } from "../settingsDialogStore";+/**+ * Settings is a modal now. The route only survives so old deep links and+ * history entries still land somewhere useful: it opens the dialog and hands+ * the user back to the workspace.+ */export const Route = createFileRoute("/settings")({beforeLoad: async ({ context, location }) => {if (@@ -103,9 +17,11 @@ export const Route = createFileRoute("/settings")({throw redirect({ to: "/pair", replace: true });}- if (location.pathname === "/settings") {- throw redirect({ to: "/settings/general", replace: true });+ if (isLegacyPluginsPath(location.pathname)) {+ openPlugins();+ } else {+ openSettings(settingsSectionFromPathname(location.pathname));}+ throw redirect({ to: "/", replace: true });},- component: SettingsRouteLayout,});diff --git a/apps/web/src/routes/usage.tsx b/apps/web/src/routes/usage.tsxindex c617e434b..c11f32d2d 100644--- a/apps/web/src/routes/usage.tsx+++ b/apps/web/src/routes/usage.tsx@@ -1,7 +1,22 @@-import { createFileRoute } from "@tanstack/react-router";+import { createFileRoute, redirect } from "@tanstack/react-router";-import { UsagePage } from "../components/usage/UsagePage";+import { openUsage } from "../usageDialogStore";+/**+ * Usage is a modal now. The route only survives so old deep links and+ * history entries still land somewhere useful: it opens the dialog and hands+ * the user back to the workspace.+ */export const Route = createFileRoute("/usage")({- component: UsagePage,+ beforeLoad: async ({ context }) => {+ if (+ context.authGateState.status !== "authenticated" &&+ context.authGateState.status !== "hosted-static"+ ) {+ throw redirect({ to: "/pair", replace: true });+ }++ openUsage();+ throw redirect({ to: "/", replace: true });+ },});diff --git a/apps/web/src/settingsDialogStore.test.ts b/apps/web/src/settingsDialogStore.test.tsnew file mode 100644index 000000000..222ea28b4--- /dev/null+++ b/apps/web/src/settingsDialogStore.test.ts@@ -0,0 +1,43 @@+import { beforeEach, describe, expect, it } from "vite-plus/test";++import {+ closeSettings,+ openSettings,+ settingsSectionFromPathname,+ useSettingsDialogStore,+} from "./settingsDialogStore";++beforeEach(() => {+ closeSettings();+});++describe("settings dialog store", () => {+ it("opens on General when no section is named", () => {+ openSettings();+ expect(useSettingsDialogStore.getState().section).toBe("general");+ });++ it("closes back to no section", () => {+ openSettings("providers");+ expect(useSettingsDialogStore.getState().section).toBe("providers");+ closeSettings();+ expect(useSettingsDialogStore.getState().section).toBeNull();+ });+});++describe("legacy settings deep links", () => {+ it("maps a known settings path onto its section", () => {+ expect(settingsSectionFromPathname("/settings/connections")).toBe("connections");+ expect(settingsSectionFromPathname("/settings/source-control")).toBe("source-control");+ });++ it("maps keybinding links onto the configurable shortcut panel", () => {+ expect(settingsSectionFromPathname("/settings/keybindings")).toBe("keybindings");+ });++ it("falls back to General for the bare path and for removed sections", () => {+ expect(settingsSectionFromPathname("/settings")).toBe("general");+ expect(settingsSectionFromPathname("/settings/")).toBe("general");+ expect(settingsSectionFromPathname("/settings/archived")).toBe("general");+ });+});diff --git a/apps/web/src/settingsDialogStore.ts b/apps/web/src/settingsDialogStore.tsnew file mode 100644index 000000000..145693454--- /dev/null+++ b/apps/web/src/settingsDialogStore.ts@@ -0,0 +1,52 @@+/**+ * Settings live in a modal, not a page. This store is the single way to open+ * it, so every entry point (sidebar, command palette, in-app links, stale+ * `/settings` deep links) lands on the same surface.+ */+import { create } from "zustand";++/**+ * Every panel the dialog can render. Some sections are reachable only from a+ * link inside another panel, so this is wider than the visible nav.+ */+export const SETTINGS_SECTIONS = [+ "general",+ "appearance",+ "providers",+ "connections",+ "keybindings",+ "source-control",+ "diagnostics",+] as const;++export type SettingsSection = (typeof SETTINGS_SECTIONS)[number];++interface SettingsDialogState {+ /** The open section, or null while the dialog is closed. */+ readonly section: SettingsSection | null;+ readonly openSettings: (section?: SettingsSection) => void;+ readonly closeSettings: () => void;+}++export const useSettingsDialogStore = create<SettingsDialogState>((set) => ({+ section: null,+ openSettings: (section = "general") => set({ section }),+ closeSettings: () => set({ section: null }),+}));++/** Open the settings modal from outside React. */+export function openSettings(section?: SettingsSection): void {+ useSettingsDialogStore.getState().openSettings(section);+}++export function closeSettings(): void {+ useSettingsDialogStore.getState().closeSettings();+}++/** Map a legacy `/settings/...` pathname onto a dialog section. */+export function settingsSectionFromPathname(pathname: string): SettingsSection {+ const slug = pathname.replace(/^\/settings\/?/, "").split("/")[0] ?? "";+ return (SETTINGS_SECTIONS as readonly string[]).includes(slug)+ ? (slug as SettingsSection)+ : "general";+}diff --git a/apps/web/src/state/bots.ts b/apps/web/src/state/bots.tsnew file mode 100644index 000000000..d4550e6c4--- /dev/null+++ b/apps/web/src/state/bots.ts@@ -0,0 +1,32 @@+import { createBotEnvironmentAtoms } from "@t3tools/client-runtime/state/bots";+import type { EnvironmentId, OrchestrationBot, OrchestrationGroup } from "@t3tools/contracts";+import { Atom } from "effect/unstable/reactivity";++import { connectionAtomRuntime } from "../connection/runtime";+import { environmentSnapshotAtom } from "./shell";++const EMPTY_BOTS: ReadonlyArray<OrchestrationBot> = Object.freeze([]);+const EMPTY_GROUPS: ReadonlyArray<OrchestrationGroup> = Object.freeze([]);++export const botEnvironment = createBotEnvironmentAtoms(connectionAtomRuntime);++export const environmentBotsAtom = Atom.family((environmentId: EnvironmentId) =>+ Atom.make(+ (get): ReadonlyArray<OrchestrationBot> =>+ get(environmentSnapshotAtom(environmentId))?.bots ?? EMPTY_BOTS,+ ).pipe(Atom.withLabel(`web-bots:${environmentId}`)),+);++export const environmentGroupsAtom = Atom.family((environmentId: EnvironmentId) =>+ Atom.make(+ (get): ReadonlyArray<OrchestrationGroup> =>+ get(environmentSnapshotAtom(environmentId))?.groups ?? EMPTY_GROUPS,+ ).pipe(Atom.withLabel(`web-groups:${environmentId}`)),+);++/** Snapshot presence gates the server-backed roster swap and bootstrap. */+export const environmentRosterLoadedAtom = Atom.family((environmentId: EnvironmentId) =>+ Atom.make((get): boolean => get(environmentSnapshotAtom(environmentId)) !== null).pipe(+ Atom.withLabel(`web-roster-loaded:${environmentId}`),+ ),+);diff --git a/apps/web/src/state/mcpServers.ts b/apps/web/src/state/mcpServers.tsnew file mode 100644index 000000000..efc90588a--- /dev/null+++ b/apps/web/src/state/mcpServers.ts@@ -0,0 +1,17 @@+import { createMcpServerEnvironmentAtoms } from "@t3tools/client-runtime/state/mcp-servers";+import type { EnvironmentId, McpServer } from "@t3tools/contracts";+import { Atom } from "effect/unstable/reactivity";++import { connectionAtomRuntime } from "../connection/runtime";+import { environmentSnapshotAtom } from "./shell";++const EMPTY_MCP_SERVERS: ReadonlyArray<McpServer> = Object.freeze([]);++export const mcpServerEnvironment = createMcpServerEnvironmentAtoms(connectionAtomRuntime);++export const environmentMcpServersAtom = Atom.family((environmentId: EnvironmentId) =>+ Atom.make(+ (get): ReadonlyArray<McpServer> =>+ get(environmentSnapshotAtom(environmentId))?.mcpServers ?? EMPTY_MCP_SERVERS,+ ).pipe(Atom.withLabel(`web-mcp-servers:${environmentId}`)),+);diff --git a/apps/web/src/state/usage.ts b/apps/web/src/state/usage.tsindex ba78a61d8..e613318ea 100644--- a/apps/web/src/state/usage.ts+++ b/apps/web/src/state/usage.ts@@ -17,11 +17,25 @@ import * as Option from "effect/Option";import { AsyncResult, Atom } from "effect/unstable/reactivity";import { useCallback, useMemo } from "react";+import { makeWindow } from "@t3tools/shared/usageFormat";import { mergeUsage, type EnvironmentUsage, type MergedUsage } from "@t3tools/shared/usageMerge";import { appAtomRegistry } from "../rpc/atomRegistry";import { environmentPresentations } from "./presentation";import { serverEnvironment } from "./server";+export const USAGE_LOOKBACK_DAYS = 30;++function usageWindowKey(input: UsageSummaryInput): string {+ return JSON.stringify({+ sinceDay: input.sinceDay,+ untilDay: input.untilDay,+ timeZone: input.timeZone,+ resolution: input.resolution,+ sinceTime: input.sinceTime,+ untilTime: input.untilTime,+ });+}+export interface EnvironmentUsageStatus {readonly environmentId: EnvironmentId;readonly label: string;@@ -71,17 +85,9 @@ export interface UsageView {readonly refresh: () => void;}-export function useUsage(input: UsageSummaryInput): UsageView {+export function useUsage(input: UsageSummaryInput = makeWindow(USAGE_LOOKBACK_DAYS)): UsageView {const windowKey = useMemo(- () =>- JSON.stringify({- sinceDay: input.sinceDay,- untilDay: input.untilDay,- timeZone: input.timeZone,- resolution: input.resolution,- sinceTime: input.sinceTime,- untilTime: input.untilTime,- }),+ () => usageWindowKey(input),[input.sinceDay,input.untilDay,diff --git a/apps/web/src/test/chatComposerProps.ts b/apps/web/src/test/chatComposerProps.tsnew file mode 100644index 000000000..87763ec82--- /dev/null+++ b/apps/web/src/test/chatComposerProps.ts@@ -0,0 +1,147 @@+import {+ EnvironmentId,+ ProjectId,+ ProviderDriverKind,+ ProviderInstanceId,+ ThreadId,+ type ServerProvider,+} from "@t3tools/contracts";+import { DEFAULT_UNIFIED_SETTINGS } from "@t3tools/contracts/settings";++import { DraftId } from "../composerDraftStore";+import type { ChatComposerProps } from "../components/chat/ChatComposer";+import type { Thread } from "../types";++/**+ * Shared ChatComposer fixtures for composer behavior tests. One configured+ * codex instance with one default model keeps model resolution deterministic.+ */+export const composerTestEnvironmentId = EnvironmentId.make("environment-local");+export const composerTestInstanceId = ProviderInstanceId.make("codex");+export const composerTestModelName = "Launchbar Model";++export function makeComposerTestProvider(): ServerProvider {+ return {+ instanceId: composerTestInstanceId,+ driver: ProviderDriverKind.make("codex"),+ enabled: true,+ installed: true,+ version: null,+ status: "ready",+ auth: { status: "authenticated" },+ checkedAt: "2026-01-01T00:00:00.000Z",+ models: [+ {+ slug: "gpt-5-codex",+ name: composerTestModelName,+ isCustom: false,+ isDefault: true,+ capabilities: {},+ },+ ],+ slashCommands: [],+ skills: [],+ };+}++export function makeComposerTestThread(overrides: Partial<Thread> = {}): Thread {+ return {+ id: ThreadId.make("thread-1"),+ environmentId: composerTestEnvironmentId,+ projectId: ProjectId.make("project-1"),+ title: "Thread",+ modelSelection: { instanceId: composerTestInstanceId, model: "gpt-5-codex" },+ runtimeMode: "full-access",+ interactionMode: "default",+ session: null,+ messages: [],+ proposedPlans: [],+ createdAt: "2026-03-01T00:00:00.000Z",+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ deletedAt: null,+ updatedAt: "2026-03-01T00:00:00.000Z",+ latestTurn: null,+ branch: null,+ worktreePath: null,+ checkpoints: [],+ activities: [],+ ...overrides,+ };+}++export function makeChatComposerProps(+ overrides: Partial<ChatComposerProps> = {},+): ChatComposerProps {+ const draftId = DraftId.make("draft-1");+ return {+ composerDraftTarget: draftId,+ environmentId: composerTestEnvironmentId,+ attachmentUploadsCapabilityKnown: true,+ supportsAttachmentUploads: true,+ routeKind: "draft",+ draftId,+ activeThreadId: ThreadId.make("thread-1"),+ activeThreadEnvironmentId: composerTestEnvironmentId,+ activeThread: makeComposerTestThread(),+ isServerThread: false,+ isLocalDraftThread: true,+ forceExpandedOnMobile: false,+ projectSelectionRequired: false,+ phase: "ready",+ isConnecting: false,+ isSendBusy: false,+ sendDisabledReason: null,+ isPreparingWorktree: false,+ externalDrawerAttached: false,+ environmentUnavailable: null,+ activePendingApproval: null,+ pendingApprovals: [],+ pendingUserInputs: [],+ activePendingProgress: null,+ activePendingResolvedAnswers: null,+ activePendingIsResponding: false,+ activePendingDraftAnswers: {},+ activePendingQuestionIndex: 0,+ respondingRequestIds: [],+ showPlanFollowUpPrompt: false,+ activeProposedPlan: null,+ activeTasksProgress: null,+ activeTaskSteps: null,+ lockedProvider: null,+ providerStatuses: [makeComposerTestProvider()],+ activeProjectDefaultModelSelection: {+ instanceId: composerTestInstanceId,+ model: "gpt-5-codex",+ },+ activeThreadModelSelection: { instanceId: composerTestInstanceId, model: "gpt-5-codex" },+ activeContextWindow: null,+ compactDisabled: false,+ compactDisabledReason: null,+ resolvedTheme: "dark",+ settings: DEFAULT_UNIFIED_SETTINGS,+ keybindings: [],+ terminalOpen: false,+ gitCwd: "/repo",+ promptRef: { current: "" },+ composerImagesRef: { current: [] },+ composerTerminalContextsRef: { current: [] },+ composerElementContextsRef: { current: [] },+ composerRef: { current: null },+ onSend: () => {},+ onInterrupt: () => {},+ onImplementPlanInNewThread: () => {},+ onRespondToApproval: async () => undefined,+ onSelectActivePendingUserInputOption: () => {},+ onAdvanceActivePendingUserInput: () => {},+ onPreviousActivePendingUserInputQuestion: () => {},+ onChangeActivePendingUserInputCustomAnswer: () => {},+ onProviderModelSelect: () => {},+ getModelDisabledReason: () => null,+ focusComposer: () => {},+ setThreadError: () => {},+ onExpandImage: () => {},+ ...overrides,+ };+}diff --git a/apps/web/src/themeBoot.test.ts b/apps/web/src/themeBoot.test.tsindex ae82d184e..8801ebaae 100644--- a/apps/web/src/themeBoot.test.ts+++ b/apps/web/src/themeBoot.test.ts@@ -1,7 +1,9 @@+import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";import { describe, expect, it, vi } from "vite-plus/test";import indexHtml from "../index.html?raw";import {+ AKERU_PAPER_THEME,CUSTOM_THEMES_STORAGE_KEY,getDefaultThemeColors,getThemeColorsForMode,@@ -9,10 +11,7 @@ import {isKnownThemePreference,resolveThemeAppearance,T3_CHAT_THEME,- EMBER_THEME,GROVE_THEME,- IRIS_THEME,- OCEAN_THEME,THEME_APPEARANCE_MODE_STORAGE_KEY,THEME_FOLLOW_SYSTEM_STORAGE_KEY,toCanonicalThemeColor,@@ -155,6 +154,14 @@ describe("index.html boot script", () => {prefersDark: boolean;}> = [{ name: "no stored preference on a dark OS", storage: {}, prefersDark: true },+ {+ name: "Akeru Paper follows a dark OS",+ storage: {+ [THEME_STORAGE_KEY]: "akeru-paper",+ [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true",+ },+ prefersDark: true,+ },{name: "T3 Chat follows a dark OS",storage: { [THEME_STORAGE_KEY]: "t3-chat", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true" },@@ -257,6 +264,26 @@ describe("index.html boot script", () => {expect(boot.isDark).toBe(runtimeResolvedAppearance(storage, prefersDark) === "dark");});+ it("boots a fresh profile into Akeru Paper", () => {+ const boot = runBootScript({ storage: {}, prefersDark: true });++ expect(boot.themeId).toBe("akeru-paper");+ expect(boot.themeSelected).toBe("true");+ expect(boot.isDark).toBe(true);+ expect(boot.backgroundColor).toBe(AKERU_PAPER_THEME.variants!.dark!.chrome);+ });++ it("migrates the old system default to Akeru Paper", () => {+ const boot = runBootScript({+ storage: { [THEME_STORAGE_KEY]: "system" },+ prefersDark: true,+ });++ expect(boot.themeId).toBe("akeru-paper");+ expect(boot.isDark).toBe(true);+ expect(boot.backgroundColor).toBe(AKERU_PAPER_THEME.variants!.dark!.chrome);+ });+it("marks built-in and custom themes on the document element", () => {const chat = runBootScript({storage: { [THEME_STORAGE_KEY]: "t3-chat", [THEME_FOLLOW_SYSTEM_STORAGE_KEY]: "true" },@@ -342,7 +369,7 @@ describe("index.html boot script", () => {// boot script's hand-maintained copy into a CI-enforced contract: any// palette change breaks this test until the copy in index.html is updated.it("keeps every built-in boot splash in sync with the real palettes", () => {- for (const theme of [T3_CHAT_THEME, GROVE_THEME, OCEAN_THEME, EMBER_THEME, IRIS_THEME]) {+ for (const theme of BUILT_IN_THEMES) {// The boot script resolves every built-in from a light base appearance.expect(theme.appearance).toBe("light");for (const mode of ["light", "dark"] as const) {@@ -514,5 +541,6 @@ describe("index.html boot script", () => {const dark = runBootScript({ storageThrows: true, prefersDark: true });expect(dark.isDark).toBe(true);+ expect(dark.backgroundColor).toBe("#050505");});});diff --git a/apps/web/src/themePalette.test.ts b/apps/web/src/themePalette.test.tsindex a836f7e0c..33f3fa1f9 100644--- a/apps/web/src/themePalette.test.ts+++ b/apps/web/src/themePalette.test.ts@@ -1,7 +1,12 @@+import * as NodeServices from "@effect/platform-node/NodeServices";+import { it as effectIt } from "@effect/vitest";+import * as Effect from "effect/Effect";+import * as FileSystem from "effect/FileSystem";import { describe, expect, it, vi } from "vite-plus/test";-import { BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";+import { BUILT_IN_THEME_IDS, BUILT_IN_THEMES } from "@t3tools/shared/themePalettes";import {+ AKERU_PAPER_THEME,applyThemeColorPreview,applyThemePalette,getThemeColorsForMode,@@ -38,6 +43,7 @@ import {getDefaultThemeColors,themeColorToHex,toCanonicalThemeColor,+ THEME_COLOR_ROLES,THEME_FILE_VERSION,} from "./themePalette";@@ -433,12 +439,57 @@ describe("theme files", () => {}});+ it("keeps the Akeru Paper palette tied to the landing design", () => {+ expect(BUILT_IN_THEME_IDS).toContain(AKERU_PAPER_THEME.id);+ expect(BUILT_IN_THEMES.map((theme) => theme.id)).toEqual(BUILT_IN_THEME_IDS);+ expect(Object.keys(AKERU_PAPER_THEME.colors).sort()).toEqual([...THEME_COLOR_ROLES].sort());+ expect(Object.keys(AKERU_PAPER_THEME.variants!.dark!).sort()).toEqual(+ [...THEME_COLOR_ROLES].sort(),+ );+ expectThemeColors(AKERU_PAPER_THEME.colors, {+ canvas: "#f4f1ea",+ text: "#2a2724",+ accent: "#8b6fc9",+ focus: "#8b6fc9",+ update: "#8b6fc9",+ messageAction: "#8b6fc9",+ terminalCursor: "#8b6fc9",+ messageSurface: "#f0eaf8",+ codeBackground: "#ece8e0",+ sidebar: "#ece8df",+ });+ expectThemeColors(AKERU_PAPER_THEME.variants!.dark!, {+ canvas: "#050505",+ text: "#f4f4f5",+ accent: "#8b6fc9",+ focus: "#8b6fc9",+ update: "#8b6fc9",+ messageAction: "#8b6fc9",+ messageSurface: "#3f3f46",+ codeBackground: "#111111",+ sidebar: "#111111",+ });+ });++ effectIt.effect("keeps Akeru Paper dark surfaces flat and opaque", () =>+ Effect.gen(function* () {+ const fileSystem = yield* FileSystem.FileSystem;+ const css = yield* fileSystem.readFileString(+ decodeURIComponent(new URL("./index.css", import.meta.url).pathname),+ );+ const scopedOverride = css.match(/html\[data-theme-id="akeru-paper"\] \{[\s\S]*?\n\}/)?.[0];++ expect(scopedOverride).toContain("--surface-grain: none");+ expect(scopedOverride).toContain("--glass-opacity: 100%");+ expect(scopedOverride).toContain("--glass-blur: 0px");+ }).pipe(Effect.provide(NodeServices.layer)),+ );+it("includes the dual-mode maintainer themes", () => {- for (const theme of [T3_CHAT_THEME, GROVE_THEME, OCEAN_THEME, EMBER_THEME, IRIS_THEME]) {+ for (const theme of BUILT_IN_THEMES) {expect(getThemeDefinition(theme.id)).toBe(theme);expect(getThemeModes(theme)).toEqual(["light", "dark"]);- expect(theme.sidebarArtwork).toBe(true);- expect(themeAllowsSidebarArtwork(theme.id)).toBe(true);+ expect(themeAllowsSidebarArtwork(theme.id)).toBe(theme.sidebarArtwork === true);expect(theme.colors.accent).toMatch(/^oklch\(/);expect(theme.variants?.dark?.accent).toMatch(/^oklch\(/);@@ -447,7 +498,7 @@ describe("theme files", () => {expect(colors).not.toBeNull();expect(contrastRatio(colors!.text, colors!.canvas)).toBeGreaterThanOrEqual(4.5);expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeGreaterThanOrEqual(4.5);- if (theme !== T3_CHAT_THEME) {+ if (theme !== T3_CHAT_THEME && theme !== AKERU_PAPER_THEME) {expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeLessThan(5.5);expect(contrastRatio(colors!.textMuted, colors!.canvas)).toBeCloseTo(mode === "dark" ? 5.082 : 4.705,@@ -476,6 +527,19 @@ describe("theme files", () => {expect(themeAllowsSidebarArtwork("my-custom-theme")).toBe(false);});+ it("reserves the Akeru Paper id for the built-in theme", () => {+ expect(isKnownThemePreference(AKERU_PAPER_THEME.id)).toBe(true);+ expect(() =>+ parseThemeFile({+ version: THEME_FILE_VERSION,+ id: AKERU_PAPER_THEME.id,+ name: "Akeru Paper copy",+ appearance: "light",+ colors: {},+ }),+ ).toThrow('The theme id "akeru-paper" is reserved.');+ });+it("rejects a variant that repeats the base appearance", () => {expect(() =>parseThemeFile({diff --git a/apps/web/src/themePalette.ts b/apps/web/src/themePalette.tsindex 8402aeb20..8b5638ff6 100644--- a/apps/web/src/themePalette.ts+++ b/apps/web/src/themePalette.ts@@ -2,6 +2,7 @@ import * as Schema from "effect/Schema";import "culori/css";import { converter, parse } from "culori/fn";import {+ AKERU_PAPER_THEME,BUILT_IN_THEMES,EMBER_THEME,GROVE_THEME,@@ -16,9 +17,20 @@ import {type ThemeVariants,} from "@t3tools/shared/themePalettes";-export { EMBER_THEME, GROVE_THEME, IRIS_THEME, OCEAN_THEME, T3_CHAT_THEME, THEME_COLOR_ROLES };+export {+ AKERU_PAPER_THEME,+ BUILT_IN_THEMES,+ EMBER_THEME,+ GROVE_THEME,+ IRIS_THEME,+ OCEAN_THEME,+ T3_CHAT_THEME,+ THEME_COLOR_ROLES,+};export type { ThemeAppearance, ThemeColorRole, ThemeColors, ThemeDefinition, ThemeVariants };+export const AKERU_PAPER_THEME_ID = "akeru-paper" as const;+export const AKERU_PAPER_THEME_LABEL = "Akeru Paper";export const T3_CHAT_THEME_ID = "t3-chat" as const;export const T3_CHAT_THEME_LABEL = "T3 Chat";export const GROVE_THEME_ID = "grove" as const;@@ -60,6 +72,7 @@ const RESERVED_THEME_IDS = new Set(["system","light","dark",+ AKERU_PAPER_THEME_ID,T3_CHAT_THEME_ID,GROVE_THEME_ID,OCEAN_THEME_ID,diff --git a/apps/web/src/usageDialogStore.test.ts b/apps/web/src/usageDialogStore.test.tsnew file mode 100644index 000000000..0c4bf78d4--- /dev/null+++ b/apps/web/src/usageDialogStore.test.ts@@ -0,0 +1,15 @@+import { afterEach, describe, expect, it } from "vite-plus/test";++import { closeUsage, openUsage, useUsageDialogStore } from "./usageDialogStore";++afterEach(() => closeUsage());++describe("usage dialog store", () => {+ it("opens and closes independently from settings", () => {+ expect(useUsageDialogStore.getState().open).toBe(false);+ openUsage();+ expect(useUsageDialogStore.getState().open).toBe(true);+ closeUsage();+ expect(useUsageDialogStore.getState().open).toBe(false);+ });+});diff --git a/apps/web/src/usageDialogStore.ts b/apps/web/src/usageDialogStore.tsnew file mode 100644index 000000000..e4f37094c--- /dev/null+++ b/apps/web/src/usageDialogStore.ts@@ -0,0 +1,21 @@+import { create } from "zustand";++interface UsageDialogState {+ readonly open: boolean;+ readonly openUsage: () => void;+ readonly closeUsage: () => void;+}++export const useUsageDialogStore = create<UsageDialogState>((set) => ({+ open: false,+ openUsage: () => set({ open: true }),+ closeUsage: () => set({ open: false }),+}));++export function openUsage(): void {+ useUsageDialogStore.getState().openUsage();+}++export function closeUsage(): void {+ useUsageDialogStore.getState().closeUsage();+}diff --git a/apps/web/src/versionSkew.test.ts b/apps/web/src/versionSkew.test.tsindex 708ebc692..95b3c9906 100644--- a/apps/web/src/versionSkew.test.ts+++ b/apps/web/src/versionSkew.test.ts@@ -19,7 +19,7 @@ import {} from "./versionSkew";const MISMATCH_HINT =- "Version mismatch. Try syncing the client and server to the same T3 Code version.";+ "Version mismatch. Try syncing the client and server to the same Akeru Bot version.";describe("versionSkew", () => {beforeEach(() => {diff --git a/apps/web/src/versionSkew.ts b/apps/web/src/versionSkew.tsindex 594bff081..0feb323e8 100644--- a/apps/web/src/versionSkew.ts+++ b/apps/web/src/versionSkew.ts@@ -67,7 +67,7 @@ export function resolveVersionMismatch(return {clientVersion: normalizedClientVersion,serverVersion: normalizedServerVersion,- hint: "Version mismatch. Try syncing the client and server to the same T3 Code version.",+ hint: "Version mismatch. Try syncing the client and server to the same Akeru Bot version.",};}diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.jsonindex 186b6ebfe..c08be5388 100644--- a/apps/web/tsconfig.json+++ b/apps/web/tsconfig.json@@ -31,6 +31,8 @@"vercel.ts","test","scripts/warm-dep-cache.ts",+ "../../plugins","../../scripts/lib/public-config.ts"- ]+ ],+ "exclude": ["../../plugins/*.test.ts"]}diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.tsindex 6ee5de587..549744bac 100644--- a/apps/web/vite.config.ts+++ b/apps/web/vite.config.ts@@ -1,3 +1,4 @@+import * as NodeUrl from "node:url";import * as NodeZlib from "node:zlib";import tailwindcss from "@tailwindcss/vite";@@ -14,6 +15,8 @@ import { DEV_PROXIED_PATH_PREFIXES } from "@t3tools/shared/devProxy";import { loadRepoEnv } from "../../scripts/lib/public-config";+const reactGrabEntry = NodeUrl.fileURLToPath(import.meta.resolve("react-grab"));+const repoEnv = loadRepoEnv();Object.assign(process.env, repoEnv);@@ -170,7 +173,6 @@ export default defineConfig(() => {],optimizeDeps: {include: [- "@clerk/clerk-js","@clerk/react/internal","@pierre/diffs","@pierre/diffs/editor",@@ -179,6 +181,7 @@ export default defineConfig(() => {"effect/Array","effect/Order","react-dom/client",+ "react-grab",],},define: {@@ -205,7 +208,10 @@ export default defineConfig(() => {},resolve: {tsconfigPaths: true,- dedupe: ["react", "react-dom"],+ dedupe: ["react", "react-dom", "effect"],+ alias: {+ "react-grab": reactGrabEntry,+ },},experimental: {bundledDev,diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.jsonindex abed33998..e5326c4f2 100644--- a/packages/client-runtime/package.json+++ b/packages/client-runtime/package.json@@ -51,6 +51,10 @@"types": "./src/state/auth.ts","default": "./src/state/auth.ts"},+ "./state/bots": {+ "types": "./src/state/bots.ts",+ "default": "./src/state/bots.ts"+ },"./state/assets": {"types": "./src/state/assets.ts","default": "./src/state/assets.ts"@@ -75,6 +79,10 @@"types": "./src/state/models.ts","default": "./src/state/models.ts"},+ "./state/mcp-servers": {+ "types": "./src/state/mcpServerCommands.ts",+ "default": "./src/state/mcpServerCommands.ts"+ },"./state/orchestration": {"types": "./src/state/orchestration.ts","default": "./src/state/orchestration.ts"diff --git a/packages/client-runtime/src/connection/registry.test.ts b/packages/client-runtime/src/connection/registry.test.tsindex 9354db9c9..c8e2612f1 100644--- a/packages/client-runtime/src/connection/registry.test.ts+++ b/packages/client-runtime/src/connection/registry.test.ts@@ -114,6 +114,8 @@ const SSH_PROFILE = new SshConnectionProfile({const CACHED_SNAPSHOT: OrchestrationShellSnapshot = {snapshotSequence: 1,+ bots: [],+ groups: [],projects: [],threads: [],updatedAt: "2026-06-06T00:00:00.000Z",diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.tsindex 0cb165006..866f25e22 100644--- a/packages/client-runtime/src/operations/commands.test.ts+++ b/packages/client-runtime/src/operations/commands.test.ts@@ -1,6 +1,9 @@import {+ BotId,CommandId,EnvironmentId,+ GroupId,+ McpServerId,ORCHESTRATION_WS_METHODS,ProjectId,ThreadId,@@ -23,10 +26,15 @@ import * as RpcSession from "../rpc/session.ts";import type { WsRpcProtocolClient } from "../rpc/protocol.ts";import {archiveThread,+ assignGroupMember,+ createMcpServer,createProject,settleThread,+ setGroupBoss,stopThreadSession,+ unassignGroupMember,unsettleThread,+ updateMcpServer,} from "./commands.ts";const TEST_CRYPTO_LAYER = Layer.succeed(@@ -99,6 +107,85 @@ describe("environment commands", () => {}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),);+ it.effect("dispatches both MCP transport configurations", () =>+ Effect.gen(function* () {+ const dispatched: ClientOrchestrationCommand[] = [];+ const supervisor = yield* makeSupervisor(dispatched);+ const mcpServerId = McpServerId.make("mcp-server-1");++ yield* createMcpServer({+ commandId: CommandId.make("mcp-create"),+ mcpServerId,+ name: "Filesystem",+ transport: "stdio",+ command: "bunx",+ args: ["server-filesystem"],+ createdAt: "2026-06-06T00:00:00.000Z",+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));+ yield* updateMcpServer({+ commandId: CommandId.make("mcp-update"),+ mcpServerId,+ name: "Remote",+ transport: "url",+ url: "https://mcp.example.com",+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));++ expect(dispatched).toEqual([+ {+ type: "mcp-server.create",+ commandId: "mcp-create",+ mcpServerId: "mcp-server-1",+ name: "Filesystem",+ transport: "stdio",+ command: "bunx",+ args: ["server-filesystem"],+ createdAt: "2026-06-06T00:00:00.000Z",+ },+ {+ type: "mcp-server.update",+ commandId: "mcp-update",+ mcpServerId: "mcp-server-1",+ name: "Remote",+ transport: "url",+ url: "https://mcp.example.com",+ },+ ]);+ }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),+ );++ it.effect("dispatches reversible group membership commands", () =>+ Effect.gen(function* () {+ const dispatched: ClientOrchestrationCommand[] = [];+ const supervisor = yield* makeSupervisor(dispatched);+ const groupId = GroupId.make("group-1");+ const botId = BotId.make("bot-1");++ yield* assignGroupMember({+ commandId: CommandId.make("assign-member"),+ groupId,+ botId,+ role: "specialist",+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));+ yield* unassignGroupMember({+ commandId: CommandId.make("unassign-member"),+ groupId,+ botId,+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));+ yield* setGroupBoss({+ commandId: CommandId.make("set-boss"),+ groupId,+ bossBotId: botId,+ unassignPreviousBoss: true,+ }).pipe(Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor));++ expect(dispatched.map((command) => command.type)).toEqual([+ "group.member.assign",+ "group.member.unassign",+ "group.boss.set",+ ]);+ }).pipe(Effect.provide(TEST_CRYPTO_LAYER)),+ );+it.effect("preserves caller metadata for idempotent queued commands", () =>Effect.gen(function* () {const dispatched: ClientOrchestrationCommand[] = [];diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.tsindex cb74f117b..33ab2920a 100644--- a/packages/client-runtime/src/operations/commands.ts+++ b/packages/client-runtime/src/operations/commands.ts@@ -17,20 +17,35 @@ import {type CommandType = ClientOrchestrationCommand["type"];type CommandOf<T extends CommandType> = Extract<ClientOrchestrationCommand, { readonly type: T }>;-type CommandInput<T extends CommandType> = Omit<- CommandOf<T>,- "type" | "commandId" | "createdAt"-> & {- readonly commandId?: CommandId;-} & ("createdAt" extends keyof CommandOf<T>- ? {- readonly createdAt?: CommandOf<T>["createdAt"];- }- : {});+type CommandInputFor<C extends ClientOrchestrationCommand> = C extends ClientOrchestrationCommand+ ? Omit<C, "type" | "commandId" | "createdAt"> & {+ readonly commandId?: CommandId;+ } & ("createdAt" extends keyof C+ ? {+ readonly createdAt?: C["createdAt"];+ }+ : {})+ : never;+type CommandInput<T extends CommandType> = CommandInputFor<CommandOf<T>>;export type CreateProjectInput = CommandInput<"project.create">;export type UpdateProjectInput = CommandInput<"project.meta.update">;export type DeleteProjectInput = CommandInput<"project.delete">;+export type CreateBotInput = CommandInput<"bot.create">;+export type UpdateBotInput = CommandInput<"bot.update">;+export type ArchiveBotInput = CommandInput<"bot.archive">;+export type RestoreBotInput = CommandInput<"bot.restore">;+export type CreateGroupInput = CommandInput<"group.create">;+export type RenameGroupInput = CommandInput<"group.rename">;+export type DeleteGroupInput = CommandInput<"group.delete">;+export type AssignGroupMemberInput = CommandInput<"group.member.assign">;+export type UnassignGroupMemberInput = CommandInput<"group.member.unassign">;+export type SetGroupBossInput = CommandInput<"group.boss.set">;+export type CreateMcpServerInput = CommandInput<"mcp-server.create">;+export type UpdateMcpServerInput = CommandInput<"mcp-server.update">;+export type DeleteMcpServerInput = CommandInput<"mcp-server.delete">;+export type EnableMcpServerInput = CommandInput<"mcp-server.enable">;+export type DisableMcpServerInput = CommandInput<"mcp-server.disable">;export type CreateThreadInput = CommandInput<"thread.create">;export type DeleteThreadInput = CommandInput<"thread.delete">;export type ArchiveThreadInput = CommandInput<"thread.archive">;@@ -118,6 +133,178 @@ export const deleteProject: (input: DeleteProjectInput) => CommandEffect = Effec});});+export const createBot: (input: CreateBotInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.createBot",+)(function* (input) {+ const metadata = yield* timestampedCommandMetadata(input);+ return yield* dispatch({+ ...input,+ type: "bot.create",+ commandId: metadata.commandId,+ createdAt: metadata.createdAt,+ });+});++export const createMcpServer: (input: CreateMcpServerInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.createMcpServer",+)(function* (input) {+ const metadata = yield* timestampedCommandMetadata(input);+ if (input.transport === "stdio") {+ return yield* dispatch({+ ...input,+ type: "mcp-server.create",+ commandId: metadata.commandId,+ createdAt: metadata.createdAt,+ });+ }+ return yield* dispatch({+ ...input,+ type: "mcp-server.create",+ commandId: metadata.commandId,+ createdAt: metadata.createdAt,+ });+});++export const updateBot: (input: UpdateBotInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.updateBot",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "bot.update",+ commandId: yield* commandId(input),+ });+});++export const updateMcpServer: (input: UpdateMcpServerInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.updateMcpServer",+)(function* (input) {+ const nextCommandId = yield* commandId(input);+ if (input.transport === "stdio") {+ return yield* dispatch({+ ...input,+ type: "mcp-server.update",+ commandId: nextCommandId,+ });+ }+ return yield* dispatch({+ ...input,+ type: "mcp-server.update",+ commandId: nextCommandId,+ });+});++export const deleteMcpServer: (input: DeleteMcpServerInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.deleteMcpServer",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "mcp-server.delete",+ commandId: yield* commandId(input),+ });+});++export const archiveBot: (input: ArchiveBotInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.archiveBot",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "bot.archive",+ commandId: yield* commandId(input),+ });+});++export const enableMcpServer: (input: EnableMcpServerInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.enableMcpServer",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "mcp-server.enable",+ commandId: yield* commandId(input),+ });+});++export const restoreBot: (input: RestoreBotInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.restoreBot",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "bot.restore",+ commandId: yield* commandId(input),+ });+});++export const createGroup: (input: CreateGroupInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.createGroup",+)(function* (input) {+ const metadata = yield* timestampedCommandMetadata(input);+ return yield* dispatch({+ ...input,+ type: "group.create",+ commandId: metadata.commandId,+ createdAt: metadata.createdAt,+ });+});++export const renameGroup: (input: RenameGroupInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.renameGroup",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "group.rename",+ commandId: yield* commandId(input),+ });+});++export const deleteGroup: (input: DeleteGroupInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.deleteGroup",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "group.delete",+ commandId: yield* commandId(input),+ });+});++export const assignGroupMember: (input: AssignGroupMemberInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.assignGroupMember",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "group.member.assign",+ commandId: yield* commandId(input),+ });+});++export const unassignGroupMember: (input: UnassignGroupMemberInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.unassignGroupMember",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "group.member.unassign",+ commandId: yield* commandId(input),+ });+});++export const setGroupBoss: (input: SetGroupBossInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.setGroupBoss",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "group.boss.set",+ commandId: yield* commandId(input),+ });+});++export const disableMcpServer: (input: DisableMcpServerInput) => CommandEffect = Effect.fn(+ "EnvironmentCommands.disableMcpServer",+)(function* (input) {+ return yield* dispatch({+ ...input,+ type: "mcp-server.disable",+ commandId: yield* commandId(input),+ });+});+export const createThread: (input: CreateThreadInput) => CommandEffect = Effect.fn("EnvironmentCommands.createThread",)(function* (input) {diff --git a/packages/client-runtime/src/relay/managedRelayState.ts b/packages/client-runtime/src/relay/managedRelayState.tsindex 1a3a22efb..eee3dcd34 100644--- a/packages/client-runtime/src/relay/managedRelayState.ts+++ b/packages/client-runtime/src/relay/managedRelayState.ts@@ -124,7 +124,7 @@ export function createManagedRelaySession(input: ManagedRelaySessionInput): Manatry: () => readCachedClerkToken(nowMillis),catch: (cause) =>new ManagedRelaySessionError({- message: "Could not obtain the T3 Connect session token.",+ message: "Could not obtain the relay session token.",cause,}),});@@ -182,7 +182,7 @@ function readSessionClerkToken(? Effect.succeed(token): Effect.fail(new ManagedRelaySessionError({- message: "The T3 Connect session token is unavailable.",+ message: "The relay session token is unavailable.",}),),),@@ -229,7 +229,7 @@ export const deregisterManagedRelayEnvironment = Effect.fn(const session = registry.get(managedRelaySessionAtom);if (!session || session.accountId !== input.accountId) {return yield* new ManagedRelaySessionError({- message: "Sign in to T3 Connect before deregistering an environment.",+ message: "Sign in before deregistering an environment.",});}const clerkToken = yield* readSessionClerkToken(session);@@ -245,7 +245,7 @@ function requireClerkToken(if (!session || session.accountId !== accountId) {return Effect.fail(new ManagedRelaySessionError({- message: "Sign in to T3 Connect before loading relay data.",+ message: "Sign in before loading relay data.",}),);}@@ -315,7 +315,7 @@ export function readManagedRelaySnapshotState<A>(let errorTraceId: string | null = null;if (result._tag === "Failure") {const cause = Cause.squash(result.cause);- error = cause instanceof Error ? cause.message : "Could not load T3 Connect data.";+ error = cause instanceof Error ? cause.message : "Could not load relay data.";errorTraceId = findErrorTraceId(cause);}return {diff --git a/packages/client-runtime/src/state/bots.ts b/packages/client-runtime/src/state/bots.tsnew file mode 100644index 000000000..f4c93017f--- /dev/null+++ b/packages/client-runtime/src/state/bots.ts@@ -0,0 +1,121 @@+import * as Crypto from "effect/Crypto";+import { Atom } from "effect/unstable/reactivity";++import type { EnvironmentRegistry } from "../connection/registry.ts";+import {+ type ArchiveBotInput,+ type AssignGroupMemberInput,+ type CreateBotInput,+ type CreateGroupInput,+ type DeleteGroupInput,+ type RenameGroupInput,+ type RestoreBotInput,+ type SetGroupBossInput,+ type UnassignGroupMemberInput,+ type UpdateBotInput,+ archiveBot,+ assignGroupMember,+ createBot,+ createGroup,+ deleteGroup,+ renameGroup,+ restoreBot,+ setGroupBoss,+ unassignGroupMember,+ updateBot,+} from "../operations/commands.ts";+import { createAtomCommandScheduler, createEnvironmentCommand } from "./runtime.ts";++export type {+ ArchiveBotInput,+ AssignGroupMemberInput,+ CreateBotInput,+ CreateGroupInput,+ DeleteGroupInput,+ RenameGroupInput,+ RestoreBotInput,+ SetGroupBossInput,+ UnassignGroupMemberInput,+ UpdateBotInput,+} from "../operations/commands.ts";++export function createBotEnvironmentAtoms<R, E>(+ runtime: Atom.AtomRuntime<EnvironmentRegistry | Crypto.Crypto | R, E>,+) {+ const scheduler = createAtomCommandScheduler();+ const botConcurrency = {+ mode: "serial" as const,+ key: ({ environmentId, input }: { environmentId: string; input: { botId: string } }) =>+ JSON.stringify([environmentId, "bot", input.botId]),+ };+ const groupConcurrency = {+ mode: "serial" as const,+ key: ({ environmentId, input }: { environmentId: string; input: { groupId: string } }) =>+ JSON.stringify([environmentId, "group", input.groupId]),+ };++ return {+ create: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:bot:create",+ execute: (input: CreateBotInput) => createBot(input),+ scheduler,+ concurrency: botConcurrency,+ }),+ update: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:bot:update",+ execute: (input: UpdateBotInput) => updateBot(input),+ scheduler,+ concurrency: botConcurrency,+ }),+ archive: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:bot:archive",+ execute: (input: ArchiveBotInput) => archiveBot(input),+ scheduler,+ concurrency: botConcurrency,+ }),+ restore: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:bot:restore",+ execute: (input: RestoreBotInput) => restoreBot(input),+ scheduler,+ concurrency: botConcurrency,+ }),+ groups: {+ create: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:group:create",+ execute: (input: CreateGroupInput) => createGroup(input),+ scheduler,+ concurrency: groupConcurrency,+ }),+ rename: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:group:rename",+ execute: (input: RenameGroupInput) => renameGroup(input),+ scheduler,+ concurrency: groupConcurrency,+ }),+ delete: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:group:delete",+ execute: (input: DeleteGroupInput) => deleteGroup(input),+ scheduler,+ concurrency: groupConcurrency,+ }),+ assignMember: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:group:member:assign",+ execute: (input: AssignGroupMemberInput) => assignGroupMember(input),+ scheduler,+ concurrency: groupConcurrency,+ }),+ unassignMember: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:group:member:unassign",+ execute: (input: UnassignGroupMemberInput) => unassignGroupMember(input),+ scheduler,+ concurrency: groupConcurrency,+ }),+ setBoss: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:group:boss:set",+ execute: (input: SetGroupBossInput) => setGroupBoss(input),+ scheduler,+ concurrency: groupConcurrency,+ }),+ },+ };+}diff --git a/packages/client-runtime/src/state/entities.test.ts b/packages/client-runtime/src/state/entities.test.tsindex d3bb66802..31558d882 100644--- a/packages/client-runtime/src/state/entities.test.ts+++ b/packages/client-runtime/src/state/entities.test.ts@@ -108,6 +108,8 @@ const THREAD_SHELL = {const SNAPSHOT: OrchestrationShellSnapshot = {snapshotSequence: 1,updatedAt: "2026-06-01T00:00:00.000Z",+ bots: [],+ groups: [],projects: [{id: PROJECT_ID,diff --git a/packages/client-runtime/src/state/mcpServerCommands.ts b/packages/client-runtime/src/state/mcpServerCommands.tsnew file mode 100644index 000000000..dd1f59043--- /dev/null+++ b/packages/client-runtime/src/state/mcpServerCommands.ts@@ -0,0 +1,69 @@+import * as Crypto from "effect/Crypto";+import { Atom } from "effect/unstable/reactivity";++import type { EnvironmentRegistry } from "../connection/registry.ts";+import {+ createMcpServer,+ deleteMcpServer,+ disableMcpServer,+ enableMcpServer,+ type CreateMcpServerInput,+ type DeleteMcpServerInput,+ type DisableMcpServerInput,+ type EnableMcpServerInput,+ type UpdateMcpServerInput,+ updateMcpServer,+} from "../operations/commands.ts";+import { createAtomCommandScheduler, createEnvironmentCommand } from "./runtime.ts";++export type {+ CreateMcpServerInput,+ DeleteMcpServerInput,+ DisableMcpServerInput,+ EnableMcpServerInput,+ UpdateMcpServerInput,+} from "../operations/commands.ts";++export function createMcpServerEnvironmentAtoms<R, E>(+ runtime: Atom.AtomRuntime<EnvironmentRegistry | Crypto.Crypto | R, E>,+) {+ const scheduler = createAtomCommandScheduler();+ const concurrency = {+ mode: "serial" as const,+ key: ({ environmentId, input }: { environmentId: string; input: { mcpServerId: string } }) =>+ JSON.stringify([environmentId, input.mcpServerId]),+ };++ return {+ create: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:mcp-server:create",+ execute: (input: CreateMcpServerInput) => createMcpServer(input),+ scheduler,+ concurrency,+ }),+ update: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:mcp-server:update",+ execute: (input: UpdateMcpServerInput) => updateMcpServer(input),+ scheduler,+ concurrency,+ }),+ delete: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:mcp-server:delete",+ execute: (input: DeleteMcpServerInput) => deleteMcpServer(input),+ scheduler,+ concurrency,+ }),+ enable: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:mcp-server:enable",+ execute: (input: EnableMcpServerInput) => enableMcpServer(input),+ scheduler,+ concurrency,+ }),+ disable: createEnvironmentCommand(runtime, {+ label: "environment-data:commands:mcp-server:disable",+ execute: (input: DisableMcpServerInput) => disableMcpServer(input),+ scheduler,+ concurrency,+ }),+ };+}diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.tsindex 2fef689a9..e23841edb 100644--- a/packages/client-runtime/src/state/server.ts+++ b/packages/client-runtime/src/state/server.ts@@ -728,6 +728,11 @@ export function createServerEnvironmentAtoms<R, E>(tag: WS_METHODS.serverGetUsageSummary,staleTimeMs: 60_000,}),+ subscriptionAuth: createEnvironmentRpcQueryAtomFamily(runtime, {+ label: "environment-data:server:subscription-auth",+ tag: WS_METHODS.subscriptionAuthList,+ staleTimeMs: 5_000,+ }),configProjection,welcome: createEnvironmentRpcSubscriptionAtomFamily(runtime, {label: "environment-data:server:welcome",@@ -770,6 +775,26 @@ export function createServerEnvironmentAtoms<R, E>(scheduler: configScheduler,concurrency: configConcurrency,}),+ startSubscriptionAuth: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:server:subscription-auth:start",+ tag: WS_METHODS.subscriptionAuthStart,+ }),+ pollSubscriptionAuth: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:server:subscription-auth:poll",+ tag: WS_METHODS.subscriptionAuthPoll,+ }),+ completeSubscriptionAuth: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:server:subscription-auth:complete",+ tag: WS_METHODS.subscriptionAuthComplete,+ }),+ cancelSubscriptionAuth: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:server:subscription-auth:cancel",+ tag: WS_METHODS.subscriptionAuthCancel,+ }),+ logoutSubscriptionAuth: createEnvironmentRpcCommand(runtime, {+ label: "environment-data:server:subscription-auth:logout",+ tag: WS_METHODS.subscriptionAuthLogout,+ }),signalProcess: createEnvironmentRpcCommand(runtime, {label: "environment-data:server:signal-process",tag: WS_METHODS.serverSignalProcess,diff --git a/packages/client-runtime/src/state/shell-sync.test.ts b/packages/client-runtime/src/state/shell-sync.test.tsindex 40e9bd80d..b5612df5b 100644--- a/packages/client-runtime/src/state/shell-sync.test.ts+++ b/packages/client-runtime/src/state/shell-sync.test.ts@@ -42,6 +42,8 @@ const PREPARED: PreparedConnection = {const LIVE_SHELL_SNAPSHOT: OrchestrationShellSnapshot = {snapshotSequence: 1,+ bots: [],+ groups: [],projects: [],threads: [],updatedAt: "2026-06-06T00:00:00.000Z",@@ -154,6 +156,8 @@ describe("environment shell synchronization", () => {Effect.gen(function* () {const cachedSnapshot: OrchestrationShellSnapshot = {snapshotSequence: 5,+ bots: [],+ groups: [],projects: [],threads: [{ id: "cached-thread" } as never],updatedAt: "2026-06-06T00:00:00.000Z",diff --git a/packages/client-runtime/src/state/shell.test.ts b/packages/client-runtime/src/state/shell.test.tsindex f1326e0a5..4e4ca82e1 100644--- a/packages/client-runtime/src/state/shell.test.ts+++ b/packages/client-runtime/src/state/shell.test.ts@@ -37,6 +37,8 @@ function shellState(input: {snapshotSequence: input.snapshotSequence ?? 1,updatedAt: input.updatedAt,projects: [],+ bots: [],+ groups: [],threads: [],}),status: input.status,diff --git a/packages/client-runtime/src/state/shellReducer.test.ts b/packages/client-runtime/src/state/shellReducer.test.tsindex fdccc4c47..d90ff5403 100644--- a/packages/client-runtime/src/state/shellReducer.test.ts+++ b/packages/client-runtime/src/state/shellReducer.test.ts@@ -1,12 +1,21 @@import { describe, expect, it } from "vite-plus/test";-import { ProjectId, ProviderInstanceId, ThreadId } from "@t3tools/contracts";+import {+ BotId,+ GroupId,+ McpServerId,+ ProjectId,+ ProviderInstanceId,+ ThreadId,+} from "@t3tools/contracts";import type { OrchestrationShellSnapshot, OrchestrationShellStreamEvent } from "@t3tools/contracts";import { applyShellStreamEvent } from "./shellReducer.ts";const baseSnapshot: OrchestrationShellSnapshot = {snapshotSequence: 0,+ bots: [],+ groups: [],projects: [],threads: [],updatedAt: "2026-04-01T00:00:00.000Z",@@ -23,6 +32,41 @@ const stubProject = {updatedAt: "2026-04-01T00:00:00.000Z",} as const;+const stubMcpServer = {+ id: McpServerId.make("mcp-server-1"),+ name: "Filesystem",+ transport: "stdio" as const,+ command: "bunx",+ args: ["@modelcontextprotocol/server-filesystem"],+ enabled: true,+ createdAt: "2026-04-01T00:00:00.000Z",+ updatedAt: "2026-04-01T00:00:00.000Z",+};++const stubBot = {+ id: BotId.make("bot-1"),+ name: "Builder",+ title: "Backend engineer",+ avatar: { kind: "dither" as const, seed: "builder" },+ engine: null,+ sandbox: "local" as const,+ runtimeMode: "full-access" as const,+ usageCap: null,+ groupId: null,+ archivedAt: null,+ createdAt: "2026-04-01T00:00:00.000Z",+ updatedAt: "2026-04-01T00:00:00.000Z",+};++const stubGroup = {+ id: GroupId.make("group-1"),+ name: "Engineering",+ bossBotId: stubBot.id,+ members: [{ botId: stubBot.id, role: "boss" as const }],+ createdAt: "2026-04-01T00:00:00.000Z",+ updatedAt: "2026-04-01T00:00:00.000Z",+};+const stubThread = {id: ThreadId.make("thread-1"),projectId: ProjectId.make("project-1"),@@ -50,6 +94,8 @@ describe("applyShellStreamEvent", () => {const snapshotWithProject: OrchestrationShellSnapshot = {...baseSnapshot,snapshotSequence: 4,+ bots: [],+ groups: [],projects: [stubProject],};@@ -122,6 +168,94 @@ describe("applyShellStreamEvent", () => {});});+ describe("MCP server events", () => {+ it("adds and updates an MCP server", () => {+ const added = applyShellStreamEvent(baseSnapshot, {+ kind: "mcp-server-upserted",+ sequence: 4,+ mcpServer: stubMcpServer,+ });+ const updated = applyShellStreamEvent(added, {+ kind: "mcp-server-upserted",+ sequence: 5,+ mcpServer: { ...stubMcpServer, enabled: false },+ });++ expect(updated.mcpServers).toEqual([{ ...stubMcpServer, enabled: false }]);+ expect(updated.snapshotSequence).toBe(5);+ });++ it("removes an MCP server", () => {+ const next = applyShellStreamEvent(+ { ...baseSnapshot, mcpServers: [stubMcpServer] },+ {+ kind: "mcp-server-removed",+ sequence: 6,+ mcpServerId: stubMcpServer.id,+ },+ );++ expect(next.mcpServers).toEqual([]);+ expect(next.snapshotSequence).toBe(6);+ });+ });++ describe("bot-upserted", () => {+ it("adds and updates a bot", () => {+ const added = applyShellStreamEvent(baseSnapshot, {+ kind: "bot-upserted",+ sequence: 4,+ bot: stubBot,+ });+ const updated = applyShellStreamEvent(added, {+ kind: "bot-upserted",+ sequence: 5,+ bot: { ...stubBot, name: "Pathfinder" },+ });++ expect(updated.bots).toHaveLength(1);+ expect(updated.bots[0]?.name).toBe("Pathfinder");+ expect(updated.snapshotSequence).toBe(5);+ });+ });++ describe("group-upserted", () => {+ it("adds and updates a group", () => {+ const added = applyShellStreamEvent(baseSnapshot, {+ kind: "group-upserted",+ sequence: 6,+ group: stubGroup,+ });+ const updated = applyShellStreamEvent(added, {+ kind: "group-upserted",+ sequence: 7,+ group: { ...stubGroup, name: "Discovery", members: [] },+ });++ expect(updated.groups).toHaveLength(1);+ expect(updated.groups[0]?.name).toBe("Discovery");+ expect(updated.groups[0]?.members).toEqual([]);+ expect(updated.snapshotSequence).toBe(7);+ });+ });++ describe("group-removed", () => {+ it("removes a group by id", () => {+ const snapshotWithGroup: OrchestrationShellSnapshot = {+ ...baseSnapshot,+ groups: [stubGroup],+ };+ const next = applyShellStreamEvent(snapshotWithGroup, {+ kind: "group-removed",+ sequence: 8,+ groupId: stubGroup.id,+ });++ expect(next.groups).toHaveLength(0);+ expect(next.snapshotSequence).toBe(8);+ });+ });+describe("thread-upserted", () => {it("adds a new thread", () => {const event: OrchestrationShellStreamEvent = {diff --git a/packages/client-runtime/src/state/shellReducer.ts b/packages/client-runtime/src/state/shellReducer.tsindex 3d3b22a12..fa2bd75cc 100644--- a/packages/client-runtime/src/state/shellReducer.ts+++ b/packages/client-runtime/src/state/shellReducer.ts@@ -28,6 +28,42 @@ export function applyShellStreamEvent(projects: Arr.filter(snapshot.projects, (p) => p.id !== event.projectId),snapshotSequence: event.sequence,};+ case "bot-upserted": {+ const bots = snapshot.bots.some((bot) => bot.id === event.bot.id)+ ? Arr.map(snapshot.bots, (bot) => (bot.id === event.bot.id ? event.bot : bot))+ : Arr.append(snapshot.bots, event.bot);+ return { ...snapshot, bots, snapshotSequence: event.sequence };+ }+ case "group-upserted": {+ const groups = snapshot.groups.some((group) => group.id === event.group.id)+ ? Arr.map(snapshot.groups, (group) => (group.id === event.group.id ? event.group : group))+ : Arr.append(snapshot.groups, event.group);+ return { ...snapshot, groups, snapshotSequence: event.sequence };+ }+ case "group-removed":+ return {+ ...snapshot,+ groups: Arr.filter(snapshot.groups, (group) => group.id !== event.groupId),+ snapshotSequence: event.sequence,+ };+ case "mcp-server-upserted": {+ const mcpServers = snapshot.mcpServers ?? [];+ const nextMcpServers = mcpServers.some((server) => server.id === event.mcpServer.id)+ ? Arr.map(mcpServers, (server) =>+ server.id === event.mcpServer.id ? event.mcpServer : server,+ )+ : Arr.append(mcpServers, event.mcpServer);+ return { ...snapshot, mcpServers: nextMcpServers, snapshotSequence: event.sequence };+ }+ case "mcp-server-removed":+ return {+ ...snapshot,+ mcpServers: Arr.filter(+ snapshot.mcpServers ?? [],+ (server) => server.id !== event.mcpServerId,+ ),+ snapshotSequence: event.sequence,+ };case "thread-upserted": {const threads = snapshot.threads.some((t) => t.id === event.thread.id)? Arr.map(snapshot.threads, (t) => (t.id === event.thread.id ? event.thread : t))diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.tsindex 10d5898c8..c23efc3ce 100644--- a/packages/client-runtime/src/state/threadReducer.ts+++ b/packages/client-runtime/src/state/threadReducer.ts@@ -80,6 +80,8 @@ export function applyThreadDetailEvent(thread: {id: event.payload.threadId,projectId: event.payload.projectId,+ botId: event.payload.botId ?? null,+ groupId: event.payload.groupId ?? null,title: event.payload.title,modelSelection: event.payload.modelSelection,runtimeMode: event.payload.runtimeMode,diff --git a/packages/shared/src/composerInlineTokens.test.ts b/packages/shared/src/composerInlineTokens.test.tsindex 81fd6add2..0d0f9cd8a 100644--- a/packages/shared/src/composerInlineTokens.test.ts+++ b/packages/shared/src/composerInlineTokens.test.ts@@ -68,6 +68,32 @@ describe("collectComposerInlineTokens", () => {]);});+ it("preserves a bot mention as a separate token type", () => {+ const text = "@Pathfinder";++ expect(+ collectComposerInlineTokens(text, {+ preserveTrailingFrom: [+ {+ type: "bot-mention",+ value: "bot-pathfinder",+ source: text,+ start: 0,+ end: text.length,+ },+ ],+ }),+ ).toEqual([+ {+ type: "bot-mention",+ value: "bot-pathfinder",+ source: text,+ start: 0,+ end: text.length,+ },+ ]);+ });+it("does not preserve a pill after its source is edited", () => {const confirmed = collectComposerInlineTokens("[package.json](package.json) ");diff --git a/packages/shared/src/composerInlineTokens.ts b/packages/shared/src/composerInlineTokens.tsindex 11a5accf3..d7a673589 100644--- a/packages/shared/src/composerInlineTokens.ts+++ b/packages/shared/src/composerInlineTokens.ts@@ -1,11 +1,20 @@export type ComposerInlineToken =| {+ /** A workspace path mention. Bot mentions use the separate bot-mention token. */readonly type: "mention";readonly value: string;readonly source: string;readonly start: number;readonly end: number;}+ | {+ /** A group member bot mention. `value` is the stable bot id. */+ readonly type: "bot-mention";+ readonly value: string;+ readonly source: string;+ readonly start: number;+ readonly end: number;+ }| {readonly type: "skill";readonly value: string;diff --git a/packages/shared/src/connectAuth.test.ts b/packages/shared/src/connectAuth.test.tsindex 275a958f2..8e854d780 100644--- a/packages/shared/src/connectAuth.test.ts+++ b/packages/shared/src/connectAuth.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test";import {buildConnectAuthorizeRequestUrl,buildConnectClerkAuthorizeUrl,+ checkConnectAuthCode,connectCallbackUrl,connectLoopbackRedirectUri,encodeConnectAuthCode,@@ -101,4 +102,16 @@ describe("connectAuth", () => {expect(parseConnectAuthCode(".leading")).toBeNull();expect(parseConnectAuthCode("trailing.")).toBeNull();});++ it("explains a malformed pasted code without naming a product", () => {+ const message = checkConnectAuthCode("no-separator", "state-1");++ expect(message).toBe("That does not look like a connect code. Copy the full code.");+ expect(+ checkConnectAuthCode(encodeConnectAuthCode({ code: "c1", state: "state-1" }), "state-1"),+ ).toEqual({+ code: "c1",+ state: "state-1",+ });+ });});diff --git a/packages/shared/src/connectAuth.ts b/packages/shared/src/connectAuth.tsindex e2a2af106..dbac5e5ae 100644--- a/packages/shared/src/connectAuth.ts+++ b/packages/shared/src/connectAuth.ts@@ -150,7 +150,7 @@ export function checkConnectAuthCode(): ConnectAuthCode | string {const parsed = parseConnectAuthCode(blob);if (parsed === null) {- return "That does not look like a T3 Connect code. Copy the full code.";+ return "That does not look like a connect code. Copy the full code.";}if (parsed.state !== expectedState) {return "That code belongs to a different connect request. Open the URL above and try again.";diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.tsindex 0a56e4519..c715d9cfd 100644--- a/packages/shared/src/relayClient.ts+++ b/packages/shared/src/relayClient.ts@@ -368,7 +368,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(functionif (!releaseAsset) {return yield* new RelayClientInstallError({reason: "unsupported_platform",- message: `T3 Code does not provide a managed relay client binary for ${platform}-${arch}.`,+ message: `Akeru Bot does not provide a managed relay client binary for ${platform}-${arch}.`,});}diff --git a/packages/shared/src/themePalettes.ts b/packages/shared/src/themePalettes.tsindex 919a3bfaf..bf3c17082 100644--- a/packages/shared/src/themePalettes.ts+++ b/packages/shared/src/themePalettes.ts@@ -1,4 +1,11 @@-export const BUILT_IN_THEME_IDS = ["t3-chat", "grove", "ocean", "ember", "iris"] as const;+export const BUILT_IN_THEME_IDS = [+ "akeru-paper",+ "t3-chat",+ "grove",+ "ocean",+ "ember",+ "iris",+] as const;/** The mobile app's own hand-tuned palette, which is not part of the built-in library. */export const MOBILE_DEFAULT_THEME_ID = "t3-code";@@ -727,7 +734,134 @@ export const IRIS_THEME: ThemeDefinition = {sidebarArtwork: true,};+export const AKERU_PAPER_THEME: ThemeDefinition = {+ id: "akeru-paper",+ label: "Akeru Paper",+ appearance: "light",+ colors: {+ canvas: "oklch(0.958531 0.009845 87.471)",+ chrome: "oklch(0.931632 0.012785 86.832)",+ toolbar: "oklch(0.958531 0.009845 87.471)",+ toolbarForeground: "oklch(0.274878 0.007028 67.529)",+ toolbarBorder: "oklch(0.847235 0.015219 80.702)",+ toolbarControl: "oklch(1 0 0)",+ toolbarControlForeground: "oklch(0.274878 0.007028 67.529)",+ toolbarControlHover: "oklch(0.908664 0.014962 80.705)",+ surface: "oklch(0.985526 0.005706 84.566)",+ surfaceRaised: "oklch(1 0 0)",+ surfaceOverlay: "oklch(1 0 0)",+ text: "oklch(0.274878 0.007028 67.529)",+ textMuted: "oklch(0.496285 0.012128 67.543)",+ border: "oklch(0.860421 0.015691 77.059)",+ input: "oklch(0.76072 0.017951 76.074)",+ focus: "oklch(0.607447 0.134946 296.512)",+ accent: "oklch(0.607447 0.134946 296.512)",+ accentForeground: "oklch(0.139671 0.024718 296.562)",+ secondary: "oklch(0.913953 0.014486 84.585)",+ secondaryForeground: "oklch(0.331371 0.010304 73.554)",+ muted: "oklch(0.937949 0.011528 84.579)",+ mutedForeground: "oklch(0.496285 0.012128 67.543)",+ placeholder: "oklch(0.496285 0.012128 67.543)",+ secondaryLabel: "oklch(0.496285 0.012128 67.543)",+ iconMuted: "oklch(0.496285 0.012128 67.543)",+ error: "oklch(0.542323 0.154141 26.861)",+ errorForeground: "oklch(0.443931 0.131056 26.805)",+ errorSurface: "oklch(0.931623 0.019109 29.549)",+ warning: "oklch(0.566615 0.126823 65.303)",+ warningForeground: "oklch(0.442827 0.097381 67.7)",+ warningSurface: "oklch(0.943016 0.035404 85.408)",+ update: "oklch(0.607447 0.134946 296.512)",+ updateForeground: "oklch(0.449304 0.145439 295.863)",+ updateSurface: "oklch(0.940347 0.022271 302.929)",+ accentSurface: "oklch(0.912658 0.033973 304.531)",+ accentSurfaceForeground: "oklch(0.449304 0.145439 295.863)",+ messageSurface: "oklch(0.945777 0.019688 305.262)",+ messageForeground: "oklch(0.274878 0.007028 67.529)",+ messageAction: "oklch(0.607447 0.134946 296.512)",+ messageActionForeground: "oklch(0.139671 0.024718 296.562)",+ messageActionHover: "oklch(0.656453 0.13742 297.344)",+ codeBackground: "oklch(0.931901 0.011546 84.579)",+ codeForeground: "oklch(0.274878 0.007028 67.529)",+ sidebar: "oklch(0.931632 0.012785 86.832)",+ sidebarForeground: "oklch(0.274878 0.007028 67.529)",+ sidebarMutedForeground: "oklch(0.496285 0.012128 67.543)",+ sidebarControlSurface: "oklch(0.970803 0.008582 84.573)",+ sidebarRowHover: "oklch(0.958531 0.009845 87.471)",+ sidebarRowActive: "oklch(1 0 0)",+ sidebarRowSelected: "oklch(1 0 0)",+ sidebarBorder: "oklch(0.860421 0.015691 77.059)",+ terminalBackground: "oklch(0.249565 0.003571 48.579)",+ terminalForeground: "oklch(0.950015 0.011492 84.579)",+ terminalCursor: "oklch(0.607447 0.134946 296.512)",+ terminalSelection: "oklch(0.912658 0.033973 304.531)",+ terminalScrollbar: "oklch(0.459577 0.01156 72.528)",+ terminalScrollbarHover: "oklch(0.551879 0.013009 71.789)",+ },+ variants: {+ dark: {+ canvas: "oklch(0.114918 0 0)",+ chrome: "oklch(0.177638 0 0)",+ toolbar: "oklch(0.114918 0 0)",+ toolbarForeground: "oklch(0.967434 0.001326 286.375)",+ toolbarBorder: "oklch(0.28908 0 0)",+ toolbarControl: "oklch(0.222129 0 0)",+ toolbarControlForeground: "oklch(0.967434 0.001326 286.375)",+ toolbarControlHover: "oklch(0.268618 0 0)",+ surface: "oklch(0.209036 0 0)",+ surfaceRaised: "oklch(0.305191 0 0)",+ surfaceOverlay: "oklch(0.177638 0 0)",+ text: "oklch(0.967434 0.001326 286.375)",+ textMuted: "oklch(0.711815 0.012937 286.067)",+ border: "oklch(0.28908 0 0)",+ input: "oklch(0.370323 0.01188 285.805)",+ focus: "oklch(0.607447 0.134946 296.512)",+ accent: "oklch(0.607447 0.134946 296.512)",+ accentForeground: "oklch(0.139671 0.024718 296.562)",+ secondary: "oklch(0.268618 0 0)",+ secondaryForeground: "oklch(0.967434 0.001326 286.375)",+ muted: "oklch(0.222129 0 0)",+ mutedForeground: "oklch(0.711815 0.012937 286.067)",+ placeholder: "oklch(0.711815 0.012937 286.067)",+ secondaryLabel: "oklch(0.711815 0.012937 286.067)",+ iconMuted: "oklch(0.711815 0.012937 286.067)",+ error: "oklch(0.665241 0.148078 26.77)",+ errorForeground: "oklch(0.772758 0.103326 25.58)",+ errorSurface: "oklch(0.289862 0.032452 25.297)",+ warning: "oklch(0.758152 0.10943 78.772)",+ warningForeground: "oklch(0.855925 0.082896 82.001)",+ warningSurface: "oklch(0.309837 0.024833 79.663)",+ update: "oklch(0.607447 0.134946 296.512)",+ updateForeground: "oklch(0.80327 0.077482 299.92)",+ updateSurface: "oklch(0.269917 0.050751 301.875)",+ accentSurface: "oklch(0.268618 0 0)",+ accentSurfaceForeground: "oklch(0.967434 0.001326 286.375)",+ messageSurface: "oklch(0.370323 0.01188 285.805)",+ messageForeground: "oklch(0.967434 0.001326 286.375)",+ messageAction: "oklch(0.607447 0.134946 296.512)",+ messageActionForeground: "oklch(0.139671 0.024718 296.562)",+ messageActionHover: "oklch(0.656453 0.13742 297.344)",+ codeBackground: "oklch(0.177638 0 0)",+ codeForeground: "oklch(0.967434 0.001326 286.375)",+ sidebar: "oklch(0.177638 0 0)",+ sidebarForeground: "oklch(0.967434 0.001326 286.375)",+ sidebarMutedForeground: "oklch(0.711815 0.012937 286.067)",+ sidebarControlSurface: "oklch(0.222129 0 0)",+ sidebarRowHover: "oklch(0.243535 0 0)",+ sidebarRowActive: "oklch(0.268618 0 0)",+ sidebarRowSelected: "oklch(0.28908 0 0)",+ sidebarBorder: "oklch(0.28908 0 0)",+ terminalBackground: "oklch(0.114918 0 0)",+ terminalForeground: "oklch(0.967434 0.001326 286.375)",+ terminalCursor: "oklch(0.656453 0.13742 297.344)",+ terminalSelection: "oklch(0.358238 0.073841 303.758)",+ terminalScrollbar: "oklch(0.321093 0 0)",+ terminalScrollbarHover: "oklch(0.4 0 0)",+ },+ },+};+export const BUILT_IN_THEMES: ReadonlyArray<ThemeDefinition> = [+ AKERU_PAPER_THEME,T3_CHAT_THEME,GROVE_THEME,OCEAN_THEME,diff --git a/packages/shared/src/usageMerge.ts b/packages/shared/src/usageMerge.tsindex 954139b4e..1b79f5a7c 100644--- a/packages/shared/src/usageMerge.ts+++ b/packages/shared/src/usageMerge.ts@@ -8,8 +8,10 @@*/import type {EnvironmentId,+ SubscriptionProviderId,UsageBucket,UsageProviderKind,+ UsageProviderPlanLimits,UsageSourceFingerprint,UsageSummary,} from "@t3tools/contracts";@@ -80,6 +82,7 @@ export interface MergedUsage {readonly duplicateSources: readonly string[];readonly contributingEnvironments: readonly EnvironmentId[];readonly staleEnvironments: readonly EnvironmentId[];+ readonly planLimits: readonly UsageProviderPlanLimits[];}/**@@ -195,6 +198,7 @@ const EMPTY_MERGED: MergedUsage = {duplicateSources: [],contributingEnvironments: [],staleEnvironments: [],+ planLimits: [],};/**@@ -413,5 +417,21 @@ export function mergeUsage(duplicateSources: duplicates,contributingEnvironments,staleEnvironments,+ planLimits: mergePlanLimits(current),};}++function mergePlanLimits(+ environments: readonly EnvironmentUsage[],+): readonly UsageProviderPlanLimits[] {+ const byProvider = new Map<SubscriptionProviderId, UsageProviderPlanLimits>();+ for (const environment of environments) {+ for (const limits of environment.summary.planLimits ?? []) {+ const existing = byProvider.get(limits.provider);+ if (existing === undefined || (existing.status !== "ok" && limits.status === "ok")) {+ byProvider.set(limits.provider, limits);+ }+ }+ }+ return [...byProvider.values()];+}diff --git a/plugins/catalog.test.ts b/plugins/catalog.test.tsnew file mode 100644index 000000000..14c11e142--- /dev/null+++ b/plugins/catalog.test.ts@@ -0,0 +1,93 @@+import * as NodeFS from "node:fs";+import { describe, expect, it } from "vite-plus/test";++import context from "./context";+import { loadCatalog } from "./index";++const CATALOG_IDS = ["context", "exa", "executor", "firecrawl", "parallel-search"];+const DISALLOWED_ID_PART = ["pipe", "dream"].join("");++describe("plugin catalog", () => {+ it("loads the focused builtin catalog with unique launch recipes", () => {+ const catalog = loadCatalog();+ const ids = catalog.map((plugin) => plugin.id);+ expect(ids.toSorted()).toEqual(CATALOG_IDS);+ expect(new Set(ids).size).toBe(catalog.length);+ expect(ids.some((id) => id.includes(DISALLOWED_ID_PART))).toBe(false);+ for (const plugin of catalog) {+ expect(plugin.builtin).toBe(true);+ expect(plugin.featured).toBe(true);+ expect(plugin.title.trim()).not.toBe("");+ expect(plugin.description.trim()).not.toBe("");+ expect(plugin.category.trim()).not.toBe("");+ expect(+ NodeFS.existsSync(new URL(`../apps/web/public${plugin.logo.src}`, import.meta.url)),+ ).toBe(true);+ if (plugin.logo.darkSrc) {+ expect(+ NodeFS.existsSync(new URL(`../apps/web/public${plugin.logo.darkSrc}`, import.meta.url)),+ ).toBe(true);+ }+ if (plugin.docsUrl) expect(plugin.docsUrl).toMatch(/^https:\/\//);+ for (const skill of plugin.skills ?? []) {+ expect(skill.title.trim()).not.toBe("");+ expect(skill.description.trim()).not.toBe("");+ expect(skill.url).toMatch(/^https:\/\/skills\.sh\//);+ }+ if (plugin.kind === "mcp-url") {+ expect(plugin.url).toMatch(/^https:\/\//);+ expect(["none", "oauth", "optional-oauth"]).toContain(plugin.authentication);+ } else {+ expect(plugin.command.trim()).not.toBe("");+ }+ }+ });++ it("keeps the verified hosted services in focused sections", () => {+ const byId = new Map(loadCatalog().map((plugin) => [plugin.id, plugin]));++ expect(byId.get("context")).toMatchObject({+ category: "Data Extraction",+ url: "https://mcp.context.dev/mcp",+ authentication: "oauth",+ });+ expect(byId.get("firecrawl")).toMatchObject({+ category: "Data Extraction",+ url: "https://mcp.firecrawl.dev/v2/mcp-oauth",+ authentication: "oauth",+ });+ expect(byId.get("exa")).toMatchObject({+ category: "Search",+ url: "https://mcp.exa.ai/mcp",+ authentication: "optional-oauth",+ });+ expect(byId.get("parallel-search")).toMatchObject({+ category: "Search",+ url: "https://search.parallel.ai/mcp-oauth",+ authentication: "oauth",+ });+ expect(byId.get("executor")).toMatchObject({+ category: "Productivity",+ command: "bunx",+ args: ["-y", "executor", "mcp"],+ });+ expect(byId.get("firecrawl")?.skills?.[0]?.url).toBe(+ "https://skills.sh/firecrawl/cli/firecrawl",+ );+ expect(byId.get("exa")?.skills?.[0]?.url).toBe(+ "https://skills.sh/exa-labs/agent-skills/exa-search",+ );+ expect(byId.get("parallel-search")?.skills?.[0]?.url).toBe(+ "https://skills.sh/parallel-web/parallel-agent-skills/parallel-web-search",+ );+ });++ it("rejects duplicate ids", () => {+ expect(() =>+ loadCatalog({+ "./context.ts": { default: context },+ "./context-copy.ts": { default: context },+ }),+ ).toThrow("Duplicate plugin id 'context'");+ });+});diff --git a/plugins/context.ts b/plugins/context.tsnew file mode 100644index 000000000..07eb12cca--- /dev/null+++ b/plugins/context.ts@@ -0,0 +1,18 @@+import { definePlugin } from "./definePlugin";++export default definePlugin({+ id: "context",+ title: "Context.dev",+ description: "Scrape, extract, parse, enrich, and monitor web data.",+ category: "Data Extraction",+ logo: {+ src: "/plugin-logos/context.png",+ darkSrc: "/plugin-logos/context-dark.png",+ },+ featured: true,+ kind: "mcp-url",+ authentication: "oauth",+ url: "https://mcp.context.dev/mcp",+ docsUrl: "https://docs.context.dev/install-mcp",+ builtin: true,+});diff --git a/plugins/definePlugin.ts b/plugins/definePlugin.tsnew file mode 100644index 000000000..017cef724--- /dev/null+++ b/plugins/definePlugin.ts@@ -0,0 +1,80 @@+export type PluginKind = "mcp-stdio" | "mcp-url";++export const PLUGIN_CATEGORIES = ["Data Extraction", "Search", "Productivity"] as const;++export type PluginCategory = (typeof PLUGIN_CATEGORIES)[number];++export interface PluginLogo {+ readonly src: `/plugin-logos/${string}`;+ readonly darkSrc?: `/plugin-logos/${string}`;+}++export interface PluginSkill {+ readonly title: string;+ readonly description: string;+ readonly url: `https://${string}`;+}++interface PluginBase {+ readonly id: string;+ readonly title: string;+ readonly description: string;+ readonly category: PluginCategory;+ readonly logo: PluginLogo;+ readonly featured?: true;+ readonly docsUrl?: string;+ readonly skills?: readonly PluginSkill[];+ readonly builtin: true;+}++interface CommandPlugin extends PluginBase {+ readonly kind: "mcp-stdio";+ readonly command: string;+ readonly args?: readonly string[];+ readonly url?: never;+}++interface UrlPlugin extends PluginBase {+ readonly kind: "mcp-url";+ readonly url: string;+ readonly authentication: "none" | "oauth" | "optional-oauth";+ readonly command?: never;+ readonly args?: never;+}++export type PluginDefinition = CommandPlugin | UrlPlugin;++const PLUGIN_ID = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;+const DISALLOWED_PROVIDER = ["pipe", "dream"].join("");++export function definePlugin<const T extends PluginDefinition>(plugin: T): Readonly<T> {+ if (!PLUGIN_ID.test(plugin.id)) {+ throw new TypeError(`Plugin id '${plugin.id}' must use stable kebab-case.`);+ }+ if (plugin.id.includes(DISALLOWED_PROVIDER)) {+ throw new TypeError(`Plugin id '${plugin.id}' names an unsupported provider.`);+ }+ if (!plugin.logo.src.startsWith("/plugin-logos/")) {+ throw new TypeError(`Plugin '${plugin.id}' needs a local logo.`);+ }+ if (plugin.title.trim().length === 0 || plugin.description.trim().length === 0) {+ throw new TypeError(`Plugin '${plugin.id}' needs a title and description.`);+ }+ for (const skill of plugin.skills ?? []) {+ if (skill.title.trim().length === 0 || skill.description.trim().length === 0) {+ throw new TypeError(`Plugin '${plugin.id}' has an incomplete skill.`);+ }+ if (new URL(skill.url).protocol !== "https:") {+ throw new TypeError(`Plugin '${plugin.id}' skill URLs must use HTTPS.`);+ }+ }+ if (plugin.kind === "mcp-url") {+ const url = new URL(plugin.url);+ if (url.protocol !== "http:" && url.protocol !== "https:") {+ throw new TypeError(`Plugin '${plugin.id}' needs an HTTP or HTTPS URL.`);+ }+ } else if (plugin.command.trim().length === 0) {+ throw new TypeError(`Plugin '${plugin.id}' needs a command.`);+ }+ return Object.freeze(plugin);+}diff --git a/plugins/exa.ts b/plugins/exa.tsnew file mode 100644index 000000000..0edcd513f--- /dev/null+++ b/plugins/exa.ts@@ -0,0 +1,22 @@+import { definePlugin } from "./definePlugin";++export default definePlugin({+ id: "exa",+ title: "Exa",+ description: "Search the web, find code, and run focused research.",+ category: "Search",+ logo: { src: "/plugin-logos/exa.svg" },+ featured: true,+ kind: "mcp-url",+ authentication: "optional-oauth",+ url: "https://mcp.exa.ai/mcp",+ docsUrl: "https://exa.ai/mcp",+ skills: [+ {+ title: "Exa Search",+ description: "Search the web through the Exa CLI.",+ url: "https://skills.sh/exa-labs/agent-skills/exa-search",+ },+ ],+ builtin: true,+});diff --git a/plugins/executor.ts b/plugins/executor.tsnew file mode 100644index 000000000..0742743bf--- /dev/null+++ b/plugins/executor.ts@@ -0,0 +1,15 @@+import { definePlugin } from "./definePlugin";++export default definePlugin({+ id: "executor",+ title: "Executor",+ description: "Use the integrations configured in your local Executor account.",+ category: "Productivity",+ logo: { src: "/plugin-logos/mcp.svg", darkSrc: "/plugin-logos/mcp-dark.svg" },+ featured: true,+ kind: "mcp-stdio",+ command: "bunx",+ args: ["-y", "executor", "mcp"],+ docsUrl: "https://executor.sh/docs",+ builtin: true,+});diff --git a/plugins/firecrawl.ts b/plugins/firecrawl.tsnew file mode 100644index 000000000..42cb27f3e--- /dev/null+++ b/plugins/firecrawl.ts@@ -0,0 +1,25 @@+import { definePlugin } from "./definePlugin";++export default definePlugin({+ id: "firecrawl",+ title: "Firecrawl",+ description: "Search, scrape, and extract structured data from the web.",+ category: "Data Extraction",+ logo: {+ src: "/plugin-logos/firecrawl.svg",+ darkSrc: "/plugin-logos/firecrawl-dark.svg",+ },+ featured: true,+ kind: "mcp-url",+ authentication: "oauth",+ url: "https://mcp.firecrawl.dev/v2/mcp-oauth",+ docsUrl: "https://docs.firecrawl.dev/mcp-server/oauth",+ skills: [+ {+ title: "Firecrawl CLI",+ description: "Search, scrape, crawl, and extract through the Firecrawl CLI.",+ url: "https://skills.sh/firecrawl/cli/firecrawl",+ },+ ],+ builtin: true,+});diff --git a/plugins/index.ts b/plugins/index.tsnew file mode 100644index 000000000..ab2c77cee--- /dev/null+++ b/plugins/index.ts@@ -0,0 +1,35 @@+import type { PluginDefinition } from "./definePlugin";++interface PluginModule {+ readonly default: PluginDefinition;+}++const catalogModules = import.meta.glob<PluginModule>(+ ["./*.ts", "!./definePlugin.ts", "!./index.ts", "!./*.test.ts"],+ { eager: true },+);++export function loadCatalog(+ modules: Readonly<Record<string, PluginModule>> = catalogModules,+): readonly PluginDefinition[] {+ const plugins = Object.entries(modules).map(([path, module]) => {+ if (!module.default)+ throw new TypeError(`Plugin module '${path}' must export a default plugin.`);+ return module.default;+ });+ const ids = new Set<string>();+ for (const plugin of plugins) {+ if (ids.has(plugin.id)) throw new TypeError(`Duplicate plugin id '${plugin.id}'.`);+ ids.add(plugin.id);+ }+ return Object.freeze(plugins.toSorted((left, right) => left.title.localeCompare(right.title)));+}++export { PLUGIN_CATEGORIES } from "./definePlugin";+export type {+ PluginCategory,+ PluginDefinition,+ PluginKind,+ PluginLogo,+ PluginSkill,+} from "./definePlugin";diff --git a/plugins/parallel-search.ts b/plugins/parallel-search.tsnew file mode 100644index 000000000..1e2747269--- /dev/null+++ b/plugins/parallel-search.ts@@ -0,0 +1,22 @@+import { definePlugin } from "./definePlugin";++export default definePlugin({+ id: "parallel-search",+ title: "Parallel Search",+ description: "Search the web and extract token-efficient content from URLs.",+ category: "Search",+ logo: { src: "/plugin-logos/parallel.svg" },+ featured: true,+ kind: "mcp-url",+ authentication: "oauth",+ url: "https://search.parallel.ai/mcp-oauth",+ docsUrl: "https://docs.parallel.ai/integrations/mcp/search-mcp",+ skills: [+ {+ title: "Parallel Web Search",+ description: "Run ranked web searches through the Parallel CLI.",+ url: "https://skills.sh/parallel-web/parallel-agent-skills/parallel-web-search",+ },+ ],+ builtin: true,+});