Compare commits

..
Author SHA1 Message Date
t3-code[bot] 6049fbea6c test(web): remove duplicate orchestration recovery test 2026-08-12 02:23:36 +00:00
maria 63e6faef62 chore: add dara to vouched (#6259) 2026-08-11 21:51:00 -04:00
Chris Deeming d37a9b09b8 feat(mobile): add thread title regeneration (#6253) 2026-08-11 21:43:05 -04:00
Exotic 560d4a4560 fix(web): keep sidebar wordmark visible at minimum width (#6246) 2026-08-11 19:57:10 -04:00
maria 52e5a75a87 feat(web): compact sidebar footer actions (#6210) 2026-08-11 18:53:40 -04:00
Exotic c196f422ed fix(web): clean up composer resize animation (#6209) 2026-08-11 23:21:44 +02:00
f0b57ca231 feat(web): add Open VSX theme search (#5654)
Co-authored-by: Julius Marminge <[email protected]>
Co-authored-by: codex <[email protected]>
2026-08-11 20:06:05 +00:00
t3-code[bot] 2db08457f2 fix(web): use upload icon for disabled push action (#6207) 2026-08-11 20:25:24 +02:00
Wout Stiens 083fa4ab24 feat(web): use OKLCH for theme palettes (#6036) 2026-08-11 20:00:17 +02:00
Exotic 35172010b1 fix(web): use a clearer pull action icon (#6194) 2026-08-11 16:39:59 +00:00
Mina Yacoub 57b1052679 fix(web): thread error banner dismiss survives reconnect and rerenders (#6123) 2026-08-11 12:27:55 -04:00
1e355a2a34 fix(web): render dropdowns above toasts (#6165)
Co-authored-by: Rodrigo Brechard <[email protected]>
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
2026-08-11 12:27:02 -04:00
Utkarsh Patilandshivam 44621c345f feat(web): add back buttons for the pull requests and usage pages in the sidebar footer (#6031)
Co-authored-by: shivam <[email protected]>
2026-08-11 12:26:24 -04:00
Arham AminandClaude Opus 4.8 220e573b14 fix(shared): detect Azure DevOps SSH remotes (ssh.dev.azure.com) (#6187)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-11 16:14:02 +00:00
47 changed files with 4284 additions and 803 deletions

No files matched your search

+1
View File
@@ -37,3 +37,4 @@ github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
github:SunkenInTime
@@ -45,6 +45,7 @@ export function HomeRouteScreen() {
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
unsettleThread,
} = useThreadListActions();
const pendingTasks = usePendingNewTasks();
@@ -186,6 +187,7 @@ export function HomeRouteScreen() {
onPinThread={pinThread}
onUnpinThread={unpinThread}
onMovePinnedThread={movePinnedThread}
onRegenerateThreadTitle={regenerateThreadTitle}
onEnvironmentChange={setSelectedEnvironmentId}
onProjectChange={setSelectedProjectKey}
onOpenSettings={() =>
@@ -115,6 +115,7 @@ interface HomeScreenProps {
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
readonly onSelectPendingTask: (pendingTask: PendingNewTask) => void;
readonly onDeletePendingTask: (pendingTask: PendingNewTask) => void;
readonly onNewThreadInProject: (project: EnvironmentProject) => void;
@@ -538,6 +539,12 @@ export function HomeScreen(props: HomeScreenProps) {
},
[props.onUnpinThread],
);
const handleRegenerateThreadTitle = useCallback(
(thread: EnvironmentThreadShell) => {
void props.onRegenerateThreadTitle(thread);
},
[props.onRegenerateThreadTitle],
);
const handleDeleteThread = props.onDeleteThread;
const handleUnsettleThread = props.onUnsettleThread;
// The settled tail renders in pages; expansion resets when the filter
@@ -615,6 +622,15 @@ export function HomeScreen(props: HomeScreenProps) {
}
return supported;
}, [serverConfigs]);
const titleRegenerationEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadTitleRegeneration === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order (reorder-capable threads only) for the
// Move up/down position flags. Computed from all shells, not the rendered
// list, so search/scope filtering never disables or misdirects a move.
@@ -811,6 +827,8 @@ export function HomeScreen(props: HomeScreenProps) {
onSelectThread={props.onSelectThread}
onDeleteThread={handleDeleteThread}
onArchiveThread={props.onArchiveThread}
onRegenerateThreadTitle={handleRegenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={handleSettleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
@@ -842,6 +860,7 @@ export function HomeScreen(props: HomeScreenProps) {
arrangedPinnedKeys,
handleMovePinnedThread,
handlePinThread,
handleRegenerateThreadTitle,
handleSettleThread,
handleSnoozeThread,
handleUnpinThread,
@@ -863,6 +882,7 @@ export function HomeScreen(props: HomeScreenProps) {
snoozeEnvironmentIds,
threadListV2Items,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
toggleSettledShelf,
toggleSnoozedShelf,
v2ProjectTitleByProjectKey,
@@ -967,6 +987,8 @@ export function HomeScreen(props: HomeScreenProps) {
searchQuery={props.searchQuery}
onArchiveThread={props.onArchiveThread}
onDeleteThread={props.onDeleteThread}
onRegenerateThreadTitle={handleRegenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={props.onSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -988,6 +1010,7 @@ export function HomeScreen(props: HomeScreenProps) {
[
handleSwipeableClose,
handleSwipeableWillOpen,
handleRegenerateThreadTitle,
projectCwdByKey,
props.onArchiveThread,
props.onDeletePendingTask,
@@ -998,6 +1021,7 @@ export function HomeScreen(props: HomeScreenProps) {
props.searchQuery,
props.savedConnectionsById,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
updateGroupDisplay,
],
);
@@ -48,6 +48,15 @@ function environmentSupportsPinReorder(environmentId: EnvironmentThreadShell["en
);
}
function environmentSupportsTitleRegeneration(
environmentId: EnvironmentThreadShell["environmentId"],
) {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadTitleRegeneration === true
);
}
type ThreadListAction = "archive" | "unarchive" | "delete" | "settle" | "unsettle";
const ACTION_VERBS: Record<ThreadListAction, string> = {
@@ -227,13 +236,18 @@ export function useThreadListActions(): {
thread: EnvironmentThreadShell,
direction: "up" | "down",
) => Promise<boolean>;
readonly regenerateThreadTitle: (thread: EnvironmentThreadShell) => Promise<boolean>;
} {
const executeAction = useThreadActionExecutor();
const snoozeMutation = useAtomCommand(threadEnvironment.snooze, { reportFailure: false });
const unsnoozeMutation = useAtomCommand(threadEnvironment.unsnooze, { reportFailure: false });
const pinMutation = useAtomCommand(threadEnvironment.pin, { reportFailure: false });
const unpinMutation = useAtomCommand(threadEnvironment.unpin, { reportFailure: false });
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
const snoozeInFlightThreadKeys = useRef(new Set<string>());
const titleRegenerationInFlightThreadKeys = useRef(new Set<string>());
const archiveThread = useCallback(
(thread: EnvironmentThreadShell) => {
@@ -405,6 +419,47 @@ export function useThreadListActions(): {
},
[unpinMutation],
);
const regenerateThreadTitle = useCallback(
async (thread: EnvironmentThreadShell) => {
const key = scopedThreadKey(thread.environmentId, thread.id);
if (
thread.titleRegeneration != null ||
titleRegenerationInFlightThreadKeys.current.has(key)
) {
return false;
}
if (!environmentSupportsTitleRegeneration(thread.environmentId)) {
Alert.alert(
"Could not regenerate title",
"This environment's server does not support title regeneration yet. Update the server to regenerate thread titles.",
);
return false;
}
titleRegenerationInFlightThreadKeys.current.add(key);
selectionHaptic();
try {
const result = await updateThreadMetadata({
environmentId: thread.environmentId,
input: { threadId: thread.id, regenerateTitle: true },
});
if (result._tag === "Failure") {
const error = Cause.squash(result.cause);
Alert.alert(
"Could not regenerate title",
error instanceof Error && error.message.trim().length > 0
? error.message
: "The thread title could not be regenerated.",
);
return false;
}
return true;
} finally {
titleRegenerationInFlightThreadKeys.current.delete(key);
}
},
[updateThreadMetadata],
);
// Move up / Move down for the pinned block. Computed against the CANONICAL
// keyed pinned order (not the rendered list), so the move is valid even
@@ -497,6 +552,7 @@ export function useThreadListActions(): {
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
};
}
@@ -211,6 +211,7 @@ function ThreadNavigationSidebarPane(
pinThread,
unpinThread,
movePinnedThread,
regenerateThreadTitle,
} = useThreadListActions();
const threadListV2Enabled = useThreadListV2Enabled();
const pendingTasks = usePendingNewTasks();
@@ -505,6 +506,15 @@ function ThreadNavigationSidebarPane(
}
return supported;
}, [serverConfigs]);
const titleRegenerationEnvironmentIds = useMemo(() => {
const supported = new Set<EnvironmentId>();
for (const [environmentId, config] of serverConfigs) {
if (config.environment.capabilities.threadTitleRegeneration === true) {
supported.add(environmentId);
}
}
return supported;
}, [serverConfigs]);
// Canonical arranged pinned order for Move up/down flags — computed from
// all shells so search/scope filtering never disables a valid move.
const arrangedPinnedKeys = useMemo(() => {
@@ -950,6 +960,8 @@ function ThreadNavigationSidebarPane(
onSelectThread={handleSelectThread}
onDeleteThread={confirmDeleteThread}
onArchiveThread={archiveThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
settlementSupported={settlementEnvironmentIds.has(thread.environmentId)}
onSettleThread={settleThread}
snoozeSupported={snoozeEnvironmentIds.has(thread.environmentId)}
@@ -1067,6 +1079,8 @@ function ThreadNavigationSidebarPane(
fullSwipeWidth={props.width - 20}
onArchiveThread={archiveThread}
onDeleteThread={confirmDeleteThread}
onRegenerateThreadTitle={regenerateThreadTitle}
titleRegenerationSupported={titleRegenerationEnvironmentIds.has(thread.environmentId)}
onSelectThread={handleSelectThread}
onSwipeableClose={handleSwipeableClose}
onSwipeableWillOpen={handleSwipeableWillOpen}
@@ -1103,6 +1117,7 @@ function ThreadNavigationSidebarPane(
projectByKey,
projectCwdByKey,
projectTitleByProjectKey,
regenerateThreadTitle,
props.onNewThreadInProject,
props.searchQuery,
props.selectedThreadKey,
@@ -1110,6 +1125,7 @@ function ThreadNavigationSidebarPane(
savedConnectionsById,
serverConfigs,
threadSearchMatchByKey,
titleRegenerationEnvironmentIds,
settleThread,
settlementEnvironmentIds,
showMoreSettled,
@@ -22,6 +22,7 @@ import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr, type ThreadPr } from "../../state/use-thread-pr";
import type { HomeGroupDisplayAction } from "../home/homeListItems";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import { resolveThreadStatus } from "./threadPresentation";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
@@ -430,6 +431,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onArchiveThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
readonly titleRegenerationSupported: boolean;
readonly onSwipeableWillOpen: (methods: SwipeableMethods) => void;
readonly onSwipeableClose: (methods: SwipeableMethods) => void;
readonly simultaneousSwipeGesture?: ComponentProps<
@@ -451,7 +454,8 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const pressedBackgroundColor = useThemeColor("--color-subtle");
const selectedBackgroundColor = useThemeColor("--color-user-bubble");
const { thread, onSelectThread, onArchiveThread, onDeleteThread } = props;
const { thread, onSelectThread, onArchiveThread, onDeleteThread, onRegenerateThreadTitle } =
props;
const status = resolveThreadStatus(thread);
const pr = useThreadPr(thread, props.projectCwd);
const timestamp = relativeTime(
@@ -471,6 +475,21 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleArchive = useCallback(() => onArchiveThread(thread), [onArchiveThread, thread]);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
);
const menuActions = useMemo<MenuAction[]>(
() => [
THREAD_ROW_MENU_ACTIONS[0]!,
...buildThreadTitleRegenerationMenuItems({
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
THREAD_ROW_MENU_ACTIONS[1]!,
],
[props.titleRegenerationSupported, thread.titleRegeneration],
);
const primaryAction = useMemo(
() => ({
accessibilityLabel: `Archive ${thread.title}`,
@@ -483,9 +502,10 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
},
[handleArchive, handleDelete],
[handleArchive, handleDelete, handleRegenerateTitle],
);
const statusPill = effectiveStatus ? (
@@ -674,7 +694,7 @@ export const ThreadListRow = memo(function ThreadListRow(props: {
// ControlPillMenu injects onLongPress into the row and anchors the
// token-styled dropdown to it; taps and swipes are untouched.
<ControlPillMenu
actions={THREAD_ROW_MENU_ACTIONS}
actions={menuActions}
onPressAction={handleMenuAction}
shouldOpenOnLongPress
>
@@ -27,6 +27,7 @@ import { useThemeColor } from "../../lib/useThemeColor";
import type { PendingNewTask } from "../../state/use-pending-new-tasks";
import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
@@ -65,8 +66,8 @@ function threadTimeLabel(thread: EnvironmentThreadShell): string {
return relativeTime(thread.latestUserMessageAt ?? thread.updatedAt ?? thread.createdAt);
}
// Menus stay lifecycle-focused: settle/un-settle plus delete. Archive keeps
// its own surface (thread screen / settings) rather than crowding the row.
// Menus keep lifecycle and title regeneration together. Archive keeps its
// own surface (thread screen / settings) rather than crowding v2 rows.
const CARD_MENU_ACTIONS: MenuAction[] = [
{ id: "settle", title: "Settle", image: "checkmark" },
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
@@ -341,6 +342,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly fullSwipeWidth?: number;
readonly onSelectThread: (thread: EnvironmentThreadShell) => void;
readonly onDeleteThread: (thread: EnvironmentThreadShell) => void;
readonly onRegenerateThreadTitle: (thread: EnvironmentThreadShell) => void;
readonly onSettleThread: (thread: EnvironmentThreadShell) => void;
readonly onSnoozeThread: (thread: EnvironmentThreadShell, snoozedUntil: string) => void;
readonly onUnsnoozeThread: (thread: EnvironmentThreadShell) => void;
@@ -355,6 +357,8 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
readonly snoozeSupported: boolean;
/** False on servers that predate thread.pin/unpin. */
readonly pinningSupported: boolean;
/** False on servers that predate thread title regeneration. */
readonly titleRegenerationSupported: boolean;
/** False on servers that predate thread.pin.reorder. Gates the pinned
Move up / Move down menu items. */
readonly pinReorderSupported?: boolean;
@@ -384,6 +388,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
variant,
onSelectThread,
onDeleteThread,
onRegenerateThreadTitle,
onSettleThread,
onSnoozeThread,
onUnsnoozeThread,
@@ -417,6 +422,10 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const timeLabel = threadTimeLabel(thread);
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
const handleRegenerateTitle = useCallback(
() => onRegenerateThreadTitle(thread),
[onRegenerateThreadTitle, thread],
);
const handleSettle = useCallback(() => onSettleThread(thread), [onSettleThread, thread]);
const handleSnooze = useCallback(
(snoozedUntil: string) => onSnoozeThread(thread, snoozedUntil),
@@ -506,6 +515,14 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
props.pinningSupported,
],
);
const titleRegenerationMenuItems = useMemo<MenuAction[]>(
() =>
buildThreadTitleRegenerationMenuItems({
supported: props.titleRegenerationSupported,
isRegenerating: thread.titleRegeneration != null,
}),
[props.titleRegenerationSupported, thread.titleRegeneration],
);
const snoozableCardMenuActions = useMemo<MenuAction[]>(
() => [
{ id: "settle", title: "Settle", image: "checkmark" },
@@ -516,13 +533,31 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
subactions: snoozePresetActions,
},
...pinMenuItem,
...titleRegenerationMenuItems,
{ id: "delete", title: "Delete", image: "trash", attributes: { destructive: true } },
],
[pinMenuItem, snoozePresetActions],
[pinMenuItem, snoozePresetActions, titleRegenerationMenuItems],
);
const cardMenuActions = useMemo<MenuAction[]>(
() => [CARD_MENU_ACTIONS[0]!, ...pinMenuItem, ...CARD_MENU_ACTIONS.slice(1)],
[pinMenuItem],
() => [
CARD_MENU_ACTIONS[0]!,
...pinMenuItem,
...titleRegenerationMenuItems,
...CARD_MENU_ACTIONS.slice(1),
],
[pinMenuItem, titleRegenerationMenuItems],
);
const slimMenuActions = useMemo<MenuAction[]>(
() => [SLIM_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SLIM_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const snoozedMenuActions = useMemo<MenuAction[]>(
() => [SNOOZED_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, SNOOZED_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const legacyMenuActions = useMemo<MenuAction[]>(
() => [LEGACY_MENU_ACTIONS[0]!, ...titleRegenerationMenuItems, LEGACY_MENU_ACTIONS[1]!],
[titleRegenerationMenuItems],
);
const handleMenuAction = useCallback(
({ nativeEvent }: { readonly nativeEvent: { readonly event: string } }) => {
@@ -534,6 +569,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
if (nativeEvent.event === "move-pin-up") handleMovePinnedUp();
if (nativeEvent.event === "move-pin-down") handleMovePinnedDown();
if (nativeEvent.event === "archive") handleArchive();
if (nativeEvent.event === "regenerate-title") handleRegenerateTitle();
if (nativeEvent.event === "delete") handleDelete();
const snoozeSelection = resolveThreadListV2SnoozeMenuSelection({
event: nativeEvent.event,
@@ -549,6 +585,7 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
[
handleArchive,
handleDelete,
handleRegenerateTitle,
handleMovePinnedDown,
handleMovePinnedUp,
handlePin,
@@ -890,11 +927,11 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
<ControlPillMenu
actions={
snoozedRow
? SNOOZED_MENU_ACTIONS
? snoozedMenuActions
: !props.settlementSupported
? LEGACY_MENU_ACTIONS
? legacyMenuActions
: canUnsettle
? SLIM_MENU_ACTIONS
? slimMenuActions
: swipeActions.secondary === "snooze"
? snoozableCardMenuActions
: cardMenuActions
@@ -0,0 +1,36 @@
import { describe, expect, it } from "vite-plus/test";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
describe("buildThreadTitleRegenerationMenuItems", () => {
it("hides regeneration when the environment does not advertise support", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: false, isRegenerating: false }),
).toEqual([]);
});
it("offers regeneration for a supported environment", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: false }),
).toEqual([
{
id: "regenerate-title",
title: "Regenerate title",
image: "arrow.clockwise",
},
]);
});
it("shows and disables the pending state", () => {
expect(
buildThreadTitleRegenerationMenuItems({ supported: true, isRegenerating: true }),
).toEqual([
{
id: "regenerate-title",
title: "Regenerating…",
image: "arrow.clockwise",
attributes: { disabled: true },
},
]);
});
});
@@ -0,0 +1,17 @@
import type { MenuAction } from "@react-native-menu/menu";
export function buildThreadTitleRegenerationMenuItems(input: {
readonly supported: boolean;
readonly isRegenerating: boolean;
}): MenuAction[] {
if (!input.supported) return [];
return [
{
id: "regenerate-title",
title: input.isRegenerating ? "Regenerating…" : "Regenerate title",
image: "arrow.clockwise",
...(input.isRegenerating ? { attributes: { disabled: true } } : {}),
},
];
}
@@ -6,16 +6,16 @@ import {
mapCodexModelCapabilities,
} from "./CodexProvider.ts";
it("keeps current Codex models out of legacy models", () => {
it("keeps only the GPT-5.6 Codex family out of legacy models", () => {
assert.deepStrictEqual(
["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol", "gpt-daybreak-blue-latest", "gpt-5.4"].map(
(model) => [model, isLegacyCodexModel(model)],
),
["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol", "gpt-5.4"].map((model) => [
model,
isLegacyCodexModel(model),
]),
[
["gpt-5.6-luna", false],
["gpt-5.6-terra", false],
["gpt-5.6-sol", false],
["gpt-daybreak-blue-latest", false],
["gpt-5.4", true],
],
);
@@ -62,12 +62,7 @@ const REASONING_EFFORT_LABELS: Readonly<Record<string, string>> = {
};
const DEFAULT_SERVICE_TIER_ID = "default";
const CURRENT_CODEX_MODELS = new Set([
"gpt-5.6-luna",
"gpt-5.6-terra",
"gpt-5.6-sol",
"gpt-daybreak-blue-latest",
]);
const CURRENT_CODEX_MODELS = new Set(["gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol"]);
export function isLegacyCodexModel(model: string): boolean {
return !CURRENT_CODEX_MODELS.has(model);
+72 -55
View File
@@ -35,16 +35,16 @@
// app colors before React mounts.
const DEFAULT_THEME_PALETTES = {
light: {
background: "#fdf7fd",
foreground: "#501854",
accent: "#db2777",
chrome: "#fdf7fd",
background: "oklch(0.982446 0.010114 325.653)",
foreground: "oklch(0.325698 0.116116 325.037)",
accent: "oklch(0.591646 0.217985 0.584)",
chrome: "oklch(0.982446 0.010114 325.653)",
},
dark: {
background: "#1f1a24",
foreground: "#f9f8fb",
accent: "#a3004c",
chrome: "#1f1a24",
background: "oklch(0.22813 0.020366 307.469)",
foreground: "oklch(0.980735 0.004092 301.426)",
accent: "oklch(0.460685 0.185347 4.099)",
chrome: "oklch(0.22813 0.020366 307.469)",
},
};
// Keep this small boot-time copy in sync with the built-in palettes so
@@ -52,72 +52,72 @@
const BUILT_IN_THEME_PALETTES = {
"t3-chat": {
light: {
background: "#fdf7fd",
foreground: "#501854",
accent: "#db2777",
chrome: "#fdf7fd",
background: "oklch(0.982446 0.010114 325.653)",
foreground: "oklch(0.325698 0.116116 325.037)",
accent: "oklch(0.591646 0.217985 0.584)",
chrome: "oklch(0.982446 0.010114 325.653)",
},
dark: {
background: "#1f1a24",
foreground: "#f9f8fb",
accent: "#a3004c",
chrome: "#1f1a24",
background: "oklch(0.22813 0.020366 307.469)",
foreground: "oklch(0.980735 0.004092 301.426)",
accent: "oklch(0.460685 0.185347 4.099)",
chrome: "oklch(0.22813 0.020366 307.469)",
},
},
grove: {
light: {
background: "#f3f7f4",
foreground: "#241523",
accent: "#1b7d50",
chrome: "#f3f7f4",
background: "oklch(0.972369 0.005497 157.15)",
foreground: "oklch(0.222003 0.03479 328.979)",
accent: "oklch(0.523295 0.112292 158.089)",
chrome: "oklch(0.972369 0.005497 157.15)",
},
dark: {
background: "#1b2821",
foreground: "#fffaff",
accent: "#69d69a",
chrome: "#1b2821",
background: "oklch(0.260865 0.02152 162.75)",
foreground: "oklch(0.990339 0.008411 325.64)",
accent: "oklch(0.796228 0.133058 157.319)",
chrome: "oklch(0.260865 0.02152 162.75)",
},
},
ocean: {
light: {
background: "#f5f7f8",
foreground: "#241523",
accent: "#2672af",
chrome: "#f5f7f8",
background: "oklch(0.974199 0.002856 241.597)",
foreground: "oklch(0.222003 0.03479 328.979)",
accent: "oklch(0.536684 0.120219 247.01)",
chrome: "oklch(0.974199 0.002856 241.597)",
},
dark: {
background: "#17212b",
foreground: "#fffaff",
accent: "#70b9ee",
chrome: "#17212b",
background: "oklch(0.242641 0.024125 250.573)",
foreground: "oklch(0.990339 0.008411 325.64)",
accent: "oklch(0.758933 0.105833 241.548)",
chrome: "oklch(0.242641 0.024125 250.573)",
},
},
ember: {
light: {
background: "#f9f7f5",
foreground: "#241523",
accent: "#ae552a",
chrome: "#f9f7f5",
background: "oklch(0.976527 0.002685 60.725)",
foreground: "oklch(0.222003 0.03479 328.979)",
accent: "oklch(0.552831 0.129438 44.656)",
chrome: "oklch(0.976527 0.002685 60.725)",
},
dark: {
background: "#291e1a",
foreground: "#fffaff",
accent: "#f09a64",
chrome: "#291e1a",
background: "oklch(0.245899 0.019144 42.044)",
foreground: "oklch(0.990339 0.008411 325.64)",
accent: "oklch(0.762174 0.124117 52.082)",
chrome: "oklch(0.245899 0.019144 42.044)",
},
},
iris: {
light: {
background: "#f8f7f9",
foreground: "#241523",
accent: "#7253b9",
chrome: "#f8f7f9",
background: "oklch(0.976531 0.003855 303.226)",
foreground: "oklch(0.222003 0.03479 328.979)",
accent: "oklch(0.525348 0.15373 294.176)",
chrome: "oklch(0.976531 0.003855 303.226)",
},
dark: {
background: "#1d1929",
foreground: "#fffaff",
accent: "#9d7df2",
chrome: "#1d1929",
background: "oklch(0.225975 0.031062 293.741)",
foreground: "oklch(0.990339 0.008411 325.64)",
accent: "oklch(0.671712 0.169136 293.929)",
chrome: "oklch(0.225975 0.031062 293.741)",
},
},
};
@@ -152,9 +152,26 @@
}
};
const isHexColor = (value) =>
typeof value === "string" &&
/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(value);
// The runtime decodes the same literal CSS formats into OKLCH. Keep
// contextual colors out: they cannot be resolved from stored data.
const SYSTEM_COLOR_KEYWORD =
/^(?:accentcolor(?:text)?|active(?:border|caption|text)|appworkspace|background|button(?:border|face|highlight|shadow|text)|canvas(?:text)?|captiontext|field(?:text)?|graytext|highlight(?:text)?|inactive(?:border|caption(?:text)?)|info(?:background|text)|linktext|mark(?:text)?|menu(?:text)?|scrollbar|selecteditem(?:text)?|threed(?:darkshadow|face|highlight|lightshadow|shadow)|visitedtext|window(?:frame|text)?)$/i;
const isThemeColor = (value) => {
if (typeof value !== "string" || typeof CSS === "undefined") return false;
const color = value.trim();
if (
/^(?:currentcolor|inherit|initial|revert|revert-layer|unset)$/i.test(color) ||
SYSTEM_COLOR_KEYWORD.test(color) ||
/\bfrom\b|(?:var|env|attr|calc|min|max|clamp)\(/i.test(color)
) {
return false;
}
const isLiteralColor =
/^#(?:[0-9a-f]{3}|[0-9a-f]{4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(color) ||
/^[a-z]+$/i.test(color) ||
/^(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\(/i.test(color);
return isLiteralColor && CSS.supports("color", color);
};
const isRecord = (value) =>
typeof value === "object" && value !== null && !Array.isArray(value);
const isThemeId = (value) =>
@@ -322,13 +339,13 @@
const fallbackSplash = isDark ? SPLASH_COLORS.dark : SPLASH_COLORS.light;
const customSplash = customColors
? {
background: isHexColor(customColors.canvas)
background: isThemeColor(customColors.canvas)
? customColors.canvas
: (customDefaults?.background ?? fallbackSplash.background),
foreground: isHexColor(customColors.text)
foreground: isThemeColor(customColors.text)
? customColors.text
: (customDefaults?.foreground ?? fallbackSplash.foreground),
accent: isHexColor(customColors.accent)
accent: isThemeColor(customColors.accent)
? customColors.accent
: (customDefaults?.accent ?? fallbackSplash.accent),
}
@@ -350,7 +367,7 @@
}
document.documentElement.classList.toggle("dark", isDark);
const chromeColor = customColors
? isHexColor(customColors.chrome)
? isThemeColor(customColors.chrome)
? customColors.chrome
: (customDefaults?.chrome ?? fallbackSplash.background)
: builtInSplash
+5
View File
@@ -23,6 +23,7 @@
"@formkit/auto-animate": "^0.9.0",
"@legendapp/list": "catalog:",
"@lexical/react": "^0.41.0",
"@noble/hashes": "catalog:",
"@pierre/diffs": "catalog:",
"@pierre/trees": "1.0.0-beta.4",
"@t3tools/client-runtime": "workspace:*",
@@ -31,8 +32,11 @@
"@tanstack/react-pacer": "^0.19.4",
"@tanstack/react-router": "^1.160.2",
"class-variance-authority": "^0.7.1",
"culori": "^4.0.2",
"effect": "catalog:",
"jose": "catalog:",
"jsonc-parser": "3.3.1",
"jszip": "3.10.1",
"lexical": "^0.41.0",
"lucide-react": "^0.564.0",
"react": "19.2.6",
@@ -53,6 +57,7 @@
"@tanstack/router-plugin": "^1.161.0",
"@types/babel__core": "^7.20.5",
"@types/compression": "^1.8.1",
"@types/culori": "^4.0.1",
"@types/react": "~19.2.14",
"@types/react-dom": "~19.2.3",
"@vercel/config": "^0.3.0",
+80 -10
View File
@@ -9,7 +9,7 @@ import {
HistoryIcon,
MonitorIcon,
} from "lucide-react";
import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useComposerDraftStore, type DraftId } from "../composerDraftStore";
import { useProject, useThread, useThreadShellsForProjectRefs } from "../state/entities";
@@ -218,16 +218,20 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
/**
* Collapse the strip's labels to icons only when the text no longer fits.
*
* Hidden labels stay measurable (they collapse to invisible absolute boxes,
* which keep their natural width), so the required width can be recomputed in
* either state on every pass - no remembered widths that could go stale or
* latch the strip compact. A small hysteresis keeps the boundary from
* flapping between states.
* Hidden labels stay measurable because their inner text keeps its natural
* width while the outer layout box collapses. This lets every pass recompute
* the expanded width without remembered values that could go stale or latch
* the strip compact. A small hysteresis keeps the boundary from flapping.
*/
const COMPACT_EXPAND_HYSTERESIS_PX = 16;
const COMPOSER_CONTEXT_MOTION_DURATION_MS = 180;
const COMPOSER_CONTEXT_MOTION_EASING = "cubic-bezier(0.32, 0.72, 0, 1)";
const COMPOSER_CONTEXT_CONTROL_SELECTOR = "[data-composer-context-control]";
function useLabelsOverflow(element: HTMLDivElement | null): boolean {
const [overflows, setOverflows] = useState(false);
const pendingControlRectsRef = useRef<Map<HTMLElement, DOMRect> | null>(null);
const controlAnimationsRef = useRef(new Map<HTMLElement, Animation>());
// A render-synced mirror instead of useEffectEvent: the compiler memoizes
// the event callback, which left observers reading the first render's null
// element forever.
@@ -241,7 +245,7 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
if (available === 0) return;
// flex-1 stretches the groups to fill the strip, so their own boxes always
// measure "full". Sum the laid-out content instead, skipping hidden form
// artifacts and absolutely-positioned nodes (the compact-hidden labels).
// artifacts and other out-of-flow nodes.
const contentWidth = (parent: Element): number => {
const gap = Number.parseFloat(getComputedStyle(parent).columnGap) || 0;
let width = 0;
@@ -283,9 +287,71 @@ function useLabelsOverflow(element: HTMLDivElement | null): boolean {
needed += Math.max(0, textWidth - label.clientWidth);
}
}
setOverflows(compact ? needed > available - COMPACT_EXPAND_HYSTERESIS_PX : needed > available);
const nextOverflows = compact
? needed > available - COMPACT_EXPAND_HYSTERESIS_PX
: needed > available;
if (nextOverflows !== compact) {
pendingControlRectsRef.current = new Map(
Array.from(current.querySelectorAll<HTMLElement>(COMPOSER_CONTEXT_CONTROL_SELECTOR)).map(
(control) => [control, control.getBoundingClientRect()],
),
);
}
setOverflows(nextOverflows);
}, []);
useLayoutEffect(() => {
const previousRects = pendingControlRectsRef.current;
if (!previousRects) return;
pendingControlRectsRef.current = null;
for (const animation of controlAnimationsRef.current.values()) {
animation.cancel();
}
controlAnimationsRef.current.clear();
if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;
for (const [control, previousRect] of previousRects) {
if (!control.isConnected) continue;
const nextRect = control.getBoundingClientRect();
const deltaX = previousRect.left - nextRect.left;
const deltaY = previousRect.top - nextRect.top;
if (Math.abs(deltaX) < 0.5 && Math.abs(deltaY) < 0.5) continue;
const animation = control.animate(
[
{ transform: `translate3d(${deltaX}px, ${deltaY}px, 0)` },
{ transform: "translate3d(0, 0, 0)" },
],
{
duration: COMPOSER_CONTEXT_MOTION_DURATION_MS,
easing: COMPOSER_CONTEXT_MOTION_EASING,
fill: "backwards",
},
);
controlAnimationsRef.current.set(control, animation);
animation.addEventListener(
"finish",
() => {
if (controlAnimationsRef.current.get(control) === animation) {
controlAnimationsRef.current.delete(control);
}
},
{ once: true },
);
}
}, [overflows]);
useEffect(
() => () => {
for (const animation of controlAnimationsRef.current.values()) {
animation.cancel();
}
},
[],
);
// Label widths can change without the strip box moving (font family or
// size preferences), so re-measure on every render as well as on resize
// and font loads.
@@ -403,7 +469,7 @@ export const BranchToolbar = memo(function BranchToolbar({
<div
ref={setStripElement}
data-compact={labelsOverflow ? "" : undefined}
className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 ps-1 pe-2 pt-5 pb-1"
className="chat-composer-context-strip group/composer-context -mt-4 mx-auto flex w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] items-center gap-2 overflow-x-clip overflow-y-visible ps-1 pe-2 pt-5 pb-1"
>
{isMobile && showGitControls ? (
<MobileRunContextSelector
@@ -431,7 +497,11 @@ export const BranchToolbar = memo(function BranchToolbar({
{...(showEnvironmentPicker && onEnvironmentChange ? { onEnvironmentChange } : {})}
/>
{showGitControls ? (
<Separator orientation="vertical" className="mx-0.5 h-3.5!" />
<Separator
orientation="vertical"
className="mx-0.5 h-3.5!"
data-composer-context-control
/>
) : null}
</>
)}
@@ -714,7 +714,10 @@ export function BranchToolbarBranchSelector({
open={isBranchMenuOpen}
value={resolvedActiveBranch}
>
<div className={cn("flex min-w-0 items-center gap-1", className)}>
<div
className={cn("flex min-w-0 items-center gap-1", className)}
data-composer-context-control
>
{branchPr && branchPrStatus ? (
<Tooltip>
<TooltipTrigger
@@ -751,9 +754,14 @@ export function BranchToolbarBranchSelector({
<GitBranchIcon className="size-3 shrink-0 opacity-70" />
<span
data-composer-label
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
>
{triggerLabel}
<span
data-composer-label-motion
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
>
{triggerLabel}
</span>
</span>
<ChevronDownIcon className="size-3 shrink-0 opacity-50" />
</ComboboxTrigger>
@@ -50,7 +50,10 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
if (envLocked) {
return (
<span className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
<span
className="inline-flex h-7 shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs"
data-composer-context-control
>
{activeWorktreePath ? (
<>
<FolderGitIcon className="size-3" />
@@ -84,6 +87,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
size="xs"
className="min-w-0 shrink font-medium"
aria-label="Workspace"
data-composer-context-control
>
{effectiveEnvMode === "worktree" ? (
<FolderGit2Icon className="size-3" />
@@ -94,9 +98,14 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
)}
<span
data-composer-label
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
>
<SelectValue />
<span
data-composer-label-motion
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
>
<SelectValue />
</span>
</span>
</SelectTrigger>
<SelectPopup>
@@ -48,7 +48,10 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
// only thing in the strip.
if (envLocked || onEnvironmentChange === undefined) {
return (
<span className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs">
<span
className="inline-flex h-7 min-w-0 max-w-full items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 sm:text-xs"
data-composer-context-control
>
{activeEnvironment?.isPrimary ? (
<MonitorIcon className="size-3 shrink-0" />
) : (
@@ -56,9 +59,14 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
)}
<span
data-composer-label
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
>
{activeEnvironment?.label ?? "Run on"}
<span
data-composer-label-motion
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
>
{activeEnvironment?.label ?? "Run on"}
</span>
</span>
</span>
);
@@ -76,6 +84,7 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
size="xs"
className="min-w-0 max-w-full font-medium"
aria-label="Run on"
data-composer-context-control
>
{activeEnvironment?.isPrimary ? (
<MonitorIcon className="size-3 shrink-0" />
@@ -84,9 +93,14 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
)}
<span
data-composer-label
className="min-w-0 max-w-[240px] truncate transition-[max-width,opacity] duration-300 ease-out group-data-[compact]/composer-context:max-w-0 group-data-[compact]/composer-context:opacity-0"
className="min-w-0 max-w-[240px] group-data-[compact]/composer-context:max-w-0"
>
<SelectValue />
<span
data-composer-label-motion
className="block w-full min-w-0 max-w-[240px] origin-left truncate transition-[opacity,transform] duration-180 ease-[cubic-bezier(0.32,0.72,0,1)] group-data-[compact]/composer-context:[transform:translateX(-0.25rem)_scaleX(0.95)] group-data-[compact]/composer-context:opacity-0 motion-reduce:transform-none motion-reduce:transition-opacity"
>
<SelectValue />
</span>
</span>
</SelectTrigger>
<SelectPopup>
+32 -4
View File
@@ -264,7 +264,13 @@ import {
ProviderStatusBanner,
shouldShowProviderStatusBanner,
} from "./chat/ProviderStatusBanner";
import { ThreadErrorBanner } from "./chat/ThreadErrorBanner";
import {
dismissThreadErrorBannerForSession,
getThreadErrorBannerKey,
isThreadErrorBannerDismissedForSession,
shouldShowThreadErrorBanner,
ThreadErrorBanner,
} from "./chat/ThreadErrorBanner";
import { resolveThreadPr } from "./ThreadStatusIndicators";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./chat/ComposerBannerStack";
import { ThreadSyncStatusPill } from "./chat/ThreadSyncStatusPill";
@@ -1493,6 +1499,24 @@ function ChatViewContent(props: ChatViewProps) {
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 —
@@ -2618,7 +2642,7 @@ function ChatViewContent(props: ChatViewProps) {
)
? activeProviderStatus
: null;
const hasTimelineTopBanner = Boolean(threadError) || visibleProviderStatus !== null;
const hasTimelineTopBanner = Boolean(visibleThreadError) || visibleProviderStatus !== null;
const activeProjectCwd = activeProject?.workspaceRoot ?? null;
const activeThreadWorktreePath = activeThread?.worktreePath ?? null;
const activeWorkspaceRoot = activeThreadWorktreePath ?? activeProjectCwd ?? undefined;
@@ -6146,8 +6170,12 @@ function ChatViewContent(props: ChatViewProps) {
</header>
<ThreadErrorBanner
error={threadError}
onDismiss={() => setThreadError(activeThread.id, null)}
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">
@@ -22,6 +22,7 @@ import { flushSync } from "react-dom";
import {
CheckIcon,
ChevronDownIcon,
CloudDownloadIcon,
CloudUploadIcon,
ExternalLinkIcon,
GitBranchPlusIcon,
@@ -357,7 +358,7 @@ function GitQuickActionIcon({
const iconClassName = "size-3.5";
if (quickAction.kind === "open_pr") return <SourceControlIcon className={iconClassName} />;
if (quickAction.kind === "open_publish") return <CloudUploadIcon className={iconClassName} />;
if (quickAction.kind === "run_pull") return <InfoIcon className={iconClassName} />;
if (quickAction.kind === "run_pull") return <CloudDownloadIcon className={iconClassName} />;
if (quickAction.kind === "run_action") {
if (quickAction.action === "commit") return <GitCommitIcon className={iconClassName} />;
if (quickAction.action === "push" || quickAction.action === "commit_push") {
@@ -366,6 +367,7 @@ function GitQuickActionIcon({
return <SourceControlIcon className={iconClassName} />;
}
if (quickAction.label === "Commit") return <GitCommitIcon className={iconClassName} />;
if (quickAction.label === "Push") return <CloudUploadIcon className={iconClassName} />;
return <InfoIcon className={iconClassName} />;
}
@@ -1,9 +1,74 @@
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import { ThreadErrorBanner } from "./ThreadErrorBanner";
import {
dismissThreadErrorBannerForSession,
getThreadErrorBannerKey,
isThreadErrorBannerDismissedForSession,
shouldShowThreadErrorBanner,
ThreadErrorBanner,
} from "./ThreadErrorBanner";
describe("ThreadErrorBanner", () => {
it("stays hidden after its current error is dismissed", () => {
const bannerKey = getThreadErrorBannerKey("env:thread-a", "Aborted");
dismissThreadErrorBannerForSession(bannerKey);
expect(
shouldShowThreadErrorBanner(
"env:thread-a",
"Aborted",
isThreadErrorBannerDismissedForSession(bannerKey),
),
).toBe(false);
});
it("reappears when a new error arrives on the same thread", () => {
dismissThreadErrorBannerForSession(getThreadErrorBannerKey("env:thread-b", "Turn failed"));
const newErrorKey = getThreadErrorBannerKey("env:thread-b", "Provider crashed");
expect(isThreadErrorBannerDismissedForSession(newErrorKey)).toBe(false);
expect(
shouldShowThreadErrorBanner(
"env:thread-b",
"Provider crashed",
isThreadErrorBannerDismissedForSession(newErrorKey),
),
).toBe(true);
});
it("scopes dismissals to the thread that dismissed them", () => {
dismissThreadErrorBannerForSession(getThreadErrorBannerKey("env:thread-c", "Aborted"));
const otherThreadKey = getThreadErrorBannerKey("env:other-thread", "Aborted");
expect(isThreadErrorBannerDismissedForSession(otherThreadKey)).toBe(false);
expect(
shouldShowThreadErrorBanner(
"env:other-thread",
"Aborted",
isThreadErrorBannerDismissedForSession(otherThreadKey),
),
).toBe(true);
});
it("keeps a dismissal across visiting threads with no error", () => {
const bannerKey = getThreadErrorBannerKey("env:thread-d", "Aborted");
dismissThreadErrorBannerForSession(bannerKey);
expect(shouldShowThreadErrorBanner("env:thread-d", null, false)).toBe(false);
expect(isThreadErrorBannerDismissedForSession(bannerKey)).toBe(true);
expect(
shouldShowThreadErrorBanner(
"env:thread-d",
"Aborted",
isThreadErrorBannerDismissedForSession(bannerKey),
),
).toBe(false);
});
it("never shows a null error", () => {
expect(shouldShowThreadErrorBanner("env:thread-e", null, false)).toBe(false);
});
it("aligns the warning and dismiss icons with the first line of a multi-line error", () => {
const markup = renderToStaticMarkup(
<ThreadErrorBanner
@@ -4,6 +4,35 @@ import { Button } from "../ui/button";
import { CircleAlertIcon, XIcon } from "lucide-react";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
export function getThreadErrorBannerKey(threadKey: string, error: string | null): string | null {
return error === null ? null : `${threadKey}\u0000${error}`;
}
export function shouldShowThreadErrorBanner(
threadKey: string,
error: string | null,
isDismissed: boolean,
): boolean {
return getThreadErrorBannerKey(threadKey, error) !== null && !isDismissed;
}
// Session-scoped (module-level so it survives ChatView remounts, e.g. route
// changes between threads). Mirrors the branch-mismatch banner: a dismissal
// is remembered per thread key plus message, so navigating away to a thread
// with no error cannot resurrect the banner, while a different error message
// on the same thread still appears.
const sessionDismissedThreadErrorBannerKeys = new Set<string>();
export function dismissThreadErrorBannerForSession(bannerKey: string | null): void {
if (bannerKey !== null) {
sessionDismissedThreadErrorBannerKeys.add(bannerKey);
}
}
export function isThreadErrorBannerDismissedForSession(bannerKey: string | null): boolean {
return bannerKey !== null && sessionDismissedThreadErrorBannerKeys.has(bannerKey);
}
export const ThreadErrorBanner = memo(function ThreadErrorBanner({
error,
onDismiss,
@@ -1,6 +1,6 @@
import type { KeyboardEvent, PointerEvent } from "react";
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { isThemeColor, type ThemeColorRole } from "../../themePalette";
import { isThemeColor, themeColorToHex, type ThemeColorRole } from "../../themePalette";
import { cn } from "../../lib/utils";
import { Input } from "../ui/input";
import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover";
@@ -37,39 +37,18 @@ function clampThemeColor(value: number, min = 0, max = 1) {
}
/**
* The picker's plane and sliders operate on opaque six-digit hex, but theme
* colors may carry alpha. The suffix is preserved separately and re-attached
* on commit so adjusting hue or brightness cannot change transparency.
* The picker remains an sRGB/hex adapter over the OKLCH palette engine. Alpha
* is preserved separately and re-attached on commit so adjusting hue or
* brightness cannot change transparency.
*/
function themePickerAlphaSuffix(value: string): string {
const trimmed = value.trim().toLowerCase();
const alpha = /^#[0-9a-f]{4}$/.test(trimmed)
? trimmed.slice(4).repeat(2)
: /^#[0-9a-f]{8}$/.test(trimmed)
? trimmed.slice(7)
: "";
const normalized = themeColorToHex(value) ?? "";
const alpha = normalized.length === 9 ? normalized.slice(7) : "";
return alpha === "ff" ? "" : alpha;
}
function normalizeThemePickerColor(value: string): string {
const trimmed = value.trim();
if (/^#[0-9a-f]{3}$/i.test(trimmed)) {
return `#${trimmed
.slice(1)
.split("")
.map((character) => `${character}${character}`)
.join("")}`;
}
if (/^#[0-9a-f]{4}$/i.test(trimmed)) {
return `#${trimmed
.slice(1, 4)
.split("")
.map((character) => `${character}${character}`)
.join("")}`;
}
if (/^#[0-9a-f]{6}$/i.test(trimmed)) return trimmed;
if (/^#[0-9a-f]{8}$/i.test(trimmed)) return trimmed.slice(0, 7);
return "#000000";
return (themeColorToHex(value) ?? "#000000").slice(0, 7);
}
function themeHexToHsv(hex: string): ThemeColorHsv {
@@ -505,6 +484,9 @@ export const ThemeColorField = memo(function ThemeColorField({
const label = customLabel ?? getThemeRoleLabel(role);
const isColorValue = isThemeColor(value);
const swatchValue = isColorValue ? value : "#000000";
const editorValue = value.trim().toLowerCase().startsWith("oklch(")
? (themeColorToHex(value) ?? value)
: value;
return (
<div
@@ -542,7 +524,7 @@ export const ThemeColorField = memo(function ThemeColorField({
onPointerDown={() => onSelect?.(role)}
size="sm"
unstyled
value={value}
value={editorValue}
/>
</div>
</div>
@@ -610,7 +610,7 @@ export function ThemeEditorPanel({
[activeAppearance, editingTheme, selectedRole],
);
const handleSubmit = useCallback(() => {
const handleSubmit = () => {
if (!name.trim()) {
setError("Name your theme first.");
return;
@@ -645,8 +645,8 @@ export function ThemeEditorPanel({
return;
}
mergedAppearance = editedModes[0] ?? null;
savedTheme = updateCustomTheme(
parseThemeFile({
savedTheme = updateCustomTheme({
...parseThemeFile({
version: THEME_FILE_VERSION,
id: mergeTarget.id,
name: mergeTarget.label,
@@ -658,7 +658,8 @@ export function ThemeEditorPanel({
},
...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
}),
);
...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
});
retiredTheme = editingTheme;
try {
removeCustomTheme(editingTheme.id);
@@ -676,8 +677,8 @@ export function ThemeEditorPanel({
} else if (editingTheme) {
const baseAppearance = editingTheme.appearance;
const variantAppearance = baseAppearance === "light" ? "dark" : "light";
savedTheme = updateCustomTheme(
parseThemeFile({
savedTheme = updateCustomTheme({
...parseThemeFile({
version: THEME_FILE_VERSION,
id: editingTheme.id,
name,
@@ -688,7 +689,8 @@ export function ThemeEditorPanel({
: {}),
...(isAdvanced ? {} : { managed: true }),
}),
);
...(editingTheme.collection ? { collection: editingTheme.collection } : {}),
});
} else if (mergeTarget) {
if (takenAppearances.includes(activeAppearance)) {
setError(
@@ -701,8 +703,8 @@ export function ThemeEditorPanel({
// survives when every palette in the theme came from the guided
// editor.
mergedAppearance = activeAppearance;
savedTheme = updateCustomTheme(
parseThemeFile({
savedTheme = updateCustomTheme({
...parseThemeFile({
version: THEME_FILE_VERSION,
id: mergeTarget.id,
name: mergeTarget.label,
@@ -714,7 +716,8 @@ export function ThemeEditorPanel({
},
...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
}),
);
...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
});
} else {
savedTheme = installCustomTheme(
parseThemeFile({
@@ -762,19 +765,7 @@ export function ThemeEditorPanel({
: "Could not create the theme.",
);
}
}, [
activeAppearance,
colorsByAppearance,
editingTheme,
isAdvanced,
isEditing,
mergeTarget,
name,
onOpenChange,
onSaved,
simpleColorsDirtyByAppearance,
takenAppearances,
]);
};
const renderNameField = () => (
<label className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
@@ -28,6 +28,7 @@ import {
DialogPopup,
DialogTitle,
} from "../ui/dialog";
import { ThemeSearchSection } from "./ThemeSearchSection";
/**
* A full theme export is a few KB, so anything past this is not a theme file.
@@ -360,9 +361,16 @@ export function ThemeImportDialog({
: null;
for (const theme of conflicts) {
try {
const existingTheme =
mode === "update"
? getCustomThemes().find((candidate) => candidate.id === theme.id)
: undefined;
const themeToUpdate = existingTheme?.collection
? { ...theme, collection: existingTheme.collection }
: theme;
resolved.push(
mode === "update"
? updateCustomTheme(theme)
? updateCustomTheme(themeToUpdate)
: installCustomTheme(versionedCopy(theme, preferredName)),
);
} catch (cause) {
@@ -426,7 +434,23 @@ export function ThemeImportDialog({
<DialogHeader>
<DialogTitle>Add a theme</DialogTitle>
</DialogHeader>
<DialogPanel className="space-y-4">
<DialogPanel className="space-y-5">
<ThemeSearchSection
onInstalled={(themes, context) => {
onImportedMany(themes, context);
onOpenChange(false);
}}
open={open}
/>
<div className="flex items-center gap-3" aria-hidden>
<div className="h-px flex-1 bg-border" />
<span className="text-muted-foreground text-[11px] uppercase tracking-wider">
or import a file
</span>
<div className="h-px flex-1 bg-border" />
</div>
{(() => {
const dropHandlers = {
onDragEnter: (event: DragEvent<HTMLDivElement>) => {
@@ -0,0 +1,389 @@
import {
ExternalLinkIcon,
PaletteIcon,
PlusIcon,
RefreshCwIcon,
SearchIcon,
ShieldCheckIcon,
} from "lucide-react";
import type { FormEvent } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import {
importOpenVsxThemeExtension,
searchOpenVsxThemes,
type OpenVsxThemeExtension,
type OpenVsxThemeSort,
} from "../../openVsxThemes";
import {
getCustomThemes,
getStoredCustomThemeCollection,
replaceCustomThemeCollection,
type ThemeDefinition,
} from "../../themePalette";
import {
AlertDialog,
AlertDialogClose,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogPopup,
AlertDialogTitle,
} from "../ui/alert-dialog";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
import { Spinner } from "../ui/spinner";
const DOWNLOAD_FORMAT = new Intl.NumberFormat(undefined, {
notation: "compact",
maximumFractionDigits: 1,
});
const SUGGESTED_SEARCHES = ["Dracula", "Catppuccin", "Nord", "Tokyo Night"];
const SORT_OPTIONS: ReadonlyArray<{ value: OpenVsxThemeSort; label: string }> = [
{ value: "downloadCount", label: "Most downloaded" },
{ value: "rating", label: "Best rated" },
{ value: "timestamp", label: "Newest" },
{ value: "relevance", label: "Most relevant" },
];
function ThemeExtensionIcon({ extension }: { extension: OpenVsxThemeExtension }) {
const [failed, setFailed] = useState(false);
return (
<div className="flex size-10 shrink-0 items-center justify-center overflow-hidden rounded-lg bg-muted text-muted-foreground">
{extension.iconUrl && !failed ? (
<img
alt=""
className="size-full object-cover"
loading="lazy"
referrerPolicy="no-referrer"
src={extension.iconUrl}
onError={() => setFailed(true)}
/>
) : (
<PaletteIcon className="size-4" />
)}
</div>
);
}
export function ThemeSearchSection({
open,
onInstalled,
}: {
open: boolean;
onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
}) {
const [query, setQuery] = useState("");
const [sortBy, setSortBy] = useState<OpenVsxThemeSort>("downloadCount");
const [results, setResults] = useState<ReadonlyArray<OpenVsxThemeExtension> | null>(null);
const [error, setError] = useState<string | null>(null);
const [isSearching, setIsSearching] = useState(false);
const [installingId, setInstallingId] = useState<string | null>(null);
const [pendingUpdate, setPendingUpdate] = useState<OpenVsxThemeExtension | null>(null);
const requestRef = useRef<AbortController | null>(null);
useEffect(() => {
requestRef.current?.abort();
requestRef.current = null;
if (open) {
setQuery("");
setSortBy("downloadCount");
setResults(null);
setError(null);
setIsSearching(false);
setInstallingId(null);
setPendingUpdate(null);
}
return () => {
requestRef.current?.abort();
requestRef.current = null;
};
}, [open]);
const runSearch = useCallback(
async (searchText: string, nextSort = sortBy) => {
const trimmed = searchText.trim();
if (!trimmed) return;
requestRef.current?.abort();
const controller = new AbortController();
requestRef.current = controller;
setQuery(trimmed);
setIsSearching(true);
setError(null);
setResults(null);
try {
const nextResults = await searchOpenVsxThemes(trimmed, {
signal: controller.signal,
sortBy: nextSort,
});
if (!controller.signal.aborted) setResults(nextResults);
} catch (cause) {
if (!controller.signal.aborted) {
setError(cause instanceof Error ? cause.message : "Open VSX search failed.");
}
}
if (requestRef.current === controller) {
requestRef.current = null;
setIsSearching(false);
}
},
[sortBy],
);
const handleSearch = useCallback(
(event: FormEvent<HTMLFormElement>) => {
event.preventDefault();
void runSearch(query);
},
[query, runSearch],
);
const handleSortChange = useCallback(
(value: OpenVsxThemeSort | null) => {
const nextSort = SORT_OPTIONS.find((option) => option.value === value)?.value;
if (!nextSort) return;
setSortBy(nextSort);
if ((results !== null || isSearching) && query.trim()) {
void runSearch(query, nextSort);
}
},
[isSearching, query, results, runSearch],
);
const handleInstall = useCallback(
async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {
setError(null);
let installedCollection: ReadonlyArray<ThemeDefinition>;
try {
installedCollection = getStoredCustomThemeCollection(extension.collectionId);
} catch (cause) {
setError(cause instanceof Error ? cause.message : "Installed themes could not be read.");
return;
}
const updated = installedCollection.length > 0;
if (updated && !allowUpdate) {
setPendingUpdate(extension);
return;
}
requestRef.current?.abort();
const controller = new AbortController();
requestRef.current = controller;
setInstallingId(extension.id);
try {
const themes = await importOpenVsxThemeExtension(extension, controller.signal);
if (!controller.signal.aborted) {
const imported = replaceCustomThemeCollection(extension.collectionId, themes, {
expectedCollection: installedCollection,
});
onInstalled(imported, { updated });
}
} catch (cause) {
if (!controller.signal.aborted) {
setError(cause instanceof Error ? cause.message : "That theme could not be added.");
}
}
if (requestRef.current === controller) {
requestRef.current = null;
setInstallingId(null);
}
},
[onInstalled],
);
return (
<section className="space-y-3" aria-labelledby="theme-search-heading">
<div>
<h3 className="text-sm font-medium" id="theme-search-heading">
Search community themes
</h3>
<p className="mt-0.5 text-muted-foreground text-xs">
Find open-source themes from Open VSX.
</p>
</div>
<form className="relative flex gap-2" onSubmit={handleSearch}>
<SearchIcon className="pointer-events-none absolute left-3 top-1/2 z-10 size-4 -translate-y-1/2 text-muted-foreground" />
<Input
aria-label="Search Open VSX themes"
className="rounded-xl [&_input]:pl-9"
autoFocus
onChange={(event) => setQuery(event.currentTarget.value)}
placeholder="try dracula, nord, catppuccin..."
size="lg"
type="search"
value={query}
/>
<Button
disabled={!query.trim() || isSearching || installingId !== null}
type="submit"
variant="outline"
>
{isSearching ? <Spinner /> : <SearchIcon />}
Search
</Button>
</form>
{!isSearching ? (
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<div className="flex min-w-0 flex-wrap items-center gap-1.5">
<p className="text-muted-foreground text-xs">Popular</p>
{SUGGESTED_SEARCHES.map((suggestion) => (
<Button
key={suggestion}
size="xs"
variant="ghost"
onClick={() => void runSearch(suggestion)}
>
{suggestion}
</Button>
))}
</div>
{results && results.length > 0 ? (
<div className="flex shrink-0 items-center justify-end gap-2">
<p className="text-muted-foreground text-xs">Sort</p>
<Select
disabled={installingId !== null}
value={sortBy}
onValueChange={handleSortChange}
>
<SelectTrigger size="sm" className="w-40" aria-label="Sort themes">
<SelectValue>
{SORT_OPTIONS.find((option) => option.value === sortBy)?.label}
</SelectValue>
</SelectTrigger>
<SelectPopup align="end" alignItemWithTrigger={false}>
{SORT_OPTIONS.map((option) => (
<SelectItem key={option.value} hideIndicator value={option.value}>
{option.label}
</SelectItem>
))}
</SelectPopup>
</Select>
</div>
) : null}
</div>
) : null}
<div className="sr-only" role="status">
{isSearching
? "Finding themes..."
: results
? `${results.length} supported ${results.length === 1 ? "theme" : "themes"} found.`
: ""}
</div>
{error ? (
<div
aria-live="polite"
className="rounded-xl border border-destructive/30 bg-destructive/5 px-3 py-2 text-destructive text-sm"
>
{error}
</div>
) : null}
{isSearching ? (
<div className="flex min-h-20 items-center justify-center gap-2 text-muted-foreground text-sm">
<Spinner /> Finding themes...
</div>
) : null}
{results ? (
results.length === 0 ? (
<div className="flex min-h-40 flex-col items-center justify-center rounded-2xl border border-dashed text-center">
<p className="text-sm font-medium">No supported open-source themes found</p>
<p className="mt-1 text-muted-foreground text-xs">Try a broader search.</p>
</div>
) : (
<div className="grid gap-2 sm:grid-cols-2">
{results.map((extension) => {
const isInstalling = installingId === extension.id;
const isInstalled = getCustomThemes().some(
(theme) => theme.collection?.id === extension.collectionId,
);
const action = isInstalled ? "Update" : "Add";
const progressAction = isInstalled ? "Updating" : "Adding";
return (
<article
className="group flex min-w-0 flex-col gap-3 rounded-xl border border-border/70 bg-card/60 p-3 transition-colors hover:bg-accent/20"
key={extension.id}
>
<div className="flex min-w-0 gap-3">
<ThemeExtensionIcon key={extension.iconUrl} extension={extension} />
<div className="min-w-0 flex-1">
<h4 className="truncate text-sm font-medium">{extension.name}</h4>
<p className="truncate text-muted-foreground text-xs">
{extension.publisher} · {DOWNLOAD_FORMAT.format(extension.downloadCount)}{" "}
downloads
</p>
</div>
</div>
<p className="line-clamp-2 min-h-8 text-muted-foreground text-xs leading-4">
{extension.description || "A community color theme for your editor."}
</p>
<div className="mt-auto flex items-center justify-between gap-2">
<div className="flex min-w-0 items-center gap-2">
<span className="inline-flex items-center gap-1 text-muted-foreground text-[11px]">
<ShieldCheckIcon className="size-3" /> {extension.license}
</span>
{extension.sourceUrl ? (
<a
aria-label={`View source for ${extension.name}`}
className="inline-flex items-center gap-1 text-muted-foreground text-[11px] hover:text-foreground"
href={extension.sourceUrl}
rel="noreferrer"
target="_blank"
>
Source <ExternalLinkIcon className="size-3" />
</a>
) : null}
</div>
<Button
aria-label={`${isInstalling ? progressAction : action} ${extension.name}`}
disabled={installingId !== null}
size="xs"
variant="outline"
onClick={() => void handleInstall(extension, false)}
>
{isInstalling ? <Spinner /> : isInstalled ? <RefreshCwIcon /> : <PlusIcon />}
{isInstalling ? `${progressAction}...` : action}
</Button>
</div>
</article>
);
})}
</div>
)
) : null}
<AlertDialog
open={pendingUpdate !== null}
onOpenChange={(nextOpen) => {
if (!nextOpen) setPendingUpdate(null);
}}
>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Update “{pendingUpdate?.name}”?</AlertDialogTitle>
<AlertDialogDescription>
This replaces its installed variants, including any local edits. Variants no longer in
the extension will be removed.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button
onClick={() => {
const extension = pendingUpdate;
setPendingUpdate(null);
if (extension) void handleInstall(extension, true);
}}
>
Update theme
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
</AlertDialog>
</section>
);
}
@@ -1,17 +1,20 @@
import {
CheckIcon,
CopyIcon,
DownloadIcon,
MoonIcon,
PenLineIcon,
PlusIcon,
SunIcon,
Trash2Icon,
UploadIcon,
} from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { useCallback, useEffect, useState, type ReactElement } from "react";
import { cn } from "../../lib/utils";
import {
getThemeDefinition,
getThemeModes,
removeCustomTheme,
removeCustomThemes,
serializeThemeFile,
type ThemeAppearance,
type ThemeDefinition,
@@ -41,6 +44,7 @@ import {
getThemeCardDefinition,
previewColorsOf,
ThemePreviewCircles,
ThemePreviewCircle,
type ThemeCardDefinition,
type ThemeMode,
} from "./ThemePreviewCircles";
@@ -54,6 +58,21 @@ const MAINTAINER_THEMES: ReadonlyArray<ThemeDefinition> = [
IRIS_THEME,
];
function collectionVariantLabels(themes: ReadonlyArray<ThemeDefinition>): ReadonlyArray<string> {
if (themes.length === 0) return [];
const words = themes.map((theme) => theme.label.trim().split(/\s+/));
const firstWords = words[0]!;
const sharedWordCount = firstWords.findIndex((word, index) =>
words.some((labelWords) => labelWords[index]?.toLocaleLowerCase() !== word.toLocaleLowerCase()),
);
const prefixLength = sharedWordCount === -1 ? firstWords.length - 1 : sharedWordCount;
return themes.map((theme, index) => {
const shortLabel = words[index]?.slice(Math.max(0, prefixLength)).join(" ").trim();
return shortLabel || theme.label;
});
}
function downloadThemeFile(filename: string, contents: string): void {
const url = URL.createObjectURL(new Blob([contents], { type: "application/json" }));
const anchor = document.createElement("a");
@@ -65,6 +84,15 @@ function downloadThemeFile(filename: string, contents: string): void {
setTimeout(() => URL.revokeObjectURL(url), 30_000);
}
function ThemeVariantTooltip({ label, children }: { label: string; children: ReactElement }) {
return (
<Tooltip>
<TooltipTrigger render={children} />
<TooltipPopup>{label}</TooltipPopup>
</Tooltip>
);
}
function ThemeLibraryCard({
theme,
isActive,
@@ -75,6 +103,7 @@ function ThemeLibraryCard({
onDuplicate,
onDownload,
onRemove,
variantNavigation,
}: {
theme: ThemeCardDefinition;
isActive: boolean;
@@ -85,10 +114,33 @@ function ThemeLibraryCard({
onDuplicate?: () => void;
onDownload?: () => void;
onRemove?: () => void;
variantNavigation?: {
collectionLabel: string;
options: ReadonlyArray<{
themeIndex: number;
label: string;
activeModes: ReadonlyArray<ThemeMode>;
preview: ThemeCardDefinition["previews"][number];
}>;
onSelectAndUse: (themeIndex: number, mode: ThemeAppearance) => void;
};
}) {
// A one-appearance theme can only take its own side of the mix, so the card
// tooltip promises exactly what clicking it does.
const cardModes = theme.previews.map((preview) => preview.mode);
const [radialModeOpen, setRadialModeOpen] = useState<ThemeAppearance | null>(null);
const radialModeGroups = (["light", "dark"] as const).map((mode) => {
const options =
variantNavigation?.options.flatMap((option) => {
const preview = option.preview;
return preview.mode === mode ? [{ option, preview }] : [];
}) ?? [];
return {
mode,
options,
selected: options.find(({ option }) => option.activeModes.includes(mode)) ?? options[0],
};
});
return (
// The card surface stays a plain div (buttons cannot nest inside a button
// role); the title button and mode circles carry the accessible actions,
@@ -105,17 +157,147 @@ function ThemeLibraryCard({
onClick={onUse}
style={isActive ? { boxShadow: "inset 0 0 0 1px var(--ring)" } : undefined}
>
<ThemePreviewCircles
label={theme.label}
activeModes={activeModes}
onSelectMode={onUseMode}
previews={theme.previews}
/>
<div className="relative">
{variantNavigation ? (
<div
aria-label="Light and dark theme variants"
className="relative h-20"
role="group"
onBlurCapture={(event) => {
const nextTarget = event.relatedTarget;
if (
!(nextTarget instanceof Node) ||
!event.currentTarget.contains(nextTarget)
) {
setRadialModeOpen(null);
}
}}
onKeyDown={(event) => {
if (event.key === "Escape") setRadialModeOpen(null);
}}
onMouseLeave={() => setRadialModeOpen(null)}
>
{radialModeGroups.map(({ mode, options, selected }) => {
if (!selected) return null;
const rootOffsetX = mode === "light" ? -52 : 52;
const isOpen = radialModeOpen === mode;
const isActive = selected.option.activeModes.includes(mode);
const modeLabel = mode === "light" ? "Light" : "Dark";
return (
<div className="contents" key={mode}>
<ThemeVariantTooltip label={`${modeLabel}: ${selected.option.label}`}>
<button
aria-label={
options.length > 1
? `Choose ${mode} variant, ${options.length} options, currently ${selected.option.label}`
: `Use ${mode} variant, currently ${selected.option.label}`
}
aria-pressed={isActive}
className="absolute left-1/2 top-2 z-20 flex size-14 items-center justify-center rounded-full outline-none focus-visible:ring-2 focus-visible:ring-ring"
style={{
transform: `translateX(calc(-50% + ${rootOffsetX}px))`,
}}
type="button"
onClick={(event) => {
event.stopPropagation();
variantNavigation.onSelectAndUse(selected.option.themeIndex, mode);
}}
onFocus={() => setRadialModeOpen(mode)}
onMouseEnter={() => setRadialModeOpen(mode)}
>
<ThemePreviewCircle
colors={selected.preview.colors}
mode={selected.preview.mode}
/>
{isActive ? (
<span
aria-hidden
className="pointer-events-none absolute inset-0 rounded-full ring-2 ring-ring"
/>
) : null}
{isActive ? (
<span className="pointer-events-none absolute -bottom-0.5 -right-0.5 flex size-4 items-center justify-center rounded-full border border-border/70 bg-background text-foreground shadow-sm">
{mode === "light" ? (
<SunIcon className="size-2.5" />
) : (
<MoonIcon className="size-2.5" />
)}
</span>
) : null}
</button>
</ThemeVariantTooltip>
<span
className="pointer-events-none absolute bottom-0 left-1/2 inline-flex max-w-24 -translate-x-1/2 items-center gap-1 text-[11px] font-medium text-foreground"
style={{ marginLeft: rootOffsetX }}
>
<span className="truncate">{selected.option.label}</span>
{options.length > 1 ? (
<span className="shrink-0 rounded-full bg-muted px-1 text-[9px] text-muted-foreground">
+{options.length - 1}
</span>
) : null}
</span>
{options.length > 1
? options.map(({ option, preview }, optionIndex) => {
const progress = optionIndex / (options.length - 1) - 0.5;
const childOffsetX = rootOffsetX + progress * 68;
const childOffsetY = Math.abs(progress) * 10;
const optionIsActive = option.activeModes.includes(mode);
return (
<ThemeVariantTooltip
key={option.label}
label={`Use ${option.label} for ${mode} mode`}
>
<button
aria-label={`Use ${option.label} for ${mode} mode${optionIsActive ? ", currently active" : ""}`}
aria-pressed={optionIsActive}
className={cn(
"absolute left-1/2 top-1 z-30 flex size-7 items-center justify-center rounded-full bg-background shadow-sm outline-none transition-[transform,opacity] duration-200 ease-out motion-reduce:transition-none focus-visible:ring-2 focus-visible:ring-ring",
optionIsActive ? "ring-2 ring-ring" : "ring-1 ring-border/70",
)}
style={{
opacity: isOpen ? 1 : 0,
pointerEvents: isOpen ? "auto" : "none",
transform: `translate(calc(-50% + ${isOpen ? childOffsetX : rootOffsetX}px), ${isOpen ? childOffsetY : 28}px) scale(${isOpen ? 1 : 0.55})`,
transitionDelay: isOpen ? `${optionIndex * 35}ms` : "0ms",
}}
type="button"
onClick={(event) => {
event.stopPropagation();
variantNavigation.onSelectAndUse(option.themeIndex, mode);
}}
onFocus={() => setRadialModeOpen(mode)}
onMouseEnter={() => setRadialModeOpen(mode)}
>
<span className="pointer-events-none scale-[0.43]">
<ThemePreviewCircle
colors={preview.colors}
mode={preview.mode}
/>
</span>
</button>
</ThemeVariantTooltip>
);
})
: null}
</div>
);
})}
</div>
) : (
<ThemePreviewCircles
label={theme.label}
activeModes={activeModes}
onSelectMode={onUseMode}
previews={theme.previews}
/>
)}
</div>
<div className="flex items-center gap-2 px-3 pb-3 pt-2">
<div className="min-w-0 flex-1">
<div className="flex items-center gap-1.5">
<button
aria-label={`Use ${theme.label} theme${isActive ? ", currently active" : ""}`}
aria-label={`Use ${variantNavigation ? `${variantNavigation.collectionLabel}, ${theme.label} variant` : `${theme.label} theme`}${isActive ? ", currently active" : ""}`}
aria-pressed={isActive}
className="min-w-0 cursor-pointer truncate rounded-sm text-left text-sm font-medium text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-card"
type="button"
@@ -124,7 +306,7 @@ function ThemeLibraryCard({
onUse();
}}
>
{theme.label}
{variantNavigation?.collectionLabel ?? theme.label}
</button>
</div>
</div>
@@ -195,7 +377,11 @@ function ThemeLibraryCard({
<TooltipTrigger
render={
<Button
aria-label={`Remove ${theme.label}`}
aria-label={
variantNavigation
? `Remove themes from ${variantNavigation.collectionLabel}`
: `Remove ${theme.label}`
}
size="icon-xs"
variant="ghost"
className="text-muted-foreground hover:text-destructive"
@@ -208,7 +394,9 @@ function ThemeLibraryCard({
</Button>
}
/>
<TooltipPopup>Remove theme</TooltipPopup>
<TooltipPopup>
{variantNavigation ? "Remove themes" : "Remove theme"}
</TooltipPopup>
</Tooltip>
) : null}
</div>
@@ -218,12 +406,97 @@ function ThemeLibraryCard({
}
/>
<TooltipPopup>
{cardModes.length > 1 ? "Use for both light and dark" : `Use for ${cardModes[0]} mode only`}
{variantNavigation
? "Use the first variants for light and dark"
: cardModes.length > 1
? "Use for both light and dark"
: `Use for ${cardModes[0]} mode only`}
</TooltipPopup>
</Tooltip>
);
}
function CustomThemeCollectionCard({
themes,
activeModesFor,
onUse,
onUseMode,
onDuplicate,
onEdit,
onDownload,
onRemove,
}: {
themes: ReadonlyArray<ThemeDefinition>;
activeModesFor: (themeId: string) => ReadonlyArray<ThemeMode>;
onUse: (theme: ThemeDefinition) => void;
onUseMode: (theme: ThemeDefinition, mode: ThemeMode) => void;
onDuplicate: (theme: ThemeDefinition) => void;
onEdit: (theme: ThemeDefinition) => void;
onDownload: (theme: ThemeDefinition) => void;
onRemove: (theme: ThemeDefinition) => void;
}) {
const [variantIndex, setVariantIndex] = useState(() => {
const activeIndex = themes.findIndex((theme) => activeModesFor(theme.id).length > 0);
return activeIndex < 0 ? 0 : activeIndex;
});
const safeIndex = Math.min(variantIndex, themes.length - 1);
const theme = themes[safeIndex];
useEffect(() => {
if (variantIndex !== safeIndex) setVariantIndex(safeIndex);
}, [safeIndex, variantIndex]);
if (!theme) return null;
const collectionLabel = theme.collection?.label ?? theme.label;
const variantLabels = collectionVariantLabels(themes);
const defaultLightTheme = themes.find((candidate) => getThemeModes(candidate).includes("light"));
const defaultDarkTheme = themes.find((candidate) => getThemeModes(candidate).includes("dark"));
const selectCollectionDefaults = () => {
if (themes.length === 1) {
onUse(theme);
return;
}
if (defaultLightTheme) onUseMode(defaultLightTheme, "light");
if (defaultDarkTheme) onUseMode(defaultDarkTheme, "dark");
setVariantIndex(0);
};
return (
<ThemeLibraryCard
activeModes={activeModesFor(theme.id)}
isActive={false}
onDownload={() => onDownload(theme)}
onDuplicate={() => onDuplicate(theme)}
onEdit={() => onEdit(theme)}
onRemove={() => onRemove(theme)}
onUse={selectCollectionDefaults}
onUseMode={(mode) => onUseMode(theme, mode)}
theme={getThemeCardDefinition(theme)}
{...(themes.length > 1
? {
variantNavigation: {
collectionLabel,
options: themes.flatMap((variant, themeIndex) =>
getThemeCardDefinition(variant).previews.map((preview) => ({
themeIndex,
label: variantLabels[themeIndex] ?? variant.label,
activeModes: activeModesFor(variant.id),
preview,
})),
),
onSelectAndUse: (themeIndex, mode) => {
const selectedTheme = themes[themeIndex];
if (!selectedTheme) return;
setVariantIndex(themeIndex);
onUseMode(selectedTheme, mode);
},
},
}
: {})}
/>
);
}
export function ThemeLibrary({
theme,
setTheme,
@@ -250,14 +523,20 @@ export function ThemeLibrary({
setThemeHalf: (appearance: ThemeAppearance, themeId: string | null) => boolean;
}) {
const openThemeEditor = useThemeEditorStore((store) => store.openThemeEditor);
const [themeToRemove, setThemeToRemove] = useState<ThemeDefinition | null>(null);
// Keep the last removal target so the dialog title stays populated while the
// close animation plays after confirming.
const lastThemeToRemoveRef = useRef<ThemeDefinition | null>(null);
useEffect(() => {
if (themeToRemove) lastThemeToRemoveRef.current = themeToRemove;
}, [themeToRemove]);
const removeDialogTheme = themeToRemove ?? lastThemeToRemoveRef.current;
const [themeRemovalTarget, setThemeRemovalTarget] = useState<{
theme: ThemeDefinition;
collectionThemes: ReadonlyArray<ThemeDefinition>;
} | null>(null);
// Keep the target after closing so the dialog text remains populated during
// its exit animation. The next trash action replaces it before reopening.
const [isThemeRemovalOpen, setIsThemeRemovalOpen] = useState(false);
const [themeIdsToRemove, setThemeIdsToRemove] = useState<ReadonlyArray<string>>([]);
const themeIdsToRemoveSet = new Set(themeIdsToRemove);
const removeDialogTheme = themeRemovalTarget?.theme;
const removeDialogCollectionThemes = themeRemovalTarget?.collectionThemes ?? [];
const canRemoveCollection = removeDialogCollectionThemes.length > 1;
const removeDialogCollectionLabel =
removeDialogTheme?.collection?.label ?? removeDialogTheme?.label;
const notifyThemeSaveFailure = useCallback(() => {
toastManager.add(
@@ -288,37 +567,43 @@ export function ThemeLibrary({
[notifyThemeSaveFailure, setTheme],
);
const handleRemoveTheme = useCallback((customTheme: ThemeDefinition) => {
setThemeToRemove(customTheme);
}, []);
const handleRemoveTheme = useCallback(
(customTheme: ThemeDefinition, collectionThemes: ReadonlyArray<ThemeDefinition>) => {
setThemeRemovalTarget({ theme: customTheme, collectionThemes });
setThemeIdsToRemove(collectionThemes.length > 1 ? [] : [customTheme.id]);
setIsThemeRemovalOpen(true);
},
[],
);
const handleConfirmRemoveTheme = useCallback(() => {
if (!themeToRemove) return;
const removesBase = getThemeDefinition(theme)?.id === themeToRemove.id;
// Keep the theme installed if we cannot move the selection off it; the
// dialog stays open so the user can retry or cancel.
if (!themeRemovalTarget) return;
const removedIds = new Set(themeIdsToRemove);
if (removedIds.size === 0) return;
const removesBase = removedIds.has(getThemeDefinition(theme)?.id ?? "");
// Keep the themes installed if we cannot move the selection off one of
// them; the dialog stays open so the user can retry or cancel.
if (removesBase && !persistTheme(appearanceMode === "system" ? "system" : appearanceMode)) {
return;
}
for (const appearance of ["light", "dark"] as const) {
const half = themeHalves?.[appearance];
if (half === undefined) continue;
// Writing a base preference clears the whole mix, so halves that name a
// surviving theme are written back; halves on the removed theme fall
// back to the base.
const next = half === themeToRemove.id ? null : removesBase ? half : undefined;
// Writing a base preference clears the whole mix, so halves that name
// a surviving theme are written back; removed halves fall back to base.
const next = half && removedIds.has(half) ? null : removesBase ? half : undefined;
if (next !== undefined && !setThemeHalf(appearance, next)) {
notifyThemeRemovalFailure();
return;
}
}
try {
removeCustomTheme(themeToRemove.id);
removeCustomThemes([...removedIds]);
} catch {
notifyThemeRemovalFailure();
return;
}
setThemeToRemove(null);
setIsThemeRemovalOpen(false);
}, [
appearanceMode,
notifyThemeRemovalFailure,
@@ -326,7 +611,8 @@ export function ThemeLibrary({
setThemeHalf,
theme,
themeHalves,
themeToRemove,
themeIdsToRemove,
themeRemovalTarget,
]);
// ----- Automatic-mode mixing -------------------------------------------
@@ -460,6 +746,20 @@ export function ThemeLibrary({
</div>
);
const customThemeCollections = [
...customThemes
.reduce((groups, customTheme) => {
const groupId = customTheme.collection
? `collection:${customTheme.collection.id}`
: `theme:${customTheme.id}`;
const group = groups.get(groupId);
if (group) group.push(customTheme);
else groups.set(groupId, [customTheme]);
return groups;
}, new Map<string, ThemeDefinition[]>())
.entries(),
];
const renderPairGrid = () => (
// One shared provider so every tooltip in the grid hands off instantly to
// the next hovered trigger instead of stacking on top of it. The card
@@ -509,43 +809,39 @@ export function ThemeLibrary({
/>
);
})}
{customThemes.map((customTheme) => {
const card = getThemeCardDefinition(customTheme);
return (
<ThemeLibraryCard
activeModes={pickedModesFor(customTheme.id)}
isActive={false}
key={customTheme.id}
onDuplicate={() =>
openThemeEditor({
editingThemeId: null,
seedThemeId: customTheme.id,
seedName: `${customTheme.label} copy`,
initialAppearance,
})
}
onEdit={() =>
openThemeEditor({
editingThemeId: customTheme.id,
seedThemeId: null,
seedName: null,
initialAppearance,
})
}
onDownload={() =>
downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))
}
onRemove={() => handleRemoveTheme(customTheme)}
onUse={() => {
const modes = getThemeModes(customTheme);
if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);
else persistTheme(customTheme.id);
}}
onUseMode={handlePairPick(customTheme.id)}
theme={card}
/>
);
})}
{customThemeCollections.map(([collectionId, themes]) => (
<CustomThemeCollectionCard
activeModesFor={pickedModesFor}
key={collectionId}
onDownload={(customTheme) =>
downloadThemeFile(`${customTheme.id}.json`, serializeThemeFile(customTheme))
}
onDuplicate={(customTheme) =>
openThemeEditor({
editingThemeId: null,
seedThemeId: customTheme.id,
seedName: `${customTheme.label} copy`,
initialAppearance,
})
}
onEdit={(customTheme) =>
openThemeEditor({
editingThemeId: customTheme.id,
seedThemeId: null,
seedName: null,
initialAppearance,
})
}
onRemove={(customTheme) => handleRemoveTheme(customTheme, themes)}
onUse={(customTheme) => {
const modes = getThemeModes(customTheme);
if (modes.length === 1) assignHalf(modes[0]!, customTheme.id);
else persistTheme(customTheme.id);
}}
onUseMode={(customTheme, mode) => handlePairPick(customTheme.id)(mode)}
themes={themes}
/>
))}
</div>
</TooltipProvider>
);
@@ -561,7 +857,7 @@ export function ThemeLibrary({
{renderModeTiles()}
<div className="flex min-h-8 flex-wrap items-center justify-between gap-3 px-3 pt-2 sm:px-4">
<h3 className="text-sm font-medium tracking-[-0.005em] text-foreground">Themes</h3>
<div className="flex flex-wrap items-center justify-end gap-3">
<div className="flex flex-wrap items-center justify-end gap-2">
<Button
size="xs"
variant="outline"
@@ -586,19 +882,9 @@ export function ThemeLibrary({
{renderPairGrid()}
<ThemeImportDialog
onImportedMany={(importedThemes, { updated }) => {
// An updated theme that is showing (as the base or either half)
// needs its palette re-applied.
if (
updated &&
importedThemes.some(
(imported) =>
getThemeDefinition(theme)?.id === imported.id ||
themeHalves?.light === imported.id ||
themeHalves?.dark === imported.id,
)
) {
refreshTheme();
}
// Re-apply after collection updates. The update may remove the
// selected variant, in which case the theme hook falls back safely.
if (updated) refreshTheme();
const verb = updated ? "updated" : "added";
toastManager.add(
stackedThreadToast({
@@ -639,23 +925,80 @@ export function ThemeLibrary({
onOpenChange={onImportOpenChange}
open={isImportOpen}
/>
<AlertDialog
open={themeToRemove !== null}
onOpenChange={(open) => {
if (!open) setThemeToRemove(null);
}}
>
<AlertDialog open={isThemeRemovalOpen} onOpenChange={setIsThemeRemovalOpen}>
<AlertDialogPopup>
<AlertDialogHeader>
<AlertDialogTitle>Remove “{removeDialogTheme?.label}”?</AlertDialogTitle>
<AlertDialogTitle>
{canRemoveCollection
? `Remove themes from “${removeDialogCollectionLabel}”?`
: `Remove “${removeDialogTheme?.label}”?`}
</AlertDialogTitle>
<AlertDialogDescription>
You can bring it back anytime by importing its JSON file.
{canRemoveCollection
? "Select the variants you want to remove. You can restore them by importing the extension again."
: "You can bring it back anytime by importing its JSON file."}
</AlertDialogDescription>
</AlertDialogHeader>
{canRemoveCollection ? (
<div className="grid max-h-72 grid-cols-1 gap-2 overflow-y-auto px-6 pb-6 sm:grid-cols-2">
{removeDialogCollectionThemes.map((customTheme) => {
const checked = themeIdsToRemoveSet.has(customTheme.id);
const card = getThemeCardDefinition(customTheme);
const checkboxId = `remove-theme-${customTheme.id}`;
return (
<label
className="group relative flex min-h-28 cursor-pointer flex-col items-center justify-center gap-2 rounded-lg border border-border/70 bg-muted/25 p-3 has-checked:border-ring has-checked:bg-accent/20 hover:bg-muted/40"
htmlFor={checkboxId}
key={customTheme.id}
>
<span className="absolute right-2 top-2 inline-grid size-5 grid-cols-1 sm:size-4">
<input
checked={checked}
className="col-start-1 row-start-1 size-full appearance-none rounded-sm border border-input bg-background outline-none checked:border-primary checked:bg-primary focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring dark:not-checked:bg-input/32 forced-colors:appearance-auto"
id={checkboxId}
name="themes-to-remove"
type="checkbox"
onChange={(event) => {
const shouldRemove = event.currentTarget.checked;
setThemeIdsToRemove((current) =>
shouldRemove
? [...current, customTheme.id]
: current.filter((themeId) => themeId !== customTheme.id),
);
}}
/>
<CheckIcon className="pointer-events-none col-start-1 row-start-1 size-3.5 shrink-0 self-center justify-self-center stroke-primary-foreground opacity-0 group-has-checked:opacity-100 sm:size-3" />
</span>
<span className="flex min-h-12 items-center justify-center gap-1">
{card.previews.map((preview) => (
<span
className="flex size-11 shrink-0 items-center justify-center"
key={preview.mode}
>
<span className="flex scale-75">
<ThemePreviewCircle colors={preview.colors} mode={preview.mode} />
</span>
</span>
))}
</span>
<p className="max-w-full truncate text-center text-base font-medium text-foreground sm:text-sm">
{customTheme.label}
</p>
</label>
);
})}
</div>
) : null}
<AlertDialogFooter>
<AlertDialogClose render={<Button variant="outline" />}>Cancel</AlertDialogClose>
<Button variant="destructive" onClick={handleConfirmRemoveTheme}>
Remove theme
<Button
disabled={themeIdsToRemove.length === 0}
variant="destructive"
onClick={handleConfirmRemoveTheme}
>
{canRemoveCollection
? `Remove selected${themeIdsToRemove.length > 0 ? ` (${themeIdsToRemove.length})` : ""}`
: "Remove theme"}
</Button>
</AlertDialogFooter>
</AlertDialogPopup>
@@ -1,6 +1,11 @@
import { ChartNoAxesColumnIcon, GitPullRequestIcon, SettingsIcon } from "lucide-react";
import {
ArrowLeftIcon,
ChartNoAxesColumnIcon,
GitPullRequestIcon,
SettingsIcon,
} from "lucide-react";
import { memo, useCallback } from "react";
import { Link, useNavigate } from "@tanstack/react-router";
import { Link, useLocation, useNavigate } from "@tanstack/react-router";
import { useEnvironmentIdentificationMode } from "../../hooks/useSettings";
import { cn } from "../../lib/utils";
@@ -22,8 +27,9 @@ import {
SidebarTrigger,
useSidebar,
} from "../ui/sidebar";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { SidebarProviderUpdatePill } from "./SidebarProviderUpdatePill";
import { SidebarUpdatePill } from "./SidebarUpdatePill";
import { SidebarUpdateArchitectureWarning, SidebarUpdatePill } from "./SidebarUpdatePill";
export const SidebarChromeHeader = memo(function SidebarChromeHeader({
isElectron,
@@ -114,6 +120,14 @@ function T3Wordmark() {
export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
const navigate = useNavigate();
const { isMobile, setOpenMobile } = useSidebar();
const currentFooterPage = useLocation({
select: (location) =>
location.pathname === "/usage"
? "usage"
: location.pathname === "/pull-requests"
? "pull-requests"
: null,
});
const primaryEnvironment = usePrimaryEnvironment();
const pullRequestsSupported =
primaryEnvironment?.serverConfig?.environment.capabilities.pullRequests === true;
@@ -138,31 +152,74 @@ export const SidebarChromeFooter = memo(function SidebarChromeFooter() {
void navigate({ to: "/usage" });
}, [isMobile, navigate, setOpenMobile]);
const handleBackClick = useCallback(() => {
closeMobileSidebar();
void navigate({ to: "/" });
}, [closeMobileSidebar, navigate]);
return (
<SidebarFooter className="p-[var(--sidebar-content-inset)]">
<SidebarProviderUpdatePill />
<SidebarUpdatePill />
<SidebarMenu>
{pullRequestsSupported ? (
<SidebarMenuItem>
<SidebarMenuButton onClick={handlePullRequestsClick}>
<GitPullRequestIcon />
<span>Pull Requests</span>
<SidebarUpdateArchitectureWarning />
<SidebarMenu className="flex-row items-center">
{currentFooterPage ? (
<SidebarMenuItem className="min-w-0 flex-1">
<SidebarMenuButton onClick={handleBackClick}>
<ArrowLeftIcon />
<span>Back</span>
</SidebarMenuButton>
</SidebarMenuItem>
) : null}
<SidebarMenuItem>
<SidebarMenuButton onClick={handleUsageClick}>
<ChartNoAxesColumnIcon />
<span>Usage</span>
</SidebarMenuButton>
</SidebarMenuItem>
<SidebarMenuItem>
<SidebarMenuButton onClick={handleSettingsClick}>
<SettingsIcon />
<span>Settings</span>
</SidebarMenuButton>
</SidebarMenuItem>
) : (
<>
<SidebarMenuItem className="shrink-0">
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuButton
aria-label="Settings"
onClick={handleSettingsClick}
size="icon"
>
<SettingsIcon />
</SidebarMenuButton>
}
/>
<TooltipPopup side="top">Settings</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
{pullRequestsSupported ? (
<SidebarMenuItem className="shrink-0">
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuButton
aria-label="Pull Requests"
onClick={handlePullRequestsClick}
size="icon"
>
<GitPullRequestIcon />
</SidebarMenuButton>
}
/>
<TooltipPopup side="top">Pull Requests</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
) : null}
<SidebarMenuItem className="shrink-0">
<Tooltip>
<TooltipTrigger
render={
<SidebarMenuButton aria-label="Usage" onClick={handleUsageClick} size="icon">
<ChartNoAxesColumnIcon />
</SidebarMenuButton>
}
/>
<TooltipPopup side="top">Usage</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
</>
)}
<SidebarUpdatePill />
</SidebarMenu>
</SidebarFooter>
);
@@ -1,10 +1,12 @@
import { DownloadIcon, RotateCwIcon, TriangleAlertIcon, XIcon } from "lucide-react";
import { DownloadIcon, RefreshCwIcon, RotateCwIcon, TriangleAlertIcon } from "lucide-react";
import { useCallback, useState } from "react";
import { isElectron } from "../../env";
import { cn } from "../../lib/utils";
import { ensureLocalApi } from "../../localApi";
import { useDesktopUpdateState } from "../../state/desktopUpdate";
import { stackedThreadToast, toastManager } from "../ui/toast";
import {
canCheckForUpdate,
getArm64IntelBuildWarningDescription,
getDesktopUpdateActionError,
getDesktopUpdateButtonTooltip,
@@ -12,12 +14,12 @@ import {
isDesktopUpdateButtonDisabled,
resolveDesktopUpdateButtonAction,
shouldShowArm64IntelBuildWarning,
shouldShowDesktopUpdateButton,
shouldToastDesktopUpdateActionResult,
} from "../desktopUpdate.logic";
import { showDesktopUpdateDownloadedToast } from "../desktopUpdate.toast";
import { Alert, AlertDescription, AlertTitle } from "../ui/alert";
import { Separator } from "../ui/separator";
import { SidebarMenuItem } from "../ui/sidebar";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
function keyReleaseNoteItems(items: ReadonlyArray<string>) {
@@ -41,16 +43,29 @@ function SidebarUpdateReleaseNotesTooltip({
}
return (
<div className="w-120 max-w-[calc(100vw-2rem)] text-left">
<div className="w-fit max-w-[min(24rem,calc(100vw-2rem))] text-left">
<div className="px-1">
<div className="text-sm leading-5 font-medium">{tooltip}</div>
{state.status === "available" ? (
<div>
<div className="whitespace-nowrap text-sm leading-5 font-medium">
Update ready to download
</div>
{state.availableVersion ? (
<div className="mt-0.5 text-xs leading-4 text-update-foreground">
{state.availableVersion}
</div>
) : null}
</div>
) : (
<div className="text-sm leading-5 font-medium">{tooltip}</div>
)}
</div>
<div className="max-h-[min(28rem,calc(100vh-6rem))] overflow-y-auto px-1 pt-4 pb-1">
{state.releaseNotes.map((releaseNote, index) => (
<div key={releaseNote.version}>
{index > 0 && <Separator className="my-3 bg-border/60" />}
<section>
<h3 className="text-muted-foreground text-xs leading-4 font-semibold">
<h3 className="text-foreground text-xs leading-4 font-semibold">
{index === 0 ? "What's changed" : `Changes in ${releaseNote.version}`}
</h3>
<ul className="mt-2 space-y-1.5 pl-4 text-xs leading-5 text-popover-foreground/90">
@@ -68,24 +83,50 @@ function SidebarUpdateReleaseNotesTooltip({
);
}
export function SidebarUpdatePill() {
export function SidebarUpdateArchitectureWarning() {
return isElectron ? <SidebarUpdateArchitectureWarningContent /> : null;
}
function SidebarUpdateArchitectureWarningContent() {
const state = useDesktopUpdateState();
const visible = shouldShowArm64IntelBuildWarning(state);
const description = state && visible ? getArm64IntelBuildWarningDescription(state) : null;
if (!visible || !description) return null;
return (
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8 text-xs">
<TriangleAlertIcon />
<AlertTitle>Intel build on Apple Silicon</AlertTitle>
<AlertDescription>{description}</AlertDescription>
</Alert>
);
}
export function SidebarUpdatePill() {
return isElectron ? <SidebarUpdateControl /> : null;
}
function SidebarUpdateControl() {
const state = useDesktopUpdateState();
const [dismissed, setDismissed] = useState(false);
const [isActionPending, setIsActionPending] = useState(false);
const visible = isElectron && shouldShowDesktopUpdateButton(state) && !dismissed;
const tooltip = state ? getDesktopUpdateButtonTooltip(state) : "Update available";
const disabled = isDesktopUpdateButtonDisabled(state);
const action = state ? resolveDesktopUpdateButtonAction(state) : "none";
const showArm64Warning = isElectron && shouldShowArm64IntelBuildWarning(state);
const arm64Description =
state && showArm64Warning ? getArm64IntelBuildWarningDescription(state) : null;
const isDownloading = state?.status === "downloading";
const isUpdateState = action !== "none" || isDownloading;
const tooltip = isUpdateState
? state
? getDesktopUpdateButtonTooltip(state)
: "Update available"
: state?.status === "checking"
? "Checking for updates…"
: "Check for updates";
const disabled = isUpdateState ? isDesktopUpdateButtonDisabled(state) : !canCheckForUpdate(state);
const handleAction = useCallback(async () => {
const bridge = window.desktopBridge;
if (!bridge || !state) return;
if (disabled || action === "none" || isActionPending) return;
if (disabled || isActionPending) return;
setIsActionPending(true);
@@ -165,99 +206,92 @@ export function SidebarUpdatePill() {
);
})
.finally(() => setIsActionPending(false));
return;
}
void bridge
.checkForUpdate()
.then((result) => {
if (result.checked) return;
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not check for updates",
description:
result.state.message ?? "Automatic updates are not available in this build.",
}),
);
})
.catch((error) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Could not check for updates",
description: error instanceof Error ? error.message : "Update check failed.",
}),
);
})
.finally(() => setIsActionPending(false));
}, [action, disabled, isActionPending, state]);
if (!visible && !showArm64Warning) return null;
return (
<div className="flex flex-col gap-1">
{showArm64Warning && arm64Description && (
<Alert variant="warning" className="rounded-2xl border-warning/40 bg-warning/8 text-xs">
<TriangleAlertIcon />
<AlertTitle>Intel build on Apple Silicon</AlertTitle>
<AlertDescription>{arm64Description}</AlertDescription>
</Alert>
)}
{visible && (
<div
className={`group/update relative flex h-7 w-full items-center rounded-lg bg-update-surface text-xs font-medium text-update-foreground ${
disabled ? " cursor-not-allowed opacity-60" : ""
}`}
>
<div className="pointer-events-none absolute inset-0 rounded-lg transition-colors group-has-[button.update-main:hover]/update:bg-update/12" />
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={tooltip}
aria-disabled={disabled || isActionPending || undefined}
disabled={disabled || isActionPending}
className="update-main relative flex h-full flex-1 items-center gap-2 px-2 enabled:cursor-pointer"
onClick={handleAction}
>
{action === "install" ? (
<>
<RotateCwIcon className="size-3.5" />
<span>Restart to update</span>
</>
) : state?.status === "downloading" ? (
<>
<DownloadIcon className="size-3.5" />
<span>
Downloading
{typeof state.downloadPercent === "number"
? ` (${Math.floor(state.downloadPercent)}%)`
: "…"}
</span>
</>
) : (
<>
<DownloadIcon className="size-3.5" />
<span>Update available</span>
</>
)}
</button>
}
/>
<TooltipPopup
align="start"
className={
state?.channel === "nightly" && state.releaseNotes.length > 0
? // pointer-events-auto overrides the positioner's pointer-events-none so the
// release notes stay open (and scrollable) when the cursor moves into them.
"pointer-events-auto max-w-none text-balance"
: undefined
}
side="top"
>
{state ? (
<SidebarUpdateReleaseNotesTooltip state={state} tooltip={tooltip} />
) : (
tooltip
<SidebarMenuItem className="ml-auto shrink-0">
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label={tooltip}
aria-disabled={disabled || isActionPending || undefined}
disabled={disabled || isActionPending}
className={cn(
"inline-flex size-8 items-center justify-center rounded-full outline-hidden ring-ring transition-colors enabled:cursor-pointer focus-visible:ring-2 disabled:cursor-not-allowed disabled:opacity-60",
isUpdateState
? "bg-update-surface text-update-foreground enabled:hover:bg-update/12"
: "text-[var(--sidebar-icon-color)] enabled:hover:bg-sidebar-row-hover enabled:hover:text-sidebar-foreground",
)}
</TooltipPopup>
</Tooltip>
{action === "download" && (
<Tooltip>
<TooltipTrigger
render={
<button
type="button"
aria-label="Dismiss update"
className="mr-1 inline-flex size-5 items-center justify-center rounded-md text-update-foreground transition-colors"
onClick={() => setDismissed(true)}
>
<XIcon className="size-3.5" />
</button>
onClick={handleAction}
>
{action === "install" ? (
<RotateCwIcon className="size-4" />
) : isUpdateState ? (
<DownloadIcon className="size-4" />
) : (
<RefreshCwIcon
className={cn("size-4", state?.status === "checking" && "animate-spin")}
/>
)}
</button>
}
/>
<TooltipPopup
align="center"
className={
isUpdateState && state?.channel === "nightly" && state.releaseNotes.length > 0
? // pointer-events-auto overrides the positioner's pointer-events-none so the
// release notes stay open (and scrollable) when the cursor moves into them.
"pointer-events-auto max-w-none text-balance"
: undefined
}
side="top"
style={
isUpdateState
? {
background:
"color-mix(in srgb, var(--update) 18%, color-mix(in srgb, var(--popover) var(--glass-opacity), transparent))",
borderColor: "var(--update-foreground)",
}
/>
<TooltipPopup side="top">Dismiss until next launch</TooltipPopup>
</Tooltip>
: undefined
}
variant={isUpdateState ? "glass" : "default"}
>
{isUpdateState && state ? (
<SidebarUpdateReleaseNotesTooltip state={state} tooltip={tooltip} />
) : (
tooltip
)}
</div>
)}
</div>
</TooltipPopup>
</Tooltip>
</SidebarMenuItem>
);
}
@@ -1,3 +1,6 @@
// @effect-diagnostics nodeBuiltinImport:off - Regression coverage compares shipped CSS with the sidebar width contract.
import * as NodeFS from "node:fs";
import { describe, expect, it } from "vite-plus/test";
import {
@@ -31,4 +34,22 @@ describe("thread sidebar width", () => {
it("keeps the sidebar minimum when the whole layout is narrower than its minimums", () => {
expect(resolveInitialThreadSidebarWidth(900, 700)).toBe(THREAD_SIDEBAR_MIN_WIDTH);
});
it("shows the desktop wordmark across the sidebar's full legal width range", () => {
const sidebarStyles = NodeFS.readFileSync(new URL("../index.css", import.meta.url), "utf8");
const desktopHeaderStyles = sidebarStyles.slice(
sidebarStyles.indexOf("@media (min-width: 48rem)"),
sidebarStyles.indexOf("/* Stage-channel sidebar art"),
);
const stageLabelThreshold = desktopHeaderStyles.match(
/@container sidebar-header \(min-width: ([\d.]+)rem\) \{\s*\.sidebar-brand-stage \{\s*display: inline-flex;/,
)?.[1];
expect(sidebarStyles).toMatch(/\.sidebar-brand \{\s*display: none;/);
expect(desktopHeaderStyles).toMatch(
/@media \(min-width: 48rem\) \{\s*\.sidebar-brand \{\s*display: flex;/,
);
expect(THREAD_SIDEBAR_MIN_WIDTH).toBe(13 * 16);
expect(Number(stageLabelThreshold) * 16).toBeGreaterThan(THREAD_SIDEBAR_MIN_WIDTH);
});
});
+1 -1
View File
@@ -97,7 +97,7 @@ function AutocompletePopup({
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-50 select-none"
className="z-[130] select-none"
data-slot="autocomplete-positioner"
side={side}
sideOffset={sideOffset}
+1 -1
View File
@@ -163,7 +163,7 @@ function ComboboxPopup({
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-50 select-none"
className="z-[130] select-none"
data-slot="combobox-positioner"
side={side}
sideOffset={sideOffset}
+1 -1
View File
@@ -42,7 +42,7 @@ function MenuPopup({
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-[60]"
className="z-[130]"
data-slot="menu-positioner"
side={side}
sideOffset={sideOffset}
+1 -1
View File
@@ -42,7 +42,7 @@ function PopoverPopup({
align={align}
alignOffset={alignOffset}
anchor={anchor}
className="z-[60] h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-transform data-instant:transition-none"
className="z-[130] h-(--positioner-height) w-(--positioner-width) max-w-(--available-width) transition-transform data-instant:transition-none"
data-slot="popover-positioner"
side={side}
sideOffset={sideOffset}
+1 -1
View File
@@ -132,7 +132,7 @@ function SelectPopup({
alignItemWithTrigger={alignItemWithTrigger}
alignOffset={alignOffset}
anchor={anchor}
className="z-50 select-none"
className="z-[130] select-none"
data-slot="select-positioner"
side={side}
sideOffset={sideOffset}
+126 -116
View File
@@ -268,16 +268,28 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
:root {
/* Dev artwork defaults. Built-in themes override these seven pigments in
the components layer; Nightly derives a darker matching palette. */
--stage-art-top: #67c2ff;
--stage-art-mid: #347ff8;
--stage-art-bottom: #1538d0;
--stage-art-highlight: #d4f6ff;
--stage-art-secondary: #65c8ff;
--stage-art-tertiary: #7c8bff;
--stage-art-line: #ddf7ff;
--stage-night-top: color-mix(in oklch, var(--stage-art-top) 38%, #32155b);
--stage-night-mid: color-mix(in oklch, var(--stage-art-mid) 38%, #151443);
--stage-night-bottom: color-mix(in oklch, var(--stage-art-bottom) 38%, #07152f);
--stage-art-top: oklch(0.782169 0.123386 240.226);
--stage-art-mid: oklch(0.616111 0.195824 259.735);
--stage-art-bottom: oklch(0.441553 0.232394 265.474);
--stage-art-highlight: oklch(0.951597 0.037289 215.482);
--stage-art-secondary: oklch(0.794668 0.12136 235.46);
--stage-art-tertiary: oklch(0.678991 0.170261 275.365);
--stage-art-line: oklch(0.959666 0.029238 218.179);
--stage-night-top: color-mix(
in oklch,
var(--stage-art-top) 38%,
oklch(0.283792 0.117327 297.201)
);
--stage-night-mid: color-mix(
in oklch,
var(--stage-art-mid) 38%,
oklch(0.227147 0.086086 277.99)
);
--stage-night-bottom: color-mix(
in oklch,
var(--stage-art-bottom) 38%,
oklch(0.200528 0.055699 261.216)
);
--stage-night-highlight: var(--stage-art-highlight);
--stage-night-secondary: color-mix(
in oklch,
@@ -289,13 +301,13 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
var(--stage-art-tertiary) 60%,
var(--stage-night-top)
);
--stage-night-line: color-mix(in oklch, var(--stage-art-line) 82%, white);
--stage-night-line: color-mix(in oklch, var(--stage-art-line) 82%, oklch(1 0 0));
}
.dark {
--stage-art-top: #3a7ad1;
--stage-art-mid: #2050ae;
--stage-art-bottom: #101f6e;
--stage-art-top: oklch(0.581473 0.149124 256.9);
--stage-art-mid: oklch(0.456509 0.159377 261.945);
--stage-art-bottom: oklch(0.291327 0.136578 267.649);
}
* {
@@ -328,10 +340,8 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
}
@media (min-width: 48rem) {
@container sidebar-header (min-width: 13.5rem) {
.sidebar-brand {
display: flex;
}
.sidebar-brand {
display: flex;
}
@container sidebar-header (min-width: 15.75rem) {
@@ -373,131 +383,131 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
These colors stay deliberately deep at the top edge so the white stage
wordmark and controls retain contrast in both appearance modes. */
html[data-theme-id="t3-chat"] {
--stage-art-top: #f28ac1;
--stage-art-mid: #cb3e86;
--stage-art-bottom: #73194f;
--stage-art-highlight: #ffe6f6;
--stage-art-secondary: #ff82bc;
--stage-art-tertiary: #c67bf1;
--stage-art-line: #ffe7f8;
--stage-art-top: oklch(0.760675 0.141361 348.019);
--stage-art-mid: oklch(0.588093 0.188832 353.138);
--stage-art-bottom: oklch(0.383959 0.135096 348.656);
--stage-art-highlight: oklch(0.949689 0.034241 339.171);
--stage-art-secondary: oklch(0.763402 0.163836 352.525);
--stage-art-tertiary: oklch(0.70819 0.180285 311.949);
--stage-art-line: oklch(0.952158 0.034194 336.179);
}
html.dark[data-theme-id="t3-chat"] {
--stage-art-top: #a8467e;
--stage-art-mid: #742253;
--stage-art-bottom: #390e2d;
--stage-art-highlight: #ffd8ee;
--stage-art-secondary: #de639e;
--stage-art-tertiary: #9c64cf;
--stage-art-line: #ffe4f4;
--stage-art-top: oklch(0.540689 0.143665 347.587);
--stage-art-mid: oklch(0.396586 0.126592 347.6);
--stage-art-bottom: oklch(0.249959 0.079694 340.523);
--stage-art-highlight: oklch(0.921297 0.051708 343.229);
--stage-art-secondary: oklch(0.667398 0.165674 352.549);
--stage-art-tertiary: oklch(0.609315 0.163722 306.315);
--stage-art-line: oklch(0.945349 0.036045 341.433);
}
html[data-theme-id="grove"] {
--stage-art-top: #6cc492;
--stage-art-mid: #2d8a5e;
--stage-art-bottom: #174a33;
--stage-art-highlight: #e4fff0;
--stage-art-secondary: #79d8a5;
--stage-art-tertiary: #d5b563;
--stage-art-line: #eafff2;
--stage-night-top: #286548;
--stage-night-mid: #174a35;
--stage-night-bottom: #0a2c21;
--stage-night-highlight: #c4eed5;
--stage-night-secondary: #54a878;
--stage-night-tertiary: #b79b4d;
--stage-night-line: #d7f6e2;
--stage-art-top: oklch(0.751465 0.112731 157.313);
--stage-art-mid: oklch(0.567105 0.11099 158.859);
--stage-art-bottom: oklch(0.367918 0.067635 160.558);
--stage-art-highlight: oklch(0.976387 0.034353 161.456);
--stage-art-secondary: oklch(0.80968 0.117071 158.817);
--stage-art-tertiary: oklch(0.784102 0.108047 88.516);
--stage-art-line: oklch(0.981098 0.027812 158.718);
--stage-night-top: oklch(0.45805 0.079616 160.092);
--stage-night-mid: oklch(0.368483 0.065631 162.719);
--stage-night-bottom: oklch(0.264797 0.044397 168.088);
--stage-night-highlight: oklch(0.912563 0.055173 158.974);
--stage-night-secondary: oklch(0.665652 0.109731 156.599);
--stage-night-tertiary: oklch(0.698651 0.103024 89.828);
--stage-night-line: oklch(0.945336 0.041923 157.222);
}
html.dark[data-theme-id="grove"] {
--stage-art-top: #438e65;
--stage-art-mid: #286447;
--stage-art-bottom: #123525;
--stage-art-highlight: #d2fbe2;
--stage-art-secondary: #62bf88;
--stage-art-tertiary: #c99b45;
--stage-art-line: #e0fae9;
--stage-night-top: #24523a;
--stage-night-mid: #113323;
--stage-night-bottom: #071d16;
--stage-night-highlight: #b5dfc4;
--stage-night-secondary: #478d66;
--stage-night-tertiary: #a9853b;
--stage-night-line: #d0ead9;
--stage-art-top: oklch(0.58719 0.09869 157.426);
--stage-art-mid: oklch(0.454979 0.079031 159.756);
--stage-art-bottom: oklch(0.297856 0.050355 161.167);
--stage-art-highlight: oklch(0.952407 0.053872 158.44);
--stage-art-secondary: oklch(0.732591 0.120606 155.853);
--stage-art-tertiary: oklch(0.716282 0.116547 80.563);
--stage-art-line: oklch(0.961577 0.035285 157.03);
--stage-night-top: oklch(0.398632 0.065534 158.601);
--stage-night-mid: oklch(0.290561 0.049694 160.456);
--stage-night-bottom: oklch(0.210147 0.03173 169.818);
--stage-night-highlight: oklch(0.866303 0.057526 156.796);
--stage-night-secondary: oklch(0.586553 0.093722 157.365);
--stage-night-tertiary: oklch(0.6364 0.101769 82.985);
--stage-night-line: oklch(0.913292 0.035718 156.976);
}
html[data-theme-id="ocean"] {
--stage-art-top: #77c9e3;
--stage-art-mid: #3384bd;
--stage-art-bottom: #174d7a;
--stage-art-highlight: #e5faff;
--stage-art-secondary: #70c9df;
--stage-art-tertiary: #5cc7be;
--stage-art-line: #e9fbff;
--stage-art-top: oklch(0.792993 0.088072 220.421);
--stage-art-mid: oklch(0.590296 0.116841 243.184);
--stage-art-bottom: oklch(0.409123 0.093718 247.98);
--stage-art-highlight: oklch(0.971217 0.023008 213.615);
--stage-art-secondary: oklch(0.788391 0.090856 215.684);
--stage-art-tertiary: oklch(0.76441 0.099607 187.893);
--stage-art-line: oklch(0.976025 0.019647 212.543);
}
html.dark[data-theme-id="ocean"] {
--stage-art-top: #4288ac;
--stage-art-mid: #285d84;
--stage-art-bottom: #132e49;
--stage-art-highlight: #d9f5ff;
--stage-art-secondary: #61b5d4;
--stage-art-tertiary: #51b8b3;
--stage-art-line: #dff7ff;
--stage-art-top: oklch(0.59663 0.089167 233.427);
--stage-art-mid: oklch(0.461094 0.084904 243.478);
--stage-art-bottom: oklch(0.294818 0.05947 250.526);
--stage-art-highlight: oklch(0.952907 0.032224 221.27);
--stage-art-secondary: oklch(0.732079 0.09296 224.414);
--stage-art-tertiary: oklch(0.720885 0.095495 190.903);
--stage-art-line: oklch(0.961039 0.027355 219.756);
}
html[data-theme-id="ember"] {
--stage-art-top: #f4a26e;
--stage-art-mid: #d66036;
--stage-art-bottom: #7c291e;
--stage-art-highlight: #fff0df;
--stage-art-secondary: #ffad77;
--stage-art-tertiary: #ef6f69;
--stage-art-line: #fff3e7;
--stage-night-top: #8a442c;
--stage-night-mid: #5c271c;
--stage-night-bottom: #32100d;
--stage-night-highlight: #ffd6ba;
--stage-night-secondary: #cb7148;
--stage-night-tertiary: #ad4b45;
--stage-night-line: #ffe0c9;
--stage-art-top: oklch(0.782439 0.118806 52.569);
--stage-art-mid: oklch(0.62863 0.15922 39.401);
--stage-art-bottom: oklch(0.404251 0.117664 30.424);
--stage-art-highlight: oklch(0.962469 0.02774 70.95);
--stage-art-secondary: oklch(0.815735 0.11904 53.659);
--stage-art-tertiary: oklch(0.69361 0.159346 24.787);
--stage-art-line: oklch(0.970313 0.02052 67.583);
--stage-night-top: oklch(0.470236 0.102322 39.355);
--stage-night-mid: oklch(0.345367 0.080697 33.217);
--stage-night-bottom: oklch(0.227386 0.056077 27.437);
--stage-night-highlight: oklch(0.903891 0.059281 56.181);
--stage-night-secondary: oklch(0.641705 0.126508 44.376);
--stage-night-tertiary: oklch(0.538694 0.129931 25.865);
--stage-night-line: oklch(0.926348 0.046029 58.73);
}
html.dark[data-theme-id="ember"] {
--stage-art-top: #ba6540;
--stage-art-mid: #803a29;
--stage-art-bottom: #3c1916;
--stage-art-highlight: #ffe1cd;
--stage-art-secondary: #e68156;
--stage-art-tertiary: #d85b58;
--stage-art-line: #ffe8d7;
--stage-night-top: #6a3425;
--stage-night-mid: #3e1b15;
--stage-night-bottom: #1d0d0b;
--stage-night-highlight: #efc4a9;
--stage-night-secondary: #a85e3f;
--stage-night-tertiary: #8f413e;
--stage-night-line: #f2d2bc;
--stage-art-top: oklch(0.597533 0.120694 43.455);
--stage-art-mid: oklch(0.437763 0.101287 34.86);
--stage-art-bottom: oklch(0.264269 0.055858 26.548);
--stage-art-highlight: oklch(0.929214 0.042638 55.801);
--stage-art-secondary: oklch(0.705592 0.137369 43.176);
--stage-art-tertiary: oklch(0.629583 0.158322 24.088);
--stage-art-line: oklch(0.945058 0.033906 58.824);
--stage-night-top: oklch(0.392352 0.081287 36.444);
--stage-night-mid: oklch(0.271305 0.056352 31.135);
--stage-night-bottom: oklch(0.182126 0.028154 27.774);
--stage-night-highlight: oklch(0.851007 0.061294 53.805);
--stage-night-secondary: oklch(0.560789 0.10645 42.953);
--stage-night-tertiary: oklch(0.476228 0.106656 24.165);
--stage-night-line: oklch(0.884931 0.046607 56.556);
}
html[data-theme-id="iris"] {
--stage-art-top: #b49ae8;
--stage-art-mid: #7a5ac4;
--stage-art-bottom: #422d80;
--stage-art-highlight: #f2eaff;
--stage-art-secondary: #b79af1;
--stage-art-tertiary: #ec79c7;
--stage-art-line: #f6eeff;
--stage-art-top: oklch(0.738305 0.113454 298.926);
--stage-art-mid: oklch(0.551826 0.159189 294.531);
--stage-art-bottom: oklch(0.37147 0.133317 289.999);
--stage-art-highlight: oklch(0.949472 0.029204 303.081);
--stage-art-secondary: oklch(0.745085 0.125892 298.647);
--stage-art-tertiary: oklch(0.73066 0.167815 340.964);
--stage-art-line: oklch(0.960278 0.024064 306.969);
}
html.dark[data-theme-id="iris"] {
--stage-art-top: #8063c4;
--stage-art-mid: #513990;
--stage-art-bottom: #261c53;
--stage-art-highlight: #e8ddff;
--stage-art-secondary: #9e83dc;
--stage-art-tertiary: #d96ab7;
--stage-art-line: #eee7ff;
--stage-art-top: oklch(0.57297 0.145973 295.185);
--stage-art-mid: oklch(0.419499 0.13752 292.131);
--stage-art-bottom: oklch(0.274235 0.095798 286.608);
--stage-art-highlight: oklch(0.916698 0.047206 300.224);
--stage-art-secondary: oklch(0.670994 0.13095 296.689);
--stage-art-tertiary: oklch(0.679357 0.165376 340.439);
--stage-art-line: oklch(0.940582 0.032921 299.076);
}
.workspace-topbar {
+526
View File
@@ -0,0 +1,526 @@
import { sha256 } from "@noble/hashes/sha2";
import JSZip from "jszip";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import {
importOpenVsxThemeExtension,
searchOpenVsxThemes,
type OpenVsxThemeExtension,
} from "./openVsxThemes";
import { getThemeColorsForMode, themeColorToHex } from "./themePalette";
const ASSET_ROOT = "https://open-vsx.org/api/demo/theme/1.0.0/file";
function extensionDetail(overrides: Record<string, unknown> = {}) {
return {
namespace: "demo",
name: "theme",
displayName: "Demo Theme",
description: "A nice theme",
version: "1.0.0",
downloadCount: 123456,
license: "MIT",
repository: "https://github.com/demo/theme",
files: {
icon: `${ASSET_ROOT}/icon.png`,
manifest: `${ASSET_ROOT}/package.json`,
sha256: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
download: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
},
...overrides,
};
}
afterEach(() => {
vi.useRealTimers();
vi.unstubAllGlobals();
});
describe("Open VSX themes", () => {
it("searches theme extensions and keeps only supported open-source licenses", async () => {
const fetchMock = vi.fn(async (input: RequestInfo | URL) => {
const url = String(input);
if (url.includes("/-/search?")) {
return new Response(
JSON.stringify({
extensions: [
{ namespace: "demo", name: "theme" },
{ namespace: "icons", name: "theme" },
{ namespace: "oversized", name: "theme" },
{ namespace: "unlicensed", name: "theme" },
{ namespace: "unavailable", name: "theme" },
{ namespace: "closed", name: "theme" },
{ namespace: "huge", name: "theme" },
],
}),
{ status: 200 },
);
}
if (url.endsWith("/icons/theme")) {
return new Response(
JSON.stringify(
extensionDetail({
namespace: "icons",
files: {
...extensionDetail().files,
manifest: `${ASSET_ROOT.replace("demo/theme", "icons/theme")}/package.json`,
},
}),
),
{ status: 200 },
);
}
if (url.endsWith("/oversized/theme")) {
return new Response(
JSON.stringify(
extensionDetail({
namespace: "oversized",
files: {
...extensionDetail().files,
download: `${ASSET_ROOT.replace("demo/theme", "oversized/theme")}/oversized.vsix`,
},
}),
),
{ status: 200 },
);
}
if (url.endsWith("/unlicensed/theme")) {
return new Response(
JSON.stringify(
extensionDetail({
namespace: "unlicensed",
files: {
...extensionDetail().files,
manifest: `${ASSET_ROOT.replace("demo/theme", "unlicensed/theme")}/package.json`,
},
}),
),
{ status: 200 },
);
}
if (url.endsWith("/unavailable/theme")) {
return new Response(
JSON.stringify(
extensionDetail({
namespace: "unavailable",
files: {
...extensionDetail().files,
download: `${ASSET_ROOT.replace("demo/theme", "unavailable/theme")}/unavailable.vsix`,
manifest: `${ASSET_ROOT.replace("demo/theme", "unavailable/theme")}/package.json`,
},
}),
),
{ status: 200 },
);
}
if (url.endsWith("/closed/theme")) {
return new Response(
JSON.stringify(extensionDetail({ namespace: "closed", license: "All Rights Reserved" })),
{ status: 200 },
);
}
if (url.endsWith("/huge/theme")) {
return new Response(JSON.stringify({ padding: "x".repeat(256 * 1024) }), { status: 200 });
}
if (url.endsWith("/oversized/theme/1.0.0/file/oversized.vsix")) {
return new Response(null, {
headers: { "content-length": String(20 * 1024 * 1024 + 1) },
status: 200,
});
}
if (url.endsWith("/unavailable/theme/1.0.0/file/unavailable.vsix")) {
return new Response(null, { status: 404 });
}
if (url.endsWith(".vsix")) {
return new Response(null, { headers: { "content-length": "1024" }, status: 200 });
}
if (url.endsWith("/icons/theme/1.0.0/file/package.json")) {
return new Response(JSON.stringify({ contributes: { iconThemes: [{}] } }), { status: 200 });
}
if (url.endsWith("/unlicensed/theme/1.0.0/file/package.json")) {
return new Response(
JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
{ status: 200 },
);
}
if (url.endsWith("/unavailable/theme/1.0.0/file/package.json")) {
return new Response(
JSON.stringify({ license: "MIT", contributes: { themes: [{ path: "./theme.json" }] } }),
{ status: 200 },
);
}
if (url.endsWith("/demo/theme/1.0.0/file/package.json")) {
return new Response(
JSON.stringify({ license: "MIT", contributes: { themes: [{ path: "./theme.json" }] } }),
{ status: 200 },
);
}
return new Response(JSON.stringify(extensionDetail()), { status: 200 });
});
vi.stubGlobal("fetch", fetchMock);
const results = await searchOpenVsxThemes(" dracula ");
expect(results).toEqual([
expect.objectContaining({
id: "demo.theme",
name: "Demo Theme",
publisher: "demo",
downloadCount: 123456,
iconUrl: `${ASSET_ROOT}/icon.png`,
sourceUrl: "https://github.com/demo/theme",
license: "MIT",
}),
]);
const searchUrl = new URL(String(fetchMock.mock.calls[0]![0]));
expect(searchUrl.searchParams.get("query")).toBe("dracula");
expect(searchUrl.searchParams.get("category")).toBe("Themes");
expect(searchUrl.searchParams.get("sortBy")).toBe("downloadCount");
expect(searchUrl.searchParams.get("sortOrder")).toBe("desc");
expect(searchUrl.searchParams.get("size")).toBe("16");
});
it("supports sorting theme searches", async () => {
const fetchMock = vi.fn(
async (..._args: unknown[]) =>
new Response(JSON.stringify({ extensions: [] }), { status: 200 }),
);
vi.stubGlobal("fetch", fetchMock);
await searchOpenVsxThemes("nord", { sortBy: "rating" });
const searchUrl = new URL(String(fetchMock.mock.calls[0]![0]));
expect(searchUrl.searchParams.get("sortBy")).toBe("rating");
expect(searchUrl.searchParams.get("sortOrder")).toBe("desc");
});
it("rejects malformed search responses", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response(JSON.stringify({ error: "unavailable" }), { status: 200 })),
);
await expect(searchOpenVsxThemes("nord")).rejects.toThrow(
"Open VSX returned an unreadable search response.",
);
});
it("reports an unavailable search when every detail request fails", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
if (String(input).includes("/-/search?")) {
return new Response(
JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),
{ status: 200 },
);
}
return new Response(null, { status: 429 });
}),
);
await expect(searchOpenVsxThemes("dracula")).rejects.toThrow(
"Open VSX theme details are unavailable",
);
});
it("reports an unavailable search when every detail response is malformed", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL) => {
if (String(input).includes("/-/search?")) {
return new Response(
JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),
{ status: 200 },
);
}
return new Response("{}", { status: 200 });
}),
);
await expect(searchOpenVsxThemes("dracula")).rejects.toThrow(
"Open VSX theme details are unavailable",
);
});
it("returns no results when every theme package is unavailable", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
const url = String(input);
if (url.includes("/-/search?")) {
return new Response(
JSON.stringify({ extensions: [{ namespace: "demo", name: "theme" }] }),
{ status: 200 },
);
}
if (url.endsWith("/demo/theme")) {
return new Response(JSON.stringify(extensionDetail()), { status: 200 });
}
if (init?.method === "HEAD") return new Response(null, { status: 404 });
return new Response(
JSON.stringify({ license: "MIT", contributes: { themes: [{ path: "./theme.json" }] } }),
{ status: 200 },
);
}),
);
await expect(searchOpenVsxThemes("dracula")).resolves.toEqual([]);
});
it("times out a stalled search request", async () => {
vi.useFakeTimers();
vi.stubGlobal(
"fetch",
vi.fn(
(_input: RequestInfo | URL, init?: RequestInit) =>
new Promise<Response>((_resolve, reject) => {
init?.signal?.addEventListener("abort", () => {
reject(new DOMException("The operation was aborted.", "AbortError"));
});
}),
),
);
const search = expect(searchOpenVsxThemes("dracula")).rejects.toThrow(
"Open VSX took too long to respond",
);
await vi.advanceTimersByTimeAsync(10_000);
await search;
});
it("downloads a verified VSIX, reads JSONC includes, and pairs contributed variants", async () => {
const zip = new JSZip();
zip.file("extension/.gitkeep", "");
zip.file(
"extension/themes/base.jsonc",
`{
// inherited workbench colors
"colors": {
"editor.foreground": "#eeeeee",
"focusBorder": "#8b5cf6",
},
}`,
);
zip.file(
"extension/themes/demo-dark.json",
`{
"include": "./base.jsonc",
"colors": { "editor.background": "#111111" }
}`,
);
zip.file(
"extension/themes/demo-light.json",
`{
"colors": {
"editor.background": "#fafafa",
"editor.foreground": "#222222",
"focusBorder": "#8b5cf6"
}
}`,
);
zip.file(
"extension/themes/demo.json",
`{
"colors": {
"editor.background": "#181818",
"editor.foreground": "#eeeeee"
}
}`,
);
const packagedManifest = {
publisher: "demo",
name: "theme",
version: "1.0.0",
license: "MIT",
contributes: {
themes: [
{ label: "Demo Dark", uiTheme: "vs-dark", path: "./themes/demo-dark.json" },
{ label: "Demo Light", uiTheme: "vs", path: "./themes/demo-light.json" },
{ label: "Demo", uiTheme: "vs-dark", path: "./themes/demo.json" },
],
},
};
let packageBytes = new ArrayBuffer(0);
let checksum = "";
const rebuildPackage = async () => {
zip.file("extension/package.json", JSON.stringify(packagedManifest));
packageBytes = await zip.generateAsync({
type: "arraybuffer",
comment: `PK\u0005\u0006${"x".repeat(26)}`,
});
checksum = [...sha256(new Uint8Array(packageBytes))]
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
};
await rebuildPackage();
// The public manifest is only a preflight hint. Imports must use the manifest
// inside the checksummed VSIX rather than this inconsistent contribution.
const manifest = {
contributes: { themes: [{ label: "Wrong", path: "./themes/missing.json" }] },
};
const extension: OpenVsxThemeExtension = {
collectionId: "open-vsx:demo.theme",
id: "demo.theme",
name: "Demo Theme",
publisher: "demo",
description: "",
downloadCount: 1,
iconUrl: null,
sourceUrl: null,
license: "MIT",
manifestUrl: `${ASSET_ROOT}/package.json`,
sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
version: "1.0.0",
vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
};
vi.stubGlobal(
"fetch",
vi.fn(async (input: string | URL | Request) => {
const url = String(input);
if (url === extension.manifestUrl) {
return new Response(JSON.stringify(manifest), { status: 200 });
}
if (url === extension.sha256Url) return new Response(`${checksum} demo.vsix`);
return new Response(packageBytes, {
status: 200,
headers: { "Content-Length": String(packageBytes.byteLength) },
});
}),
);
const themes = await importOpenVsxThemeExtension(extension);
expect(themes).toHaveLength(2);
expect(new Set(themes.map((theme) => theme.id)).size).toBe(2);
expect(themes.every((theme) => /^ovx-[a-z0-9-]+-[0-9a-f]{12}$/.test(theme.id))).toBe(true);
expect(themes.every((theme) => theme.collection?.id === "open-vsx:demo.theme")).toBe(true);
const paired = themes.find(
(theme) =>
getThemeColorsForMode(theme, "light") !== null &&
getThemeColorsForMode(theme, "dark") !== null,
)!;
expect(paired.label).toBe("Demo");
expect(themeColorToHex(paired.colors.canvas)).toBe("#fafafa");
expect(themeColorToHex(getThemeColorsForMode(paired, "dark")!.canvas)).toBe("#111111");
expect(themeColorToHex(getThemeColorsForMode(paired, "dark")!.text)).toBe("#eeeeee");
packagedManifest.contributes.themes[0]!.label = "Renamed Dark";
packagedManifest.contributes.themes[1]!.label = "Renamed Light";
packagedManifest.contributes.themes[2]!.label = "Renamed Solo";
await rebuildPackage();
const renamedThemes = await importOpenVsxThemeExtension(extension);
expect(renamedThemes.map((theme) => theme.id)).toEqual(themes.map((theme) => theme.id));
packagedManifest.contributes.themes.push({
label: "Duplicate Demo",
uiTheme: "vs-dark",
path: "./themes/demo.json",
});
await rebuildPackage();
const duplicatePathThemes = await importOpenVsxThemeExtension(extension);
expect(new Set(duplicatePathThemes.map((theme) => theme.id)).size).toBe(
duplicatePathThemes.length,
);
expect(themes.every(({ id }) => duplicatePathThemes.some((theme) => theme.id === id))).toBe(
true,
);
packagedManifest.contributes.themes.pop();
packagedManifest.contributes.themes[2]!.path = "./themes/missing.json";
await rebuildPackage();
await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
"could not be imported safely",
);
packagedManifest.contributes.themes[2]!.path = "./themes/demo.json";
packagedManifest.license = "Proprietary";
await rebuildPackage();
await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
"does not match its advertised license",
);
Reflect.deleteProperty(packagedManifest, "license");
await rebuildPackage();
await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow(
"does not match its advertised license",
);
});
it("stops import work when the request is cancelled", async () => {
const packageBytes = new Uint8Array([1, 2, 3]);
const checksum = [...sha256(packageBytes)]
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
const controller = new AbortController();
const extension: OpenVsxThemeExtension = {
collectionId: "open-vsx:demo.theme",
id: "demo.theme",
name: "Demo Theme",
publisher: "demo",
description: "",
downloadCount: 1,
iconUrl: null,
sourceUrl: null,
license: "MIT",
manifestUrl: `${ASSET_ROOT}/package.json`,
sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
version: "1.0.0",
vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
};
vi.stubGlobal(
"fetch",
vi.fn(async (input: string | URL | Request) => {
const url = String(input);
if (url === extension.manifestUrl) {
return new Response(
JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
);
}
if (url === extension.sha256Url) {
controller.abort();
return new Response(checksum);
}
return new Response(packageBytes);
}),
);
await expect(importOpenVsxThemeExtension(extension, controller.signal)).rejects.toMatchObject({
name: "AbortError",
});
});
it("rejects a package whose Open VSX checksum does not match", async () => {
const extension: OpenVsxThemeExtension = {
collectionId: "open-vsx:demo.theme",
id: "demo.theme",
name: "Demo Theme",
publisher: "demo",
description: "",
downloadCount: 1,
iconUrl: null,
sourceUrl: null,
license: "MIT",
manifestUrl: `${ASSET_ROOT}/package.json`,
sha256Url: `${ASSET_ROOT}/demo.theme-1.0.0.sha256`,
version: "1.0.0",
vsixUrl: `${ASSET_ROOT}/demo.theme-1.0.0.vsix`,
};
vi.stubGlobal(
"fetch",
vi.fn(async (input: string | URL | Request) => {
const url = String(input);
if (url === extension.manifestUrl) {
return new Response(
JSON.stringify({ contributes: { themes: [{ path: "./theme.json" }] } }),
);
}
if (url === extension.sha256Url) return new Response("0".repeat(64));
return new Response(new Uint8Array([1, 2, 3]));
}),
);
await expect(importOpenVsxThemeExtension(extension)).rejects.toThrow("integrity check");
});
});
+776
View File
@@ -0,0 +1,776 @@
import { sha256 } from "@noble/hashes/sha2";
import JSZip from "jszip";
import { parse, type ParseError } from "jsonc-parser";
import type { ThemeDefinition } from "./themePalette";
import {
isVsCodeThemeFile,
pairVsCodeThemes,
parseVsCodeThemeFile,
resolveThemeLabelCollisions,
} from "./vscodeThemeImport";
const OPEN_VSX_SEARCH_URL = "https://open-vsx.org/api/-/search";
const MAX_VSIX_BYTES = 20 * 1024 * 1024;
const MAX_SEARCH_BYTES = 512 * 1024;
const MAX_DETAIL_BYTES = 256 * 1024;
const MAX_MANIFEST_BYTES = 256 * 1024;
const SEARCH_REQUEST_TIMEOUT_MS = 10_000;
const MAX_THEME_BYTES = 256 * 1024;
const MAX_ZIP_ENTRIES = 2_000;
const MAX_UNCOMPRESSED_BYTES = 50 * 1024 * 1024;
const MAX_COMPRESSION_RATIO = 200;
const MAX_THEMES_PER_EXTENSION = 40;
const MAX_INCLUDE_DEPTH = 8;
const MAX_PACKAGE_PATH_LENGTH = 1_024;
const MAX_COLOR_VALUE_LENGTH = 128;
const MAX_RESOLVED_THEME_FILES = MAX_THEMES_PER_EXTENSION * MAX_INCLUDE_DEPTH;
const SUPPORTED_LICENSES = new Set([
"0BSD",
"Apache-2.0",
"BSD-2-Clause",
"BSD-3-Clause",
"CC0-1.0",
"ISC",
"MIT",
"MPL-2.0",
"Unlicense",
]);
const USED_WORKBENCH_COLORS = new Set([
"activityBar.background",
"activityBarBadge.background",
"badge.background",
"button.background",
"button.foreground",
"contrastBorder",
"descriptionForeground",
"disabledForeground",
"dropdown.background",
"dropdown.border",
"editor.background",
"editor.foreground",
"editor.selectionBackground",
"editorCursor.foreground",
"editorError.foreground",
"editorGroup.border",
"editorPane.background",
"editorWarning.foreground",
"editorWidget.background",
"errorForeground",
"focusBorder",
"foreground",
"input.border",
"input.placeholderForeground",
"list.activeSelectionBackground",
"list.hoverBackground",
"list.inactiveSelectionBackground",
"menu.background",
"panel.background",
"panel.border",
"progressBar.background",
"quickInput.background",
"scrollbarSlider.background",
"sideBar.background",
"sideBar.border",
"sideBar.foreground",
"terminal.background",
"terminal.foreground",
"terminal.selectionBackground",
"terminalCursor.foreground",
"textCodeBlock.background",
"textLink.foreground",
]);
export type OpenVsxThemeSort = "downloadCount" | "rating" | "timestamp" | "relevance";
export type OpenVsxThemeExtension = {
id: string;
collectionId: string;
name: string;
publisher: string;
description: string;
downloadCount: number;
iconUrl: string | null;
sourceUrl: string | null;
manifestUrl: string;
sha256Url: string;
vsixUrl: string;
version: string;
license: string;
};
export type OpenVsxThemeSearchOptions = {
signal?: AbortSignal;
sortBy?: OpenVsxThemeSort;
};
type ThemeContribution = { label?: unknown; uiTheme?: unknown; path?: unknown };
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function shortHash(value: string): string {
return [...sha256(new TextEncoder().encode(value))]
.slice(0, 6)
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
}
function openVsxThemeId(extensionId: string, source: string): string {
return `ovx-theme-${shortHash(`${extensionId}:${source}`)}`;
}
function openVsxCollectionId(extensionId: string): string {
const normalized = `open-vsx:${extensionId.toLowerCase()}`;
return /^[a-z0-9][a-z0-9.:-]{0,127}$/.test(normalized)
? normalized
: `open-vsx:${shortHash(extensionId)}`;
}
function trustedOpenVsxUrl(value: unknown): string | null {
if (typeof value !== "string") return null;
try {
const url = new URL(value);
return url.protocol === "https:" && url.hostname.toLowerCase() === "open-vsx.org"
? url.toString()
: null;
} catch {
return null;
}
}
function publicSourceUrl(value: unknown): string | null {
const rawValue =
typeof value === "string"
? value
: isRecord(value) && typeof value.url === "string"
? value.url
: null;
if (!rawValue) return null;
try {
const url = new URL(rawValue);
return url.protocol === "https:" && !url.username && !url.password ? url.toString() : null;
} catch {
return null;
}
}
function themeContributions(manifest: Record<string, unknown>): ThemeContribution[] {
const contributes = isRecord(manifest.contributes) ? manifest.contributes : null;
return Array.isArray(contributes?.themes)
? (contributes.themes.filter(isRecord) as ThemeContribution[])
: [];
}
function manifestLicenseMatches(manifest: Record<string, unknown>, license: string): boolean {
return (
typeof manifest.license === "string" &&
manifest.license.trim().toLowerCase() === license.toLowerCase()
);
}
function extensionFromDetail(value: unknown): OpenVsxThemeExtension | null {
if (!isRecord(value) || !isRecord(value.files)) {
throw new Error("Open VSX returned malformed theme details.");
}
const namespace = typeof value.namespace === "string" ? value.namespace.trim() : "";
const extensionName = typeof value.name === "string" ? value.name.trim() : "";
const displayName =
(typeof value.displayName === "string" ? value.displayName.trim() : "") || extensionName;
const version = typeof value.version === "string" ? value.version.trim() : "";
const license = typeof value.license === "string" ? value.license.trim() : "";
const manifestUrl = trustedOpenVsxUrl(value.files.manifest);
const sha256Url = trustedOpenVsxUrl(value.files.sha256);
const vsixUrl = trustedOpenVsxUrl(value.files.download);
if (!namespace || !extensionName || !version || !manifestUrl || !sha256Url || !vsixUrl) {
throw new Error("Open VSX returned malformed theme details.");
}
if (!SUPPORTED_LICENSES.has(license)) return null;
const id = `${namespace}.${extensionName}`;
return {
id,
collectionId: openVsxCollectionId(id),
name: displayName,
publisher: namespace,
description: typeof value.description === "string" ? value.description : "",
downloadCount:
typeof value.downloadCount === "number" && Number.isFinite(value.downloadCount)
? value.downloadCount
: 0,
iconUrl: trustedOpenVsxUrl(value.files.icon),
sourceUrl:
publicSourceUrl(value.repository) ??
publicSourceUrl(value.homepage) ??
publicSourceUrl(value.url),
manifestUrl,
sha256Url,
vsixUrl,
version,
license,
};
}
async function withSearchTimeout<T>(
operation: (signal: AbortSignal) => Promise<T>,
parentSignal?: AbortSignal,
): Promise<T> {
const controller = new AbortController();
const abort = () => controller.abort();
if (parentSignal?.aborted) abort();
else parentSignal?.addEventListener("abort", abort, { once: true });
const timeout = setTimeout(abort, SEARCH_REQUEST_TIMEOUT_MS);
try {
return await operation(controller.signal);
} catch (cause) {
if (controller.signal.aborted && !parentSignal?.aborted) {
throw new Error("Open VSX took too long to respond.", { cause });
}
throw cause;
} finally {
clearTimeout(timeout);
parentSignal?.removeEventListener("abort", abort);
}
}
export async function searchOpenVsxThemes(
query: string,
{ signal, sortBy = "downloadCount" }: OpenVsxThemeSearchOptions = {},
): Promise<OpenVsxThemeExtension[]> {
const searchText = query.trim();
if (!searchText) return [];
const url = new URL(OPEN_VSX_SEARCH_URL);
url.searchParams.set("query", searchText);
url.searchParams.set("category", "Themes");
url.searchParams.set("sortBy", sortBy);
url.searchParams.set("sortOrder", "desc");
// Ask for a few extras because results without a supported SPDX license
// are intentionally omitted.
url.searchParams.set("size", "16");
const value = await withSearchTimeout(async (requestSignal) => {
const response = await fetch(url, { signal: requestSignal });
if (!response.ok) throw new Error("Open VSX search is unavailable right now.");
const searchBytes = await readCappedResponse(
response,
MAX_SEARCH_BYTES,
"Open VSX returned an unexpectedly large response.",
);
try {
return JSON.parse(new TextDecoder().decode(searchBytes)) as unknown;
} catch {
throw new Error("Open VSX returned an unreadable response.");
}
}, signal);
if (!isRecord(value) || !Array.isArray(value.extensions)) {
throw new Error("Open VSX returned an unreadable search response.");
}
const identities = value.extensions.flatMap((candidate): Array<[string, string]> => {
if (!isRecord(candidate)) return [];
const namespace = typeof candidate.namespace === "string" ? candidate.namespace : "";
const name = typeof candidate.name === "string" ? candidate.name : "";
return namespace && name ? [[namespace, name]] : [];
});
const details = await Promise.allSettled(
identities.slice(0, 16).map(([namespace, name]) =>
withSearchTimeout(async (requestSignal) => {
const detailUrl = `https://open-vsx.org/api/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`;
const detailResponse = await fetch(detailUrl, { signal: requestSignal });
if (!detailResponse.ok) throw new Error("Open VSX theme details are unavailable.");
const detailBytes = await readCappedResponse(
detailResponse,
MAX_DETAIL_BYTES,
"Open VSX returned an unexpectedly large detail response.",
);
try {
const extension = extensionFromDetail(JSON.parse(new TextDecoder().decode(detailBytes)));
if (!extension) return null;
const [manifestResponse, packageResponse] = await Promise.all([
fetch(extension.manifestUrl, { signal: requestSignal }),
fetch(extension.vsixUrl, { method: "HEAD", signal: requestSignal }),
]);
if (!manifestResponse.ok) throw new Error("manifest unavailable");
if (!packageResponse.ok) return null;
const packageLength = Number(packageResponse.headers.get("content-length"));
if (Number.isFinite(packageLength) && packageLength > MAX_VSIX_BYTES) {
return null;
}
const manifestBytes = await readCappedResponse(
manifestResponse,
MAX_MANIFEST_BYTES,
"Open VSX returned an unexpectedly large manifest.",
);
const manifest = parseJsoncObject(
new TextDecoder().decode(manifestBytes),
"Extension manifest",
);
return themeContributions(manifest).length > 0 &&
manifestLicenseMatches(manifest, extension.license)
? extension
: null;
} catch {
throw new Error("Open VSX returned unreadable theme details.");
}
}, signal),
),
);
if (signal?.aborted) throw new DOMException("The operation was aborted.", "AbortError");
const completedDetails = details.filter((result) => result.status === "fulfilled");
if (identities.length > 0 && completedDetails.length === 0) {
throw new Error("Open VSX theme details are unavailable right now.");
}
return completedDetails.flatMap((result) => (result.value ? [result.value] : [])).slice(0, 8);
}
function parseJsoncObject(source: string, description: string): Record<string, unknown> {
const errors: ParseError[] = [];
const value: unknown = parse(source, errors, { allowTrailingComma: true });
if (errors.length > 0 || !isRecord(value)) throw new Error(`${description} is not valid JSON.`);
return value;
}
function sanitizeThemeObject(value: Record<string, unknown>): Record<string, unknown> {
const colors: Record<string, string> = {};
if (isRecord(value.colors)) {
for (const [key, color] of Object.entries(value.colors)) {
if (
USED_WORKBENCH_COLORS.has(key) &&
typeof color === "string" &&
color.length <= MAX_COLOR_VALUE_LENGTH
) {
colors[key] = color;
}
}
}
return {
...(typeof value.include === "string" ? { include: value.include } : {}),
colors,
};
}
function normalizePackagePath(path: string, relativeTo = "extension/"): string {
if (
path.length > MAX_PACKAGE_PATH_LENGTH ||
path.includes("\0") ||
path.startsWith("/") ||
/^[a-zA-Z]:/.test(path)
) {
throw new Error("Theme path is not a safe relative package path.");
}
const normalizedInput = path.replaceAll("\\", "/");
const baseSegments = relativeTo.split("/").slice(0, -1);
const segments = baseSegments;
for (const segment of normalizedInput.split("/")) {
if (!segment || segment === ".") continue;
if (segment === "..") {
if (segments.length <= 1) throw new Error("Theme path escapes the extension package.");
segments.pop();
continue;
}
segments.push(segment);
}
if (segments[0] !== "extension") segments.unshift("extension");
return segments.join("/");
}
function contributionType(uiTheme: unknown): string | null {
if (uiTheme === "vs") return "light";
if (uiTheme === "vs-dark") return "dark";
if (uiTheme === "hc-black" || uiTheme === "hc-light") return uiTheme;
return null;
}
type ZipEntrySizes = {
uncompressedSize?: unknown;
};
type InspectableZipObject = JSZip.JSZipObject & {
_data?: ZipEntrySizes;
unsafeOriginalName?: string;
internalStream?: (type: "uint8array") => JSZip.JSZipStreamHelper<Uint8Array>;
};
function inspectZipDirectory(bytes: Uint8Array): Uint8Array {
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
const minimumOffset = Math.max(0, bytes.byteLength - 65_557);
let endOffset = bytes.byteLength - 22;
while (
endOffset >= minimumOffset &&
(view.getUint32(endOffset, true) !== 0x06054b50 ||
endOffset + 22 + view.getUint16(endOffset + 20, true) !== bytes.byteLength)
) {
endOffset -= 1;
}
if (endOffset < minimumOffset) throw new Error("That extension package has no ZIP directory.");
const directorySize = view.getUint32(endOffset + 12, true);
const directoryOffset = view.getUint32(endOffset + 16, true);
const directoryEnd = directoryOffset + directorySize;
if (directoryEnd !== endOffset || directoryEnd > bytes.byteLength) {
throw new Error("That extension package has an invalid ZIP directory.");
}
let entryCount = 0;
let totalUncompressed = 0;
let offset = directoryOffset;
while (offset < directoryEnd) {
if (offset + 46 > directoryEnd || view.getUint32(offset, true) !== 0x02014b50) {
throw new Error("That extension package has an invalid ZIP directory.");
}
entryCount += 1;
if (entryCount > MAX_ZIP_ENTRIES) {
throw new Error("That extension package has too many files.");
}
const compressed = view.getUint32(offset + 20, true);
const uncompressed = view.getUint32(offset + 24, true);
if (compressed === 0xffffffff || uncompressed === 0xffffffff) {
throw new Error("That extension package has unsupported ZIP64 metadata.");
}
totalUncompressed += uncompressed;
if (totalUncompressed > MAX_UNCOMPRESSED_BYTES) {
throw new Error("That extension package expands beyond the safe import limit.");
}
if (
uncompressed > 0 &&
(compressed === 0 || uncompressed / compressed > MAX_COMPRESSION_RATIO)
) {
throw new Error("That extension package has an unsafe compression ratio.");
}
const nameLength = view.getUint16(offset + 28, true);
const extraLength = view.getUint16(offset + 30, true);
const commentLength = view.getUint16(offset + 32, true);
offset += 46 + nameLength + extraLength + commentLength;
}
if (offset !== directoryEnd)
throw new Error("That extension package has an invalid ZIP directory.");
const commentLength = view.getUint16(endOffset + 20, true);
if (commentLength === 0) return bytes;
// JSZip mistakes EOCD-like bytes inside an archive comment for the real EOCD.
// The comment is not needed for theme import, so remove it before parsing.
const withoutComment = bytes.slice(0, endOffset + 22);
withoutComment[endOffset + 20] = 0;
withoutComment[endOffset + 21] = 0;
return withoutComment;
}
function inspectZip(zip: JSZip): void {
const entries = Object.values(zip.files) as InspectableZipObject[];
if (entries.length > MAX_ZIP_ENTRIES)
throw new Error("That extension package has too many files.");
for (const entry of entries) {
if (entry.unsafeOriginalName) normalizePackagePath(entry.unsafeOriginalName);
}
}
async function readZipText(
zip: JSZip,
path: string,
description: string,
signal?: AbortSignal,
): Promise<string> {
signal?.throwIfAborted();
const file = zip.file(path) as InspectableZipObject | null;
if (!file) throw new Error(`${description} is missing from the extension package.`);
if (typeof file._data?.uncompressedSize !== "number" || !file.internalStream) {
throw new Error(`${description} has unreadable size metadata.`);
}
if (file._data.uncompressedSize > MAX_THEME_BYTES) {
throw new Error(`${description} is too large.`);
}
return new Promise((resolve, reject) => {
const chunks: Uint8Array[] = [];
let byteLength = 0;
let settled = false;
const stream = file.internalStream!("uint8array");
const cleanup = () => signal?.removeEventListener("abort", handleAbort);
const handleAbort = () => {
if (settled) return;
settled = true;
stream.pause();
cleanup();
reject(signal?.reason);
};
signal?.addEventListener("abort", handleAbort, { once: true });
stream
.on("data", (chunk) => {
if (settled) return;
byteLength += chunk.byteLength;
if (byteLength > MAX_THEME_BYTES) {
settled = true;
stream.pause();
cleanup();
reject(new Error(`${description} is too large.`));
return;
}
chunks.push(chunk);
})
.on("error", (cause) => {
if (settled) return;
settled = true;
cleanup();
reject(cause);
})
.on("end", () => {
if (settled) return;
settled = true;
cleanup();
const bytes = new Uint8Array(byteLength);
let offset = 0;
for (const chunk of chunks) {
bytes.set(chunk, offset);
offset += chunk.byteLength;
}
resolve(new TextDecoder().decode(bytes));
})
.resume();
});
}
async function loadThemeObject(
zip: JSZip,
path: string,
cache: Map<string, Record<string, unknown>>,
budget: { files: number },
ancestors: ReadonlySet<string> = new Set(),
signal?: AbortSignal,
): Promise<Record<string, unknown>> {
signal?.throwIfAborted();
if (ancestors.size >= MAX_INCLUDE_DEPTH) throw new Error("Theme includes are nested too deeply.");
if (ancestors.has(path)) throw new Error("Theme includes contain a cycle.");
const cached = cache.get(path);
if (cached) return cached;
budget.files += 1;
if (budget.files > MAX_RESOLVED_THEME_FILES) {
throw new Error("That extension references too many theme files.");
}
const value = sanitizeThemeObject(
parseJsoncObject(await readZipText(zip, path, path, signal), path),
);
if (typeof value.include !== "string") {
cache.set(path, value);
return value;
}
const includePath = normalizePackagePath(value.include, path);
const nextAncestors = new Set(ancestors);
nextAncestors.add(path);
const base = await loadThemeObject(zip, includePath, cache, budget, nextAncestors, signal);
const resolved = {
...base,
...value,
colors: {
...(isRecord(base.colors) ? base.colors : {}),
...(isRecord(value.colors) ? value.colors : {}),
},
};
cache.set(path, resolved);
return resolved;
}
async function readCappedResponse(
response: Response,
limit: number,
tooLargeMessage: string,
): Promise<Uint8Array> {
const contentLength = response.headers.get("content-length");
if (contentLength && Number(contentLength) > limit) throw new Error(tooLargeMessage);
if (!response.body) {
const bytes = new Uint8Array(await response.arrayBuffer());
if (bytes.byteLength > limit) throw new Error(tooLargeMessage);
return bytes;
}
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let byteLength = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
byteLength += value.byteLength;
if (byteLength > limit) {
await reader.cancel();
throw new Error(tooLargeMessage);
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const result = new Uint8Array(byteLength);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.byteLength;
}
return result;
}
async function fetchPackage(url: string, signal?: AbortSignal): Promise<Uint8Array> {
const response = await fetch(url, signal ? { signal } : {});
if (!response.ok) throw new Error("That Open VSX theme could not be downloaded.");
return readCappedResponse(
response,
MAX_VSIX_BYTES,
"That theme extension is too large to import safely.",
);
}
export async function importOpenVsxThemeExtension(
extension: OpenVsxThemeExtension,
signal?: AbortSignal,
): Promise<ReadonlyArray<ThemeDefinition>> {
const manifestResponse = await fetch(extension.manifestUrl, signal ? { signal } : {});
if (!manifestResponse.ok) throw new Error("That Open VSX extension has no readable manifest.");
const manifestBytes = await readCappedResponse(
manifestResponse,
MAX_MANIFEST_BYTES,
"That Open VSX extension manifest is too large.",
);
const manifest = parseJsoncObject(new TextDecoder().decode(manifestBytes), "Extension manifest");
const advertisedContributions = themeContributions(manifest);
if (advertisedContributions.length === 0) {
throw new Error("That extension does not contain color themes.");
}
if (advertisedContributions.length > MAX_THEMES_PER_EXTENSION) {
throw new Error("That extension contains too many color themes to import safely.");
}
const packageBytes = await fetchPackage(extension.vsixUrl, signal);
signal?.throwIfAborted();
const checksumResponse = await fetch(extension.sha256Url, signal ? { signal } : {});
if (!checksumResponse.ok) throw new Error("That Open VSX theme has no readable checksum.");
const expectedChecksum = new TextDecoder()
.decode(
await readCappedResponse(
checksumResponse,
256,
"That Open VSX checksum response is invalid.",
),
)
.trim()
.split(/\s+/)[0];
if (!expectedChecksum || !/^[a-f\d]{64}$/i.test(expectedChecksum)) {
throw new Error("That Open VSX theme has an invalid checksum.");
}
signal?.throwIfAborted();
const actualChecksum = [...sha256(packageBytes)]
.map((byte) => byte.toString(16).padStart(2, "0"))
.join("");
if (actualChecksum.toLowerCase() !== expectedChecksum.toLowerCase()) {
throw new Error("That Open VSX theme failed its integrity check.");
}
signal?.throwIfAborted();
let zip: JSZip;
try {
const inspectedPackageBytes = inspectZipDirectory(packageBytes);
zip = await JSZip.loadAsync(inspectedPackageBytes);
signal?.throwIfAborted();
inspectZip(zip);
} catch (cause) {
if (signal?.aborted) signal.throwIfAborted();
if (cause instanceof Error && cause.message.startsWith("That extension package")) throw cause;
throw new Error("That Open VSX extension package could not be opened.", { cause });
}
const packagedManifest = parseJsoncObject(
await readZipText(zip, "extension/package.json", "Extension manifest", signal),
"Extension manifest",
);
if (
typeof packagedManifest.publisher !== "string" ||
packagedManifest.publisher.toLowerCase() !== extension.publisher.toLowerCase() ||
typeof packagedManifest.name !== "string" ||
`${packagedManifest.publisher}.${packagedManifest.name}`.toLowerCase() !==
extension.id.toLowerCase() ||
packagedManifest.version !== extension.version
) {
throw new Error("That extension package does not match the selected Open VSX theme.");
}
if (!manifestLicenseMatches(packagedManifest, extension.license)) {
throw new Error("That extension package does not match its advertised license.");
}
const contributions = themeContributions(packagedManifest);
if (contributions.length === 0) throw new Error("That extension does not contain color themes.");
if (contributions.length > MAX_THEMES_PER_EXTENSION) {
throw new Error("That extension contains too many color themes to import safely.");
}
const parsed: Array<{ theme: ThemeDefinition; sourceName: string; sourcePath: string }> = [];
const failures: string[] = [];
const themeCache = new Map<string, Record<string, unknown>>();
const themeBudget = { files: 0 };
for (const contribution of contributions) {
signal?.throwIfAborted();
if (typeof contribution.path !== "string") {
failures.push("theme path is missing");
continue;
}
try {
const path = normalizePackagePath(contribution.path);
const themeValue = await loadThemeObject(
zip,
path,
themeCache,
themeBudget,
new Set(),
signal,
);
const type = contributionType(contribution.uiTheme);
const label =
typeof contribution.label === "string" && contribution.label.trim()
? contribution.label.trim()
: extension.name;
const decorated = {
...themeValue,
displayName: label,
...(type ? { type } : {}),
};
if (!isVsCodeThemeFile(decorated)) throw new Error("not a VS Code color theme");
parsed.push({
theme: parseVsCodeThemeFile(decorated),
sourceName: path.split("/").at(-1)!,
sourcePath: path,
});
} catch (cause) {
signal?.throwIfAborted();
failures.push(cause instanceof Error ? cause.message : "theme could not be read");
}
}
if (failures.length > 0) {
throw new Error("One or more color themes in that extension could not be imported safely.");
}
if (parsed.length === 0) {
throw new Error("That extension has no compatible color themes.");
}
const extensionId = extension.id.toLowerCase();
const sourcePathCounts = new Map<string, number>();
for (const { sourcePath } of parsed) {
sourcePathCounts.set(sourcePath, (sourcePathCounts.get(sourcePath) ?? 0) + 1);
}
const sourcePathOccurrences = new Map<string, number>();
const sourceIdentities = parsed.map(({ sourcePath }) => {
if (sourcePathCounts.get(sourcePath) === 1) return sourcePath;
const occurrence = sourcePathOccurrences.get(sourcePath) ?? 0;
sourcePathOccurrences.set(sourcePath, occurrence + 1);
return occurrence === 0 ? sourcePath : `${sourcePath}\0${occurrence}`;
});
const resolved = resolveThemeLabelCollisions(parsed).map((theme, index) => ({
...theme,
id: openVsxThemeId(extensionId, sourceIdentities[index]!),
}));
const paired = pairVsCodeThemes(resolved, {
pairedId: (light, dark) => openVsxThemeId(extensionId, [light.id, dark.id].sort().join(":")),
});
const themes = resolveThemeLabelCollisions(paired.map((theme) => ({ theme })));
const collection = {
id: extension.collectionId,
label: extension.name.slice(0, 48),
};
return themes.map((theme) => ({ ...theme, collection }));
}
@@ -120,22 +120,6 @@ describe("createOrchestrationRecoveryCoordinator", () => {
});
});
it("keeps enough state to explain why bootstrap snapshot recovery requests replay", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
expect(coordinator.beginSnapshotRecovery("bootstrap")).toBe(true);
expect(coordinator.classifyDomainEvent(4)).toBe("defer");
expect(coordinator.completeSnapshotRecovery(2)).toBe(true);
expect(coordinator.getState()).toMatchObject({
latestSequence: 2,
highestObservedSequence: 4,
bootstrapped: true,
pendingReplay: false,
inFlight: null,
});
});
it("reports skip state when snapshot recovery is requested while replay is in flight", () => {
const coordinator = createOrchestrationRecoveryCoordinator();
+66 -3
View File
@@ -15,6 +15,7 @@ import {
OCEAN_THEME,
THEME_APPEARANCE_MODE_STORAGE_KEY,
THEME_FOLLOW_SYSTEM_STORAGE_KEY,
toCanonicalThemeColor,
} from "./themePalette";
const THEME_STORAGE_KEY = "t3code:theme";
@@ -83,7 +84,12 @@ function runBootScript(options: {
matchMedia: () => ({ matches: options.prefersDark }),
};
new Function("window", "document", bootScript)(fakeWindow, fakeDocument);
const fakeCss = {
supports: (property: string, value: string) =>
property === "color" && toCanonicalThemeColor(value) !== null,
};
new Function("window", "document", "CSS", bootScript)(fakeWindow, fakeDocument, fakeCss);
return {
isDark: classes.has("dark"),
@@ -275,6 +281,63 @@ describe("index.html boot script", () => {
expect(aurora.metaContent).toBe(DEFAULT_DARK_CHROME);
});
it("accepts exponent-form OKLCH before the runtime mounts", () => {
const colors = {
canvas: "oklch(9.5e-1 1e-2 2.8e2)",
chrome: "oklch(9.4e-1 1e-2 2.8e2)",
text: "oklch(2e-1 0 0 / 9e-1)",
accent: "oklch(6.2e-1 0.2 2.8e2)",
};
const boot = runBootScript({
storage: {
[THEME_STORAGE_KEY]: "scientific",
[CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([
{
id: "scientific",
label: "Scientific",
appearance: "light",
colors,
},
]),
},
prefersDark: false,
});
expect(boot.bootVariables["--boot-background"]).toBe(colors.canvas);
expect(boot.bootVariables["--boot-foreground"]).toBe(colors.text);
expect(boot.bootVariables["--boot-accent"]).toBe(colors.accent);
expect(boot.backgroundColor).toBe(colors.chrome);
expect(boot.metaContent).toBe(colors.chrome);
});
it("accepts legacy CSS color formats before the runtime mounts", () => {
const colors = {
canvas: "rgb(248 251 255)",
chrome: "hsl(210 100% 99%)",
text: "rebeccapurple",
accent: "color(display-p3 0.36 0.42 1)",
};
const boot = runBootScript({
storage: {
[THEME_STORAGE_KEY]: "legacy-css",
[CUSTOM_THEMES_STORAGE_KEY]: JSON.stringify([
{
id: "legacy-css",
label: "Legacy CSS",
appearance: "light",
colors,
},
]),
},
prefersDark: false,
});
expect(boot.bootVariables["--boot-background"]).toBe(colors.canvas);
expect(boot.bootVariables["--boot-foreground"]).toBe(colors.text);
expect(boot.bootVariables["--boot-accent"]).toBe(colors.accent);
expect(boot.backgroundColor).toBe(colors.chrome);
});
// Asserting against the real palette definitions (not literals) turns the
// 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.
@@ -410,9 +473,9 @@ describe("index.html boot script", () => {
});
expect(boot.themeId).toBe("partial");
expect(boot.bootVariables["--boot-background"]).toBe("#1f1a24");
expect(boot.bootVariables["--boot-background"]).toBe(getDefaultThemeColors("dark").canvas);
expect(boot.bootVariables["--boot-foreground"]).toBe("#fffaff");
expect(boot.bootVariables["--boot-accent"]).toBe("#a3004c");
expect(boot.bootVariables["--boot-accent"]).toBe(getDefaultThemeColors("dark").accent);
expect(boot.backgroundColor).toBe(DEFAULT_DARK_CHROME);
expect(boot.metaContent).toBe(DEFAULT_DARK_CHROME);
});
+533 -49
View File
@@ -10,11 +10,15 @@ import {
getThemePreferenceMode,
isKnownThemePreference,
getCustomThemes,
getStoredCustomThemeCollection,
invalidateCustomThemes,
installCustomTheme,
canonicalThemePreference,
parseThemeFile,
parseThemeHalves,
removeCustomTheme,
removeCustomThemes,
replaceCustomThemeCollection,
resolveDesktopTheme,
resolveThemeAppearance,
serializeThemeFile,
@@ -31,12 +35,35 @@ import {
createManagedThemeColors,
createVividThemeColors,
getDefaultThemeColors,
themeColorToHex,
toCanonicalThemeColor,
THEME_FILE_VERSION,
} from "./themePalette";
function asHex(value: string): string {
const hex = themeColorToHex(value);
if (!hex) throw new Error(`Expected a theme color, received ${value}`);
return hex.slice(0, 7);
}
function canonical(value: string): string {
const color = toCanonicalThemeColor(value);
if (!color) throw new Error(`Expected a theme color, received ${value}`);
return color;
}
function expectThemeColors(
colors: Readonly<Record<string, string>>,
expected: Readonly<Record<string, string>>,
): void {
for (const [role, value] of Object.entries(expected)) {
expect(asHex(colors[role]!)).toBe(value);
}
}
function contrastRatio(first: string, second: string): number {
const toRgb = (value: string) => {
const hex = value.slice(1);
const hex = asHex(value).slice(1);
return [0, 1, 2].map(
(channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
);
@@ -56,8 +83,8 @@ describe("theme files", () => {
const dark = createManagedThemeColors("dark", "#ffffff", "#ffff00");
const darkDefaults = getDefaultThemeColors("dark");
expect(light.canvas).not.toBe("#111827");
expect(dark.canvas).not.toBe("#ffffff");
expect(asHex(light.canvas)).not.toBe("#111827");
expect(asHex(dark.canvas)).not.toBe("#ffffff");
expect(contrastRatio(light.accent, light.canvas)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(dark.accent, dark.canvas)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(light.textMuted, light.canvas)).toBeGreaterThanOrEqual(4.5);
@@ -73,7 +100,7 @@ describe("theme files", () => {
// Status colors fall back to T3 Code's standard red and amber rather than
// the flagship palette's, so no generated theme inherits a brand tint.
const channels = (value: string) =>
[1, 3, 5].map((index) => Number.parseInt(value.slice(index, index + 2), 16)) as [
[1, 3, 5].map((index) => Number.parseInt(asHex(value).slice(index, index + 2), 16)) as [
number,
number,
number,
@@ -92,7 +119,7 @@ describe("theme files", () => {
expect(warnRed).toBeGreaterThan(warnBlue);
expect(warnGreen).toBeGreaterThan(warnBlue);
}
expect(dark.error).not.toBe(darkDefaults.error);
expect(asHex(dark.error)).not.toBe(asHex(darkDefaults.error));
});
it("derives readable, distinctive vivid palettes from exact seeds", () => {
@@ -108,8 +135,10 @@ describe("theme files", () => {
for (const [appearance, canvas, accent] of seeds) {
const colors = createVividThemeColors(appearance, canvas, accent);
// Exact seeds are honored.
expect(colors.canvas).toBe(canvas);
expect(colors.accent).toBe(accent);
expect(colors.canvas).toMatch(/^oklch\(/);
expect(colors.accent).toMatch(/^oklch\(/);
expect(asHex(colors.canvas)).toBe(canvas);
expect(asHex(colors.accent)).toBe(accent);
// Readability is solved per surface.
expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(7);
expect(contrastRatio(colors.textMuted, colors.canvas)).toBeGreaterThanOrEqual(4.5);
@@ -131,7 +160,7 @@ describe("theme files", () => {
// The companion action is a distinct voice, not the accent again.
expect(colors.messageAction).not.toBe(colors.accent);
// Update family follows the theme, not the default palette.
expect(colors.update).toBe(accent);
expect(asHex(colors.update)).toBe(accent);
}
});
@@ -170,13 +199,53 @@ describe("theme files", () => {
label: "Ocean dusk",
appearance: "dark",
colors: {
canvas: "#07152f",
accent: "#67c2ff",
placeholder: "#968d9f",
canvas: canonical("#07152f"),
accent: canonical("#67c2ff"),
placeholder: canonical("#968d9f"),
},
});
});
it("decodes literal CSS color formats into OKLCH without dropping alpha", () => {
const theme = parseThemeFile({
version: THEME_FILE_VERSION,
name: "Translucent",
appearance: "light",
colors: {
canvas: "oklch(62% 0.2 280deg / 50%)",
accent: "#abcd",
focus: "rgb(10 20 30 / 50%)",
error: "hsl(350 80% 50%)",
warning: "hwb(45 10% 20%)",
update: "lab(60% 40 30)",
messageAction: "lch(60% 50 120)",
sidebar: "oklab(0.6 0.1 -0.1)",
terminalCursor: "color(display-p3 0.8 0.2 0.3)",
terminalSelection: "rebeccapurple",
terminalScrollbar: "transparent",
terminalScrollbarHover: "rgb(10 20 30 / none)",
},
});
expect(theme.colors.canvas).toBe("oklch(0.62 0.2 280 / 0.5)");
expect(theme.colors.accent).toBe(canonical("#abcd"));
expect(themeColorToHex(theme.colors.accent)).toBe("#aabbccdd");
expect(themeColorToHex(theme.colors.focus)).toBe("#0a141e80");
expect(themeColorToHex(theme.colors.terminalSelection)).toBe("#663399");
expect(theme.colors.terminalScrollbar).toBe("oklch(0 0 0 / 0)");
expect(themeColorToHex(theme.colors.terminalScrollbarHover)).toBe("#0a141e00");
for (const role of [
"error",
"warning",
"update",
"messageAction",
"sidebar",
"terminalCursor",
] as const) {
expect(theme.colors[role]).toMatch(/^oklch\(/);
}
});
it("rejects unknown roles and invalid color values", () => {
expect(() =>
parseThemeFile({
@@ -194,19 +263,45 @@ describe("theme files", () => {
appearance: "light",
colors: { accent: "var(--danger)" },
}),
).toThrow('The color for "accent" must be a hex color');
).toThrow('The color for "accent" must be a literal CSS color');
});
it("serializes a theme back into the importable file shape", () => {
const serialized = serializeThemeFile(T3_CHAT_THEME);
it("canonicalizes the explicitly exported theme", () => {
const serialized = serializeThemeFile({
...T3_CHAT_THEME,
colors: { ...T3_CHAT_THEME.colors, accent: "hsl(263 70% 58%)" },
});
expect(JSON.parse(serialized)).toMatchObject({
version: THEME_FILE_VERSION,
id: T3_CHAT_THEME.id,
name: T3_CHAT_THEME.label,
appearance: "light",
colors: { accent: canonical("hsl(263 70% 58%)") },
});
});
it("serializes a theme back into the importable file shape", () => {
const theme = {
...parseThemeFile({
version: THEME_FILE_VERSION,
id: "community-demo",
name: "Community Demo",
appearance: "dark",
colors: { canvas: "#111111" },
}),
collection: { id: "open-vsx:demo.theme", label: "Demo Theme" },
};
const serialized = serializeThemeFile(theme);
expect(JSON.parse(serialized)).toMatchObject({
version: THEME_FILE_VERSION,
id: theme.id,
name: theme.label,
appearance: "dark",
collection: theme.collection,
});
expect(parseThemeFile(JSON.parse(serialized)).collection).toEqual(theme.collection);
});
it("keeps sidebar artwork disabled for custom theme files", () => {
const theme = parseThemeFile({
version: THEME_FILE_VERSION,
@@ -257,8 +352,8 @@ describe("theme files", () => {
expect(getThemeModes(theme)).toEqual(["light", "dark"]);
expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
canvas: "#101827",
text: "#eef5ff",
canvas: canonical("#101827"),
text: canonical("#eef5ff"),
});
expect(getThemeModes(T3_CHAT_THEME)).toEqual(["light", "dark"]);
expect(resolveThemeAppearance(T3_CHAT_THEME.id, true, true)).toBe("dark");
@@ -266,13 +361,13 @@ describe("theme files", () => {
expect(resolveThemeAppearance(T3_CHAT_THEME.id, false, false, "dark")).toBe("dark");
expect(resolveDesktopTheme(T3_CHAT_THEME.id, false, "dark")).toBe("dark");
expect(JSON.parse(serializeThemeFile(theme)).variants.dark).toMatchObject({
canvas: "#101827",
text: "#eef5ff",
canvas: canonical("#101827"),
text: canonical("#eef5ff"),
});
});
it("keeps the T3 Chat palette faithful and readable", () => {
expect(T3_CHAT_THEME.colors).toMatchObject({
expectThemeColors(T3_CHAT_THEME.colors, {
canvas: "#fdf7fd",
chrome: "#fdf7fd",
toolbarBorder: "#efbdeb",
@@ -287,7 +382,7 @@ describe("theme files", () => {
accentSurface: "#f3e6f5",
sidebar: "#f2e1f4",
});
expect(T3_CHAT_THEME.variants?.dark).toMatchObject({
expectThemeColors(T3_CHAT_THEME.variants!.dark!, {
canvas: "#1f1a24",
chrome: "#1f1a24",
surface: "#29232d",
@@ -321,8 +416,8 @@ describe("theme files", () => {
expect(getThemeModes(theme)).toEqual(["light", "dark"]);
expect(theme.sidebarArtwork).toBe(true);
expect(themeAllowsSidebarArtwork(theme.id)).toBe(true);
expect(theme.colors.accent).toMatch(/^#[0-9a-f]{6}$/i);
expect(theme.variants?.dark?.accent).toMatch(/^#[0-9a-f]{6}$/i);
expect(theme.colors.accent).toMatch(/^oklch\(/);
expect(theme.variants?.dark?.accent).toMatch(/^oklch\(/);
for (const mode of ["light", "dark"] as const) {
const colors = getThemeColorsForMode(theme, mode);
@@ -380,7 +475,9 @@ describe("theme files", () => {
});
expect(getThemeModes(theme)).toEqual(["dark"]);
expect(getThemeColorsForMode(theme, "dark")).toMatchObject({ canvas: "#111827" });
expect(getThemeColorsForMode(theme, "dark")).toMatchObject({
canvas: canonical("#111827"),
});
expect(getThemeColorsForMode(theme, "light")).toBeNull();
});
@@ -419,8 +516,188 @@ describe("theme files", () => {
vi.unstubAllGlobals();
});
it("updates a personal theme without changing its id", () => {
it("preserves valid imported-theme collections and drops malformed metadata", () => {
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) =>
key === CUSTOM_THEMES_STORAGE_KEY
? JSON.stringify([
{
id: "github-dark",
label: "GitHub Dark",
appearance: "dark",
colors: { canvas: "#0d1117" },
collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" },
},
{
id: "github-light",
label: "GitHub Light",
appearance: "light",
colors: { canvas: "#ffffff" },
collection: { id: "bad collection id", label: "GitHub Theme" },
},
])
: null,
},
});
invalidateCustomThemes();
expect(getCustomThemes()).toMatchObject([
{ collection: { id: "open-vsx:github.github-vscode-theme", label: "GitHub Theme" } },
{ id: "github-light" },
]);
expect(getCustomThemes()[1]).not.toHaveProperty("collection");
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("atomically replaces an imported collection and removes stale variants", () => {
const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
const personalTheme = {
id: "personal",
label: "Personal",
appearance: "dark",
colors: { canvas: "#111111", futureRole: "hsl(10 20% 30%)" },
futureMetadata: { version: 2 },
};
const stored = new Map<string, string>([
[
CUSTOM_THEMES_STORAGE_KEY,
JSON.stringify([
personalTheme,
{
id: "old-light",
label: "Old Light",
appearance: "light",
colors: { canvas: "#ffffff" },
collection,
},
{
id: "removed-dark",
label: "Removed Dark",
appearance: "dark",
colors: { canvas: "#000000" },
collection,
},
]),
],
]);
const setItem = vi.fn((key: string, value: string) => stored.set(key, value));
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) => stored.get(key) ?? null,
setItem,
},
});
invalidateCustomThemes();
const expectedCollection = getStoredCustomThemeCollection(collection.id);
getCustomThemes();
const concurrentlyAddedTheme = {
id: "other-tab",
label: "Other Tab",
appearance: "dark",
colors: { canvas: "#222222" },
};
stored.set(
CUSTOM_THEMES_STORAGE_KEY,
JSON.stringify([
...JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]"),
concurrentlyAddedTheme,
]),
);
const replacement = [
{
...parseThemeFile({
version: THEME_FILE_VERSION,
id: "old-light",
name: "New Light",
appearance: "light",
colors: { canvas: "#fafafa" },
}),
collection,
},
{
...parseThemeFile({
version: THEME_FILE_VERSION,
id: "new-dark",
name: "New Dark",
appearance: "dark",
colors: { canvas: "#101010" },
}),
collection,
},
];
expect(
replaceCustomThemeCollection(collection.id, replacement, { expectedCollection }),
).toEqual(replacement);
expect(getCustomThemes().map((theme) => theme.id)).toEqual([
"personal",
"old-light",
"new-dark",
"other-tab",
]);
expect(setItem).toHaveBeenCalledTimes(1);
expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toEqual(personalTheme);
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("replaces collection entries even when their stored collection label is malformed", () => {
const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
const stored = new Map<string, string>([
[
CUSTOM_THEMES_STORAGE_KEY,
JSON.stringify([
{
id: "old-light",
label: "Old Light",
appearance: "light",
colors: { canvas: "#ffffff" },
collection: { id: collection.id, label: 42 },
},
]),
],
]);
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) => stored.get(key) ?? null,
setItem: (key: string, value: string) => stored.set(key, value),
},
});
invalidateCustomThemes();
const replacement = {
...parseThemeFile({
version: THEME_FILE_VERSION,
id: "old-light",
name: "New Light",
appearance: "light",
colors: { canvas: "#fafafa" },
}),
collection,
};
expect(replaceCustomThemeCollection(collection.id, [replacement])).toEqual([replacement]);
expect(getCustomThemes()).toEqual([replacement]);
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("canonicalizes explicit writes without migrating untouched themes", () => {
const stored = new Map<string, string>();
const untouchedTheme = {
id: "legacy",
label: "Legacy",
appearance: "dark",
colors: { accent: "#5b6cff", futureRole: "hsl(10 20% 30%)" },
futureMetadata: { version: 2 },
};
stored.set(CUSTOM_THEMES_STORAGE_KEY, JSON.stringify([untouchedTheme]));
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) => stored.get(key) ?? null,
@@ -442,24 +719,226 @@ describe("theme files", () => {
const updatedTheme = updateCustomTheme({
...createdTheme,
label: "Aurora Night",
colors: { ...createdTheme.colors, accent: "#7c3aed" },
colors: { ...createdTheme.colors, accent: "hsl(263 70% 58%)" },
});
expect(updatedTheme).toMatchObject({
id: "aurora",
label: "Aurora Night",
colors: { accent: canonical("hsl(263 70% 58%)") },
});
expect(updatedTheme).not.toHaveProperty("sidebarArtwork");
invalidateCustomThemes();
expect(getCustomThemes()).toEqual([updatedTheme]);
expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toMatchObject({
const storedThemes = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
expect(storedThemes[0]).toEqual(untouchedTheme);
expect(storedThemes[1]).toMatchObject({
id: "aurora",
label: "Aurora Night",
colors: { accent: canonical("hsl(263 70% 58%)") },
});
expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).not.toHaveProperty(
"sidebarArtwork",
expect(storedThemes[1]).not.toHaveProperty("sidebarArtwork");
invalidateCustomThemes();
expect(getCustomThemes().find((theme) => theme.id === "aurora")).toMatchObject({
id: "aurora",
colors: { accent: canonical("hsl(263 70% 58%)") },
});
removeCustomTheme("aurora");
expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")).toEqual([untouchedTheme]);
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("removes multiple custom themes atomically while preserving unrelated entries", () => {
const collection = { id: "open-vsx:demo.theme", label: "Demo Theme" };
const personalTheme = {
id: "personal",
label: "Personal",
appearance: "dark",
colors: { canvas: "#111111", futureRole: "hsl(10 20% 30%)" },
futureMetadata: { version: 2 },
};
const stored = new Map<string, string>([
[
CUSTOM_THEMES_STORAGE_KEY,
JSON.stringify([
personalTheme,
{
id: "demo-light",
label: "Demo Light",
appearance: "light",
colors: { canvas: "#ffffff" },
collection,
},
{
id: "demo-dark",
label: "Demo Dark",
appearance: "dark",
colors: { canvas: "#000000" },
collection,
},
]),
],
]);
const setItem = vi.fn((key: string, value: string) => stored.set(key, value));
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) => stored.get(key) ?? null,
setItem,
},
});
invalidateCustomThemes();
removeCustomThemes(["demo-light", "demo-dark"]);
expect(setItem).toHaveBeenCalledOnce();
expect(getCustomThemes()).toEqual([expect.objectContaining({ id: "personal" })]);
expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")).toEqual([personalTheme]);
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("writes from the cached raw snapshot without risking a destructive reread", () => {
const legacyTheme = {
id: "legacy",
label: "Legacy",
appearance: "dark",
colors: { accent: "#5b6cff" },
futureMetadata: true,
};
let storedThemes = JSON.stringify([legacyTheme]);
let readCount = 0;
const setItem = vi.fn((_key: string, value: string) => {
storedThemes = value;
});
vi.stubGlobal("window", {
localStorage: {
getItem: () => {
readCount += 1;
if (readCount > 1) throw new Error("transient read failure");
return storedThemes;
},
setItem,
},
});
invalidateCustomThemes();
expect(getCustomThemes()).toHaveLength(1);
installCustomTheme(
parseThemeFile({
version: THEME_FILE_VERSION,
id: "aurora",
name: "Aurora",
appearance: "light",
colors: { accent: "hsl(263 70% 58%)" },
}),
);
expect(readCount).toBe(1);
expect(setItem).toHaveBeenCalledOnce();
expect(JSON.parse(storedThemes)[0]).toEqual(legacyTheme);
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("refuses to overwrite a theme library that could not be read", () => {
const setItem = vi.fn();
vi.stubGlobal("window", {
localStorage: {
getItem: () => {
throw new Error("storage unavailable");
},
setItem,
},
});
invalidateCustomThemes();
expect(getCustomThemes()).toEqual([]);
expect(() =>
installCustomTheme(
parseThemeFile({
version: THEME_FILE_VERSION,
id: "aurora",
name: "Aurora",
appearance: "light",
colors: { accent: "#5b6cff" },
}),
),
).toThrow(`Failed to read the theme library from ${CUSTOM_THEMES_STORAGE_KEY}.`);
expect(setItem).not.toHaveBeenCalled();
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("rejects malformed stored entries that reuse an installed theme id", () => {
const storedThemes = JSON.stringify([{ id: "aurora", malformed: true }]);
const setItem = vi.fn();
vi.stubGlobal("window", {
localStorage: {
getItem: () => storedThemes,
setItem,
},
});
invalidateCustomThemes();
expect(() =>
installCustomTheme(
parseThemeFile({
version: THEME_FILE_VERSION,
id: "aurora",
name: "Aurora",
appearance: "light",
colors: { accent: "#5b6cff" },
}),
),
).toThrow('A theme named "Aurora" is already installed.');
expect(setItem).not.toHaveBeenCalled();
vi.unstubAllGlobals();
invalidateCustomThemes();
});
it("collapses duplicate raw entries when their theme is explicitly updated", () => {
const stored = new Map<string, string>();
const theme = {
id: "aurora",
label: "Aurora",
appearance: "light",
colors: { accent: "#5b6cff" },
};
const untouchedTheme = { id: "future", malformed: true, metadata: { version: 2 } };
stored.set(
CUSTOM_THEMES_STORAGE_KEY,
JSON.stringify([theme, { id: "aurora", malformed: true }, untouchedTheme]),
);
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) => stored.get(key) ?? null,
setItem: (key: string, value: string) => stored.set(key, value),
},
});
invalidateCustomThemes();
const installedTheme = getCustomThemes()[0]!;
updateCustomTheme({
...installedTheme,
label: "Aurora Night",
colors: { ...installedTheme.colors, accent: "hsl(263 70% 58%)" },
});
const updatedLibrary = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
expect(updatedLibrary.filter((entry: { id?: string }) => entry.id === "aurora")).toHaveLength(
1,
);
expect(updatedLibrary[0]).toMatchObject({
id: "aurora",
label: "Aurora Night",
colors: { accent: canonical("hsl(263 70% 58%)") },
});
expect(updatedLibrary[1]).toEqual(untouchedTheme);
vi.unstubAllGlobals();
invalidateCustomThemes();
});
@@ -530,23 +1009,23 @@ describe("stored theme preferences", () => {
expect(isKnownThemePreference("missing-theme")).toBe(false);
});
it("keeps stored themes with unknown roles and drops invalid entries", () => {
it("decodes stored colors in memory without writing during reads", () => {
const storedThemes = JSON.stringify([
{
id: "aurora",
label: "Aurora",
appearance: "light",
colors: { canvas: "#f8fbff", futureRole: "#123456", accent: "not-a-color" },
variants: { dark: { canvas: "rgb(16 24 39)" } },
},
{ id: "light", label: "Reserved", appearance: "light", colors: {} },
{ id: "aurora", label: "Duplicate", appearance: "dark", colors: {} },
]);
const setItem = vi.fn();
vi.stubGlobal("window", {
localStorage: {
getItem: (key: string) =>
key === CUSTOM_THEMES_STORAGE_KEY
? JSON.stringify([
{
id: "aurora",
label: "Aurora",
appearance: "light",
colors: { canvas: "#f8fbff", futureRole: "#123456", accent: "not-a-color" },
variants: { light: { canvas: "#101827" } },
},
{ id: "light", label: "Reserved", appearance: "light", colors: {} },
{ id: "aurora", label: "Duplicate", appearance: "dark", colors: {} },
])
: null,
getItem: (key: string) => (key === CUSTOM_THEMES_STORAGE_KEY ? storedThemes : null),
setItem,
},
});
invalidateCustomThemes();
@@ -555,11 +1034,16 @@ describe("stored theme preferences", () => {
expect(themes).toHaveLength(1);
expect(themes[0]).toMatchObject({
id: "aurora",
colors: { canvas: "#f8fbff", accent: getDefaultThemeColors("light").accent },
colors: { canvas: canonical("#f8fbff"), accent: getDefaultThemeColors("light").accent },
});
expect(getThemeModes(themes[0]!)).toEqual(["light", "dark"]);
expect(getThemeColorsForMode(themes[0]!, "dark")?.canvas).toBe(canonical("rgb(16 24 39)"));
expect(setItem).not.toHaveBeenCalled();
expect(JSON.parse(storedThemes)[0].colors).toEqual({
canvas: "#f8fbff",
futureRole: "#123456",
accent: "not-a-color",
});
// The variant shadowing the base appearance is dropped so the theme
// round-trips through parseThemeFile on export.
expect(getThemeModes(themes[0]!)).toEqual(["light"]);
vi.unstubAllGlobals();
invalidateCustomThemes();
File diff suppressed because it is too large. Load diff
+26 -19
View File
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vite-plus/test";
import { getThemeColorsForMode, THEME_FILE_VERSION } from "./themePalette";
import { getThemeColorsForMode, themeColorToHex, THEME_FILE_VERSION } from "./themePalette";
import {
isVsCodeThemeFile,
pairVsCodeThemes,
@@ -8,9 +8,15 @@ import {
resolveThemeLabelCollisions,
} from "./vscodeThemeImport";
function asHex(value: string): string {
const hex = themeColorToHex(value);
if (!hex) throw new Error(`Expected a theme color, received ${value}`);
return hex;
}
function contrastRatio(first: string, second: string): number {
const toChannels = (value: string) => {
const hex = value.slice(1);
const hex = asHex(value).slice(1);
return [0, 1, 2].map(
(channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
);
@@ -69,18 +75,18 @@ describe("VS Code theme import", () => {
// The slug name is read as words; a displayName would win verbatim.
expect(theme.label).toBe("Pierre Dark Soft");
expect(theme.appearance).toBe("dark");
expect(theme.colors.canvas).toBe("#171717");
expect(theme.colors.text).toBe("#d4d4d4");
expect(theme.colors.accent).toBe("#69b1ff");
expect(theme.colors.sidebar).toBe("#101010");
expect(theme.colors.terminalBackground).toBe("#101010");
expect(asHex(theme.colors.canvas)).toBe("#171717");
expect(asHex(theme.colors.text)).toBe("#d4d4d4");
expect(asHex(theme.colors.accent)).toBe("#69b1ff");
expect(asHex(theme.colors.sidebar)).toBe("#101010");
expect(asHex(theme.colors.terminalBackground)).toBe("#101010");
});
it("flattens alpha overlays onto the surface they sit on", () => {
const theme = parseVsCodeThemeFile(VSCODE_DARK);
// #1f3e5e59 over the #101010 sidebar, not left semi-transparent.
expect(theme.colors.sidebarRowHover).toMatch(/^#[0-9a-f]{6}$/);
expect(theme.colors.sidebarRowHover).not.toBe("#1f3e5e59");
expect(theme.colors.sidebarRowHover).toMatch(/^oklch\(/);
expect(asHex(theme.colors.sidebarRowHover)).not.toBe("#1f3e5e59");
expect(theme.colors.sidebarRowSelected).not.toBe(theme.colors.sidebar);
});
@@ -88,7 +94,7 @@ describe("VS Code theme import", () => {
const theme = parseVsCodeThemeFile(VSCODE_DARK);
const colors = getThemeColorsForMode(theme, "dark")!;
for (const value of Object.values(colors)) {
expect(value).toMatch(/^#[0-9a-f]{3,8}$/i);
expect(value).toMatch(/^oklch\(/);
}
expect(contrastRatio(colors.text, colors.canvas)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.sidebarForeground, colors.sidebar)).toBeGreaterThanOrEqual(4.5);
@@ -117,7 +123,7 @@ describe("VS Code theme import", () => {
type: "dark",
colors: { "editor.background": "#101010", "editor.foreground": "#111111" },
});
expect(theme.colors.text).not.toBe("#111111");
expect(asHex(theme.colors.text)).not.toBe("#111111");
expect(contrastRatio(theme.colors.text, theme.colors.canvas)).toBeGreaterThanOrEqual(4.5);
});
@@ -134,7 +140,7 @@ describe("VS Code theme import", () => {
"terminal.background": "#fbfbfb",
},
});
expect(theme.colors.sidebar).toBe("#fafafa");
expect(asHex(theme.colors.sidebar)).toBe("#fafafa");
expect(
contrastRatio(theme.colors.sidebarForeground, theme.colors.sidebar),
).toBeGreaterThanOrEqual(4.5);
@@ -156,10 +162,10 @@ describe("VS Code theme import", () => {
"editor.selectionBackground": "color(display-p3 0.308664 0.645271 1.000000 / 0.300000)",
},
});
expect(theme.colors.canvas).toMatch(/^#0[89ab]/);
expect(theme.colors.text).toMatch(/^#f[a-f0-9]/);
expect(asHex(theme.colors.canvas)).toMatch(/^#0[89ab]/);
expect(asHex(theme.colors.text)).toMatch(/^#f[a-f0-9]/);
// The P3 blue lands in sRGB blue, not black or a clipped grey.
const accent = theme.colors.accent;
const accent = asHex(theme.colors.accent);
const [red, green, blue] = [1, 3, 5].map((index) =>
Number.parseInt(accent.slice(index, index + 2), 16),
) as [number, number, number];
@@ -192,8 +198,8 @@ describe("VS Code theme import", () => {
const github = themes[0]!;
expect(github.appearance).toBe("light");
expect(getThemeColorsForMode(github, "dark")).not.toBeNull();
expect(getThemeColorsForMode(github, "dark")!.canvas).toBe("#101014");
expect(github.colors.canvas).toBe("#fdfdfd");
expect(asHex(getThemeColorsForMode(github, "dark")!.canvas)).toBe("#101014");
expect(asHex(github.colors.canvas)).toBe("#fdfdfd");
// The unpaired dimmed variant stays a single dark theme.
expect(getThemeColorsForMode(themes[2]!, "light")).toBeNull();
});
@@ -220,14 +226,15 @@ describe("VS Code theme import", () => {
// surface, plain surfaces) must stay near the canvas, not turn blue.
const theme = parseVsCodeThemeFile(VSCODE_DARK);
const spread = (value: string) => {
const channels = [1, 3, 5].map((index) => Number.parseInt(value.slice(index, index + 2), 16));
const hex = asHex(value);
const channels = [1, 3, 5].map((index) => Number.parseInt(hex.slice(index, index + 2), 16));
return Math.max(...channels) - Math.min(...channels);
};
expect(spread(theme.colors.codeBackground)).toBeLessThanOrEqual(8);
expect(spread(theme.colors.surface)).toBeLessThanOrEqual(8);
expect(spread(theme.colors.text)).toBeLessThanOrEqual(12);
// The accent itself keeps the file's color.
expect(theme.colors.accent).toBe("#69b1ff");
expect(asHex(theme.colors.accent)).toBe("#69b1ff");
});
it("tells same-named variants apart by their file names", () => {
+6 -1
View File
@@ -2,6 +2,7 @@ import {
createVividThemeColors,
getThemeModes,
parseThemeFile,
themeColorToHex,
THEME_FILE_VERSION,
type ThemeAppearance,
type ThemeColorRole,
@@ -138,7 +139,7 @@ function contrastRatio(first: VsCodeRgb, second: VsCodeRgb): number {
}
function hexToRgb(value: string): VsCodeRgb {
return parseVsCodeColor(value) ?? { r: 0, g: 0, b: 0, a: 1 };
return parseVsCodeColor(themeColorToHex(value) ?? value) ?? { r: 0, g: 0, b: 0, a: 1 };
}
/**
@@ -336,6 +337,9 @@ export function parseVsCodeThemeFile(value: unknown): ThemeDefinition {
*/
export function pairVsCodeThemes(
themes: ReadonlyArray<ThemeDefinition>,
options?: {
pairedId?: (light: ThemeDefinition, dark: ThemeDefinition) => string;
},
): ReadonlyArray<ThemeDefinition> {
const stripAppearance = (label: string) =>
label
@@ -371,6 +375,7 @@ export function pairVsCodeThemes(
order: group.order,
theme: parseThemeFile({
version: THEME_FILE_VERSION,
...(options?.pairedId ? { id: options.pairedId(group.light[0]!, group.dark[0]!) } : {}),
name: key,
appearance: "light",
colors: group.light[0]!.colors,
+4
View File
@@ -18,3 +18,7 @@ Dev and Nightly environments can identify themselves with artwork at the top of
the send button. Choose **Artwork**, **Version pill**, or **None** in Settings under environment
identification. Artwork is recolored to match each built-in theme. Custom themes use the **Version
pill** fallback because their colors are not controlled by T3 Code.
To generate a fresh title from the conversation, open a thread's context menu and choose
**Regenerate title**. While T3 Code is generating it, the action reads **Regenerating…** and cannot
be selected again. The option is hidden when the connected environment needs a server update.
+16
View File
@@ -57,6 +57,22 @@ describe("detectSourceControlProviderFromRemoteUrl", () => {
).toBe("bitbucket");
});
it("detects Azure DevOps SSH remotes", () => {
// The default Azure DevOps SSH clone URL uses the ssh.dev.azure.com host.
expect(
detectSourceControlProviderFromRemoteUrl("[email protected]:v3/org/project/repo")?.kind,
).toBe("azure-devops");
expect(
detectSourceControlProviderFromRemoteUrl("ssh://[email protected]:22/v3/org/project/repo")
?.kind,
).toBe("azure-devops");
// Legacy visualstudio.com SSH host stays classified too.
expect(
detectSourceControlProviderFromRemoteUrl("[email protected]:v3/org/project/repo")
?.kind,
).toBe("azure-devops");
});
it("preserves ports while classifying by hostname", () => {
expect(
detectSourceControlProviderFromRemoteUrl("https://gitlab.com:8443/group/repo.git"),
+9 -1
View File
@@ -176,7 +176,15 @@ function isGitLabHost(host: string): boolean {
}
function isAzureDevOpsHost(host: string): boolean {
return host === "dev.azure.com" || host.endsWith(".visualstudio.com");
// `ssh.dev.azure.com` is the default Azure DevOps SSH clone host
// ([email protected]:v3/org/project/repo), so match any `*.dev.azure.com`
// subdomain, not just the bare `dev.azure.com`. Legacy hosts stay under
// `.visualstudio.com` (including `vs-ssh.visualstudio.com`).
return (
host === "dev.azure.com" ||
host.endsWith(".dev.azure.com") ||
host.endsWith(".visualstudio.com")
);
}
function isBitbucketHost(host: string): boolean {
+20
View File
@@ -546,6 +546,9 @@ importers:
'@lexical/react':
specifier: ^0.41.0
version: 0.41.0([email protected]([email protected]))([email protected])([email protected])
'@noble/hashes':
specifier: 'catalog:'
version: 1.8.0
'@pierre/diffs':
specifier: 'catalog:'
version: 1.3.0-beta.10(patch_hash=7ef7cb0cbabb17c15cdb137554068b36f15f6f5265e73fb51452aa3380db91aa)(@shikijs/[email protected])([email protected]([email protected]))([email protected])
@@ -570,12 +573,21 @@ importers:
class-variance-authority:
specifier: ^0.7.1
version: 0.7.1
culori:
specifier: ^4.0.2
version: 4.0.2
effect:
specifier: 4.0.0-beta.103
version: 4.0.0-beta.103(patch_hash=af36b7948b6f9c56623074662b51dade5699880c1a7c71245de73e13c3185fb6)
jose:
specifier: 'catalog:'
version: 6.2.2
jsonc-parser:
specifier: 3.3.1
version: 3.3.1
jszip:
specifier: 3.10.1
version: 3.10.1
lexical:
specifier: ^0.41.0
version: 0.41.0
@@ -631,6 +643,9 @@ importers:
'@types/compression':
specifier: ^1.8.1
version: 1.8.1
'@types/culori':
specifier: ^4.0.1
version: 4.0.1
'@types/react':
specifier: ~19.2.14
version: 19.2.16
@@ -4794,6 +4809,9 @@ packages:
'@types/[email protected]':
resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==}
'@types/[email protected]':
resolution: {integrity: sha512-43M51r/22CjhbOXyGT361GZ9vncSVQ39u62x5eJdBQFviI8zWp2X5jzqg7k4M6PVgDQAClpy2bUe2dtwEgEDVQ==}
'@types/[email protected]':
resolution: {integrity: sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==}
@@ -14972,6 +14990,8 @@ snapshots:
dependencies:
'@types/node': 24.12.4
'@types/[email protected]': {}
'@types/[email protected]':
dependencies:
'@types/ms': 2.1.0