Compare commits

..
Author SHA1 Message Date
t3-code[bot]andUtkarsh Patil 23aeb0a20c docs: refresh subagent redesign screenshots
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 18:07:00 +00:00
t3-code[bot]andUtkarsh Patil a9eb066b53 docs: add subagent diff bar screenshots
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 16:32:33 +00:00
Exotic b73232bdd3 feat(web): reset sidebar width on double click (#6320) 2026-08-12 10:07:39 -04:00
Wout Stiens f131228a59 fix(web): theme Clerk surfaces (#6300) 2026-08-12 19:36:04 +05:30
t3-code[bot]andWout Stiens e321667b10 fix(web): prevent changed files header overlap (#6314)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Wout Stiens <[email protected]>
2026-08-12 08:56:13 -04:00
Julius Marminge 849bac8946 fix(connect): preserve CLI OAuth parameters through browser sign-in (#6285) 2026-08-12 12:58:34 +02:00
t3-code[bot]andUtkarsh Patil 6fd088af9f fix(web): align mobile onboarding header (#6293)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: Utkarsh Patil <[email protected]>
2026-08-12 16:07:44 +05:30
Wout Stiens b54bfc9312 feat(web): a better right panel empty state (#6258) 2026-08-12 15:28:46 +05:30
Nick Anisimovandshivam e1378a1f4d fix(mobile): keep ordered lists inside user bubbles (#6154)
Co-authored-by: shivam <[email protected]>
2026-08-12 14:39:51 +05:30
t3-code[bot]andmaria 5a84614809 fix(web): align the composer model picker (#6252)
Co-authored-by: t3-code[bot] <269035359+t3-code[bot]@users.noreply.github.com>
Co-authored-by: maria <[email protected]>
2026-08-11 22:38:45 -04: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
Arham AminandClaude Opus 4.8 6befe42eb0 fix(shared): normalize a bare Windows drive root the same as C:\ / C:/ (#6189)
Co-authored-by: Claude Opus 4.8 (1M context) <[email protected]>
2026-08-11 15:52:23 +00:00
Julius Marmingeandcodex b30a9bc414 feat(web): make environment artwork theme aware (#6183)
Co-authored-by: codex <[email protected]>
2026-08-11 17:46:52 +02:00
75 changed files with 5187 additions and 961 deletions

No files matched your search

+1
View File
@@ -37,3 +37,4 @@ github:shivamhwp
github:jappyjan
github:justsomelegs
github:UtkarshUsername
github:SunkenInTime
Binary file not shown.

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

@@ -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,
};
}
@@ -104,6 +104,10 @@ import { useMarkdownCodeHighlight } from "./markdownCodeHighlightState";
import { useAssetUrl } from "../../state/assets";
import { resolveWorkspaceRelativeFilePath } from "../files/filePath";
const WIDE_MARKDOWN_BLOCK_OPTIONS = {
includeOrderedLists: Platform.OS === "android",
} as const;
const MESSAGE_TIME_FORMATTER = new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
@@ -888,7 +892,7 @@ function renderFeedEntry(
// children during the unclamped pass and never moves them once the width
// is clamped, so the paragraphs around the block end up drawn on top of
// each other. Pinning the width removes that pass.
const hasWideBlock = hasWideMarkdownBlock(message.text);
const hasWideBlock = hasWideMarkdownBlock(message.text, WIDE_MARKDOWN_BLOCK_OPTIONS);
const assistantTurnStillInProgress =
message.role === "assistant" &&
props.unsettledTurnId !== null &&
@@ -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 } } : {}),
},
];
}
@@ -17,6 +17,30 @@ describe("hasWideMarkdownBlock", () => {
expect(hasWideMarkdownBlock(" ```\ncode\n```")).toBe(true);
});
it("detects top-level and blockquoted ordered-list markers", () => {
expect(hasWideMarkdownBlock("1. One\n2. Two\n3. Three\n4. Four\n5. Five")).toBe(true);
expect(hasWideMarkdownBlock("before\n3) Three")).toBe(true);
expect(hasWideMarkdownBlock("> 1. One\n> 2. Two")).toBe(true);
expect(hasWideMarkdownBlock("> > 3) Three")).toBe(true);
});
it("detects nested ordered lists without treating indented code as a list", () => {
expect(hasWideMarkdownBlock("- Parent\n 1. Child\n 2. Child")).toBe(true);
expect(hasWideMarkdownBlock("> - Parent\n> 1. Child")).toBe(true);
expect(hasWideMarkdownBlock(" 1. indented code")).toBe(false);
expect(hasWideMarkdownBlock(" - code-like bullet\n 1. indented code")).toBe(false);
});
it("can limit ordered-list width pinning to Android", () => {
const orderedList = "1. One\n2. Two";
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: true })).toBe(true);
expect(hasWideMarkdownBlock(orderedList, { includeOrderedLists: false })).toBe(false);
expect(hasWideMarkdownBlock("```\ncode\n```", { includeOrderedLists: false })).toBe(true);
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |", { includeOrderedLists: false })).toBe(
true,
);
});
it("detects GFM tables", () => {
expect(hasWideMarkdownBlock("| a | b |\n| --- | --- |\n| 1 | 2 |")).toBe(true);
expect(hasWideMarkdownBlock("a | b\n:-- | --:\n1 | 2")).toBe(true);
+60 -8
View File
@@ -1,9 +1,10 @@
/**
* Detects markdown that the JS renderer draws as a standalone block View
* wrapping a horizontal ScrollView — fenced code blocks and GFM tables.
* Detects markdown that the JS renderer draws as a block requiring a definite
* user-bubble width — fenced code blocks, GFM tables, and ordered lists.
*
* Those blocks report an intrinsic width equal to their widest line, which is
* effectively unbounded. A user bubble sizes itself from its content
* Fenced code blocks and tables report an intrinsic width equal to their
* widest line, which is effectively unbounded. A user bubble sizes itself
* from its content
* (`maxWidth` with no `width`), so Android lays the bubble's children out
* during the unclamped intrinsic pass — where the surrounding paragraphs
* collapse to a single line — and never repositions them once the width is
@@ -12,12 +13,57 @@
* intrinsic pass entirely, which is the same reason review-comment bubbles
* already carry an explicit width.
*
* Indented (four-space) code blocks are deliberately not detected: they are
* vanishingly rare in chat input and the check would fire on ordinary nested
* list continuations.
* Ordered lists hit the same Android layout bug because each item contains a
* flexing content column inside a shrink-to-fit row.
*
* A four-space ordered marker is only treated as a list when the preceding
* non-empty line is a less-indented list item. This keeps standalone indented
* code out of the heuristic while covering nested lists.
*/
const FENCED_CODE_BLOCK = /^ {0,3}(?:```|~~~)/m;
// Trades some precision for a simple check, favoring false positives over false
// negatives: list-shaped paragraph may get a wider bubble
const ORDERED_LIST_ITEM = /^ {0,3}\d{1,9}[.)](?:[ \t]+|$)/;
const INDENTED_ORDERED_LIST_ITEM = /^( {4,})\d{1,9}[.)](?:[ \t]+|$)/;
const ANY_LIST_ITEM = /^( *)(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/;
const BLOCKQUOTE_PREFIX = /^ {0,3}>[ \t]?/;
export interface WideMarkdownBlockOptions {
readonly includeOrderedLists?: boolean;
}
function stripBlockquotePrefixes(line: string): string {
let content = line;
while (BLOCKQUOTE_PREFIX.test(content)) {
content = content.replace(BLOCKQUOTE_PREFIX, "");
}
return content;
}
function hasOrderedListItem(text: string): boolean {
let previousNonEmptyLine: string | null = null;
for (const rawLine of text.split("\n")) {
const line = stripBlockquotePrefixes(rawLine);
if (ORDERED_LIST_ITEM.test(line)) {
return true;
}
const nestedMatch = INDENTED_ORDERED_LIST_ITEM.exec(line);
const parentMatch =
previousNonEmptyLine === null ? null : ANY_LIST_ITEM.exec(previousNonEmptyLine);
if (nestedMatch && parentMatch && parentMatch[1].length < nestedMatch[1].length) {
return true;
}
if (line.trim().length > 0) {
previousNonEmptyLine = line;
}
}
return false;
}
function isTableDelimiterRow(line: string): boolean {
const trimmed = line.trim();
@@ -27,10 +73,16 @@ function isTableDelimiterRow(line: string): boolean {
return /^[|\-: \t]+$/.test(trimmed);
}
export function hasWideMarkdownBlock(text: string): boolean {
export function hasWideMarkdownBlock(
text: string,
options: WideMarkdownBlockOptions = {},
): boolean {
if (FENCED_CODE_BLOCK.test(text)) {
return true;
}
if (options.includeOrderedLists !== false && hasOrderedListItem(text)) {
return true;
}
if (!text.includes("|")) {
return false;
}
+9 -7
View File
@@ -26,7 +26,6 @@ import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse";
import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
checkConnectAuthCode,
connectCallbackUrl,
} from "@t3tools/shared/connectAuth";
@@ -367,6 +366,7 @@ export const make = Effect.gen(function* () {
const login = Effect.fn("cloud.cli_token.login")(function* () {
const metadata = yield* cloudCliOAuthConfig;
const hostedAppUrl = yield* hostedAppUrlConfig;
const { verifier, challenge, state } = yield* makePkceRequest;
const callback = yield* Deferred.make<string>();
const callbackRoute = HttpRouter.add(
@@ -392,19 +392,21 @@ export const make = Effect.gen(function* () {
Layer.provide(
NodeHttpServer.layer(NodeHttp.createServer, {
host: "127.0.0.1",
port: 34338,
port: metadata.loopbackPort,
disablePreemptiveShutdown: true,
}),
),
Layer.build,
);
const authorizationUrl = buildConnectClerkAuthorizeUrl({
authorizationEndpoint: metadata.authorizationEndpoint,
clientId: metadata.clientId,
redirectUri: metadata.redirectUri,
scopes: metadata.scopes,
// The hosted /connect page establishes a Clerk session before forwarding
// the request to /oauth/authorize with the loopback redirect URI. Sending
// a signed-out browser to /oauth/authorize directly loses the authorize
// parameters across Clerk's sign-in redirect (#5051).
const authorizationUrl = buildConnectAuthorizeRequestUrl({
hostedAppUrl,
state,
challenge,
loopbackPort: metadata.loopbackPort,
});
yield* Console.log(formatLoopbackAuthorizationPrompt(authorizationUrl));
const authorization = yield* waitForLoopbackAuthorization({
+1 -2
View File
@@ -90,9 +90,9 @@ it.effect("derives direct Clerk OAuth endpoints from statically injected public
}).pipe(provideEnv({}));
assert.deepEqual(config, {
authorizationEndpoint: "https://clerk.example.test/oauth/authorize",
tokenEndpoint: "https://clerk.example.test/oauth/token",
clientId: "oauth_client_embedded",
loopbackPort: 34338,
redirectUri: "http://127.0.0.1:34338/callback",
scopes: ["openid", "profile", "email"],
});
@@ -111,7 +111,6 @@ it.effect("prefers runtime Clerk OAuth config overrides over statically injected
}),
);
assert.equal(config.authorizationEndpoint, "https://runtime.example.test/oauth/authorize");
assert.equal(config.tokenEndpoint, "https://runtime.example.test/oauth/token");
assert.equal(config.clientId, "oauth_client_runtime");
}),
+15 -5
View File
@@ -1,4 +1,8 @@
import { CONNECT_OAUTH_SCOPES, DEFAULT_HOSTED_APP_URL } from "@t3tools/shared/connectAuth";
import {
connectLoopbackRedirectUri,
CONNECT_OAUTH_SCOPES,
DEFAULT_HOSTED_APP_URL,
} from "@t3tools/shared/connectAuth";
import { clerkFrontendApiUrlFromPublishableKey } from "@t3tools/shared/relayAuth";
import { normalizeSecureRelayUrl } from "@t3tools/shared/relayUrl";
import * as Config from "effect/Config";
@@ -14,7 +18,7 @@ declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_URL__: string | undefined;
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_DATASET__: string | undefined;
declare const __T3CODE_BUILD_RELAY_CLIENT_OTLP_TRACES_TOKEN__: string | undefined;
const CLOUD_CLI_OAUTH_REDIRECT_URI = "http://127.0.0.1:34338/callback";
const CLOUD_CLI_OAUTH_LOOPBACK_PORT = 34338;
const CLOUD_CLI_OAUTH_SCOPES = CONNECT_OAUTH_SCOPES;
function validateRelayUrl(value: string) {
@@ -145,10 +149,16 @@ function makePublicValueConfig(name: string, fallback: string) {
);
}
/**
* The CLI never calls Clerk's /oauth/authorize itself: the browser leg goes
* through the hosted /connect page, which builds the authorize URL after a
* Clerk session exists (see CliTokenManager.login). Only the token endpoint
* is contacted directly.
*/
export interface CloudCliOAuthConfig {
readonly authorizationEndpoint: string;
readonly tokenEndpoint: string;
readonly clientId: string;
readonly loopbackPort: number;
readonly redirectUri: string;
readonly scopes: typeof CLOUD_CLI_OAUTH_SCOPES;
}
@@ -184,10 +194,10 @@ export function makeCloudCliOAuthConfig({
Effect.map(
(clerkFrontendApiUrl) =>
({
authorizationEndpoint: `${clerkFrontendApiUrl}/oauth/authorize`,
tokenEndpoint: `${clerkFrontendApiUrl}/oauth/token`,
clientId,
redirectUri: CLOUD_CLI_OAUTH_REDIRECT_URI,
loopbackPort: CLOUD_CLI_OAUTH_LOOPBACK_PORT,
redirectUri: connectLoopbackRedirectUri(CLOUD_CLI_OAUTH_LOOPBACK_PORT),
scopes: CLOUD_CLI_OAUTH_SCOPES,
}) satisfies CloudCliOAuthConfig,
),
+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",
+16
View File
@@ -46,6 +46,22 @@ describe("connectCliAuth", () => {
expect(url.searchParams.get("code_challenge_method")).toBe("S256");
});
it("redirects straight to the CLI's loopback listener when the request carries a port", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
vi.stubEnv("VITE_CLERK_CLI_OAUTH_CLIENT_ID", "oauthapp_123");
const authorizeUrl = buildConnectCliClerkAuthorizeUrl({
state: "state-1",
challenge: "challenge-1",
loopbackPort: 34338,
});
expect(authorizeUrl).not.toBeNull();
const url = new URL(authorizeUrl!);
expect(url.searchParams.get("redirect_uri")).toBe("http://127.0.0.1:34338/callback");
expect(url.searchParams.get("state")).toBe("state-1");
});
it("returns null when the CLI OAuth client id is not configured", () => {
vi.stubEnv("VITE_CLERK_PUBLISHABLE_KEY", TEST_PUBLISHABLE_KEY);
expect(
+10 -1
View File
@@ -1,6 +1,7 @@
import {
buildConnectClerkAuthorizeUrl,
connectCallbackUrl,
connectLoopbackRedirectUri,
CONNECT_OAUTH_SCOPES,
type ConnectAuthorizeRequest,
} from "@t3tools/shared/connectAuth";
@@ -34,6 +35,11 @@ export function connectCliAuthRoutesEnabled(): boolean {
* Builds the Clerk authorize URL for a CLI-initiated connect request. The
* state is mirrored into sessionStorage so the callback page can verify the
* response matches a request this browser actually started.
*
* A request carrying a loopback port came from a CLI with a local callback
* listener: the authorization code must return to `127.0.0.1` directly, so
* the hosted callback page never sees it. Clerk enforces its registered
* redirect URI allowlist either way.
*/
export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeRequest): string | null {
const { clerkPublishableKey } = resolveCloudPublicConfig();
@@ -44,7 +50,10 @@ export function buildConnectCliClerkAuthorizeUrl(request: ConnectAuthorizeReques
return buildConnectClerkAuthorizeUrl({
authorizationEndpoint: `${clerkFrontendApiUrlFromPublishableKey(clerkPublishableKey)}/oauth/authorize`,
clientId,
redirectUri: connectCallbackUrl(configuredHostedAppUrl()),
redirectUri:
request.loopbackPort === undefined
? connectCallbackUrl(configuredHostedAppUrl())
: connectLoopbackRedirectUri(request.loopbackPort),
scopes: CONNECT_OAUTH_SCOPES,
state: request.state,
challenge: request.challenge,
+18 -4
View File
@@ -10,7 +10,7 @@ import {
import { useLocation, useNavigate } from "@tanstack/react-router";
import { isElectron } from "../env";
import { getLocalStorageItem } from "../hooks/useLocalStorage";
import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalStorage";
import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings";
import { cn, isMacPlatform } from "../lib/utils";
import { primaryServerKeybindingsAtom } from "../state/server";
@@ -19,7 +19,10 @@ import LegacyThreadSidebar from "./LegacySidebar";
import ThreadSidebar from "./Sidebar";
import { SettingsSidebarNav } from "./settings/SettingsSidebarNav";
import { SidebarChromeHeader } from "./sidebar/SidebarChrome";
import { useSidebarStageBackdropVariant } from "./SidebarStageBackdrop";
import {
resolveSidebarStageFocusRingOffsetClass,
useSidebarStageBackdropVariant,
} from "./SidebarStageBackdrop";
import { useProjects } from "../state/entities";
import {
resolveInitialThreadSidebarWidth,
@@ -105,7 +108,10 @@ function SidebarControl() {
"pointer-events-auto",
isSidebarVisible &&
stageBackdropVariant &&
"[:hover,[data-pressed]]:bg-white/15 focus-visible:ring-white/90 focus-visible:ring-offset-blue-700 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white!",
"focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",
isSidebarVisible &&
stageBackdropVariant &&
resolveSidebarStageFocusRingOffsetClass(stageBackdropVariant),
)}
aria-label="Toggle main sidebar"
/>
@@ -141,6 +147,14 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
// that would otherwise refresh a render-time snapshot.
const viewportWidth = useSyncExternalStore(subscribeToViewportWidth, readViewportWidth);
const sidebarMaximumWidth = resolveThreadSidebarMaximumWidth(viewportWidth);
const resetSidebarWidth = () => {
try {
removeLocalStorageItem(THREAD_SIDEBAR_WIDTH_STORAGE_KEY);
} catch (error) {
console.error("Could not clear persisted thread sidebar width.", error);
}
setSidebarWidth(resolveInitialThreadSidebarWidth(null, viewportWidth));
};
const [isWindowFullscreen, setIsWindowFullscreen] = useState(() => {
const getWindowFullscreenState = window.desktopBridge?.getWindowFullscreenState;
return isMacosDesktop && typeof getWindowFullscreenState === "function"
@@ -219,7 +233,7 @@ export function AppSidebarLayout({ children }: { children: ReactNode }) {
) : (
<ThreadSidebar />
)}
<SidebarRail />
<SidebarRail onDoubleClick={resetSidebarWidth} />
</Sidebar>
{children}
<SidebarControl />
+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>
+40 -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";
@@ -474,6 +480,14 @@ function shouldTypeToFocusComposer(event: KeyboardEvent): boolean {
if (eventPathContainsSelector(event, TYPE_TO_FOCUS_INTERACTIVE_SELECTOR)) return false;
if (document.querySelector(TYPE_TO_FOCUS_FLOATING_LAYER_SELECTOR)) return false;
// The right-panel surface launcher claims its shortcut letters while it is
// visible (data attribute set in RightPanelTabs); those keys open surfaces
// instead of typing into the composer.
const launcherKeys = document
.querySelector("[data-surface-launcher-keys]")
?.getAttribute("data-surface-launcher-keys");
if (launcherKeys && launcherKeys.toLowerCase().includes(event.key.toLowerCase())) return false;
return true;
}
@@ -1493,6 +1507,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 +2650,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 +6178,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} />;
}
+203 -58
View File
@@ -11,6 +11,7 @@ import {
X,
} from "lucide-react";
import {
type KeyboardEvent as ReactKeyboardEvent,
type MouseEvent as ReactMouseEvent,
type ReactElement,
type ReactNode,
@@ -25,6 +26,7 @@ import type { RightPanelSurface } from "~/rightPanelStore";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
import { Tooltip, TooltipPopup, TooltipTrigger } from "~/components/ui/tooltip";
import { Kbd } from "~/components/ui/kbd";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "~/components/ui/menu";
import { ScrollArea } from "~/components/ui/scroll-area";
import { faviconUrlForOrigin } from "~/lib/favicon";
@@ -88,6 +90,28 @@ const SURFACE_DISABLED_REASONS = {
agents: "Agents are only available from a thread.",
} as const;
/** Overlays that must win over the launcher's letter shortcuts. */
const LAUNCHER_SHORTCUT_BLOCKING_LAYERS = [
'[data-slot="dialog-popup"]',
'[data-slot="alert-dialog-popup"]',
'[data-slot="command-dialog-popup"]',
'[data-slot="menu-popup"]',
'[data-slot="select-popup"]',
'[data-slot="popover-popup"]',
'[data-slot="combobox-popup"]',
'[data-slot="autocomplete-popup"]',
].join(",");
/** One-line unavailability hints for the empty-state cards. */
const SURFACE_UNAVAILABLE_HINTS = {
browser: "Only available in the desktop app.",
terminal: "Available when a project is open.",
files: "Available when a project is open.",
diff: "Available for Git repositories.",
pullRequest: "No pull request on this branch yet.",
agents: "Available from a thread.",
} as const;
type TabContextMenuAction = "copy-path" | "close" | "close-others" | "close-to-right" | "close-all";
function DisabledReasonTooltip(props: { reason: string; trigger: ReactElement }) {
@@ -118,6 +142,13 @@ function SurfaceMenuItem(props: {
return <DisabledReasonTooltip reason={props.disabledReason} trigger={item} />;
}
/**
* Card launcher shown when the right panel has no surfaces. Keyboard-first
* without palette chrome: a surface's letter opens it directly from anywhere
* outside a typing context, and arrows plus Enter work while the launcher is
* focused. The highlight only appears on hover or arrow use. Unavailable
* surfaces stay visible with a one-line reason.
*/
function RightPanelEmptyState(props: {
onAddBrowser: () => void;
onAddTerminal: () => void;
@@ -133,13 +164,17 @@ function RightPanelEmptyState(props: {
agentsAvailable: boolean;
liveAgentCount: number;
}) {
// -1 means no highlight: it only appears on hover or arrow use.
const [highlight, setHighlight] = useState(-1);
const actions = [
{
label: "Browser",
description: "Open a local app or URL.",
icon: Globe2,
shortcut: "B",
available: props.browserAvailable,
disabledReason: SURFACE_DISABLED_REASONS.browser,
disabledReason: SURFACE_UNAVAILABLE_HINTS.browser,
onClick: props.onAddBrowser,
badgeCount: 0,
},
@@ -147,8 +182,9 @@ function RightPanelEmptyState(props: {
label: "Terminal",
description: "Start a shell in this workspace.",
icon: TerminalSquare,
shortcut: "T",
available: props.terminalAvailable,
disabledReason: SURFACE_DISABLED_REASONS.terminal,
disabledReason: SURFACE_UNAVAILABLE_HINTS.terminal,
onClick: props.onAddTerminal,
badgeCount: 0,
},
@@ -156,8 +192,9 @@ function RightPanelEmptyState(props: {
label: "Files",
description: "Browse and read workspace files.",
icon: Files,
shortcut: "F",
available: props.filesAvailable,
disabledReason: SURFACE_DISABLED_REASONS.files,
disabledReason: SURFACE_UNAVAILABLE_HINTS.files,
onClick: props.onAddFiles,
badgeCount: 0,
},
@@ -165,91 +202,199 @@ function RightPanelEmptyState(props: {
label: "Diff",
description: "Review changes in this thread.",
icon: FileDiff,
shortcut: "D",
available: props.diffAvailable,
disabledReason: SURFACE_DISABLED_REASONS.diff,
disabledReason: SURFACE_UNAVAILABLE_HINTS.diff,
onClick: props.onAddDiff,
badgeCount: 0,
},
{
label: "Pull request",
description: "Open the pull request for this thread's branch.",
description: "Open this branch's pull request.",
icon: GitPullRequest,
shortcut: "P",
available: props.pullRequestAvailable,
disabledReason: SURFACE_DISABLED_REASONS.pullRequest,
disabledReason: SURFACE_UNAVAILABLE_HINTS.pullRequest,
onClick: props.onAddPullRequest,
badgeCount: 0,
},
{
label: "Agents",
description: "Watch subagents and workflows run.",
description: "Follow subagents and workflows.",
icon: Bot,
shortcut: "A",
available: props.agentsAvailable,
disabledReason: SURFACE_DISABLED_REASONS.agents,
disabledReason: SURFACE_UNAVAILABLE_HINTS.agents,
onClick: props.onAddAgents,
badgeCount: props.liveAgentCount,
},
] as const;
type SurfaceAction = (typeof actions)[number];
const availableActions = actions.filter((action) => action.available);
const highlightIndex =
availableActions.length === 0 ? -1 : Math.min(highlight, availableActions.length - 1);
// Letter shortcuts work while the launcher is visible, not only while it
// is focused; focus moves around too easily (stray clicks) to carry them.
// Capture phase so app-level key handlers cannot swallow the event first;
// typing contexts and already-handled events are left alone.
const shortcutActionsRef = useRef(availableActions);
useEffect(() => {
shortcutActionsRef.current = availableActions;
});
useEffect(() => {
const handler = (event: KeyboardEvent) => {
if (event.defaultPrevented || event.isComposing) return;
if (event.metaKey || event.ctrlKey || event.altKey) return;
if (document.querySelector(LAUNCHER_SHORTCUT_BLOCKING_LAYERS)) return;
const target = event.target;
if (target instanceof HTMLElement) {
if (target.closest("input, textarea, select")) return;
// An empty contenteditable (the chat composer at rest) does not
// count as typing; letters only become text once a draft exists.
const editable = target.isContentEditable ? target : target.closest("[contenteditable]");
if (editable && (editable.textContent ?? "").trim().length > 0) return;
}
const action = shortcutActionsRef.current.find(
(candidate) => candidate.shortcut.toLowerCase() === event.key.toLowerCase(),
);
if (!action) return;
event.preventDefault();
event.stopPropagation();
action.onClick();
};
window.addEventListener("keydown", handler, true);
return () => window.removeEventListener("keydown", handler, true);
}, []);
const handleKeyDown = (event: ReactKeyboardEvent<HTMLDivElement>) => {
if (event.defaultPrevented || event.metaKey || event.ctrlKey || event.altKey) return;
if (availableActions.length === 0) return;
if (event.key === "ArrowDown" || event.key === "ArrowRight") {
event.preventDefault();
setHighlight((highlightIndex + 1) % availableActions.length);
return;
}
if (event.key === "ArrowUp" || event.key === "ArrowLeft") {
event.preventDefault();
setHighlight(
highlightIndex === -1
? availableActions.length - 1
: (highlightIndex - 1 + availableActions.length) % availableActions.length,
);
return;
}
if (event.key === "Enter") {
// A focused card button owns its own activation; only open from the
// highlight when the container itself has focus.
if (event.target instanceof HTMLElement && event.target.closest("button")) return;
const action = availableActions[highlightIndex];
if (!action) return;
event.preventDefault();
action.onClick();
}
};
// Stable identity so React only runs this callback ref on mount/unmount;
// an inline arrow would re-attach and re-focus on every render.
const focusOnMount = useCallback((node: HTMLDivElement | null) => {
node?.focus();
}, []);
const isHighlighted = (action: SurfaceAction) =>
highlightIndex !== -1 && availableActions[highlightIndex] === action;
const actionIcon = (action: SurfaceAction, iconClassName = "size-4") => {
const Icon = action.icon;
return (
<span className="relative inline-flex shrink-0">
<Icon className={iconClassName} />
{action.badgeCount > 0 ? (
<span
aria-hidden
className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
>
{action.badgeCount}
</span>
) : null}
</span>
);
};
const cardShellClass =
"rounded-lg border border-border/80 bg-card dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5";
const highlightedCardClass = "bg-accent/60 dark:inset-ring-white/20";
return (
<div className="flex min-h-0 flex-1 items-center justify-center p-6">
<div className="w-full max-w-xl">
<div className="mb-5 text-center">
<h3 className="text-sm font-medium text-foreground">Open a surface</h3>
<p className="mt-1 text-xs text-muted-foreground">
<div
ref={focusOnMount}
tabIndex={0}
onKeyDown={handleKeyDown}
aria-label="Open a surface"
data-surface-launcher-keys={availableActions.map((action) => action.shortcut).join("")}
className={cn(
"flex min-h-0 flex-1 items-center justify-center overflow-y-auto px-6 pt-6 outline-none",
// The panel topbar sits above this container; matching bottom padding
// keeps the cards centered against the full panel, not the leftover.
"pb-[calc(var(--workspace-topbar-height)+--spacing(6))]",
)}
>
<div className="relative w-full max-w-lg">
<div className="absolute inset-x-0 bottom-full mb-5 text-center">
<h3 className="font-medium text-foreground text-sm">Open a surface</h3>
<p className="mt-1 text-muted-foreground text-xs">
Choose what to show in the right panel.
</p>
</div>
<div className="grid grid-cols-2 gap-2">
{actions.map((action) => {
const Icon = action.icon;
const content = (
<>
<span className="relative mb-3 inline-flex">
<Icon className="size-5" />
{action.badgeCount > 0 ? (
<span
aria-hidden
className="absolute -top-1.5 -right-2 flex h-3.5 min-w-3.5 items-center justify-center rounded-full bg-info px-1 text-[9px] font-semibold tabular-nums text-white"
>
{action.badgeCount}
</span>
) : null}
{actions.map((action) =>
action.available ? (
<button
key={action.label}
type="button"
onClick={action.onClick}
onMouseEnter={() => setHighlight(availableActions.indexOf(action))}
onMouseLeave={() =>
setHighlight((current) =>
current === availableActions.indexOf(action) ? -1 : current,
)
}
className={cn(
"relative flex w-full cursor-pointer flex-col items-start p-4 text-left transition hover:border-border hover:bg-accent/60",
cardShellClass,
isHighlighted(action) && highlightedCardClass,
)}
>
<Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
<span className="flex items-center gap-2 pe-8">
{actionIcon(action)}
<span className="font-medium text-sm">{action.label}</span>
</span>
<span className="text-sm font-medium">{action.label}</span>
<span className="mt-1 text-xs leading-relaxed text-muted-foreground">
<span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
{action.description}
</span>
</>
);
if (action.available) {
return (
<button
key={action.label}
type="button"
onClick={action.onClick}
className="cursor-pointer flex min-h-28 w-full flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left transition hover:border-border hover:bg-accent/60 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
>
{content}
</button>
);
}
const disabledCard = (
<button
type="button"
className="flex min-h-28 w-full cursor-not-allowed flex-col items-start rounded-lg border border-border/80 bg-card p-4 text-left opacity-40 dark:border-transparent dark:shadow-none dark:inset-ring-1 dark:inset-ring-white/5"
aria-disabled="true"
>
{content}
</button>
);
return (
<DisabledReasonTooltip
) : (
<div
key={action.label}
reason={action.disabledReason}
trigger={disabledCard}
/>
);
})}
className={cn(
"relative flex w-full flex-col items-start p-4 opacity-40",
cardShellClass,
)}
>
<Kbd className="absolute top-3 right-3">{action.shortcut}</Kbd>
<span className="flex items-center gap-2 pe-8">
{actionIcon(action)}
<span className="font-medium text-sm">{action.label}</span>
</span>
<span className="mt-1.5 text-muted-foreground text-xs leading-relaxed">
{action.disabledReason}
</span>
</div>
),
)}
</div>
</div>
</div>
@@ -4,6 +4,7 @@ import { renderToStaticMarkup } from "react-dom/server";
import {
resolveEnvironmentIdentificationPillLabel,
resolveSidebarStageBackdropVariant,
resolveSidebarStageFocusRingOffsetClass,
StageBackdropArt,
StageBackdropButtonArt,
} from "./SidebarStageBackdrop";
@@ -23,13 +24,22 @@ describe("SidebarStageBackdrop", () => {
expect(resolveEnvironmentIdentificationPillLabel("Alpha")).toBeNull();
});
it("matches the focus-ring offset to each artwork palette", () => {
expect(resolveSidebarStageFocusRingOffsetClass("nightly")).toBe(
"focus-visible:ring-offset-(--stage-night-bottom)",
);
expect(resolveSidebarStageFocusRingOffsetClass("dev")).toBe(
"focus-visible:ring-offset-(--stage-art-bottom)",
);
});
it.each(["nightly", "dev"] as const)(
"uses unique SVG definition ids when %s artwork is rendered more than once",
(variant) => {
const markup = renderToStaticMarkup(
<>
<StageBackdropArt variant={variant} />
<StageBackdropButtonArt variant={variant} />
<StageBackdropArt variant={variant} />
</>,
);
const ids = Array.from(markup.matchAll(/\sid="([^"]+)"/g), (match) => match[1]);
@@ -38,4 +48,26 @@ describe("SidebarStageBackdrop", () => {
expect(new Set(ids).size).toBe(ids.length);
},
);
it("paints each artwork variant with theme-owned color tokens", () => {
const nightlyMarkup = renderToStaticMarkup(<StageBackdropArt variant="nightly" />);
const devMarkup = renderToStaticMarkup(<StageBackdropArt variant="dev" />);
expect(nightlyMarkup).toContain("var(--stage-night-bottom)");
expect(nightlyMarkup).toContain("var(--stage-night-line)");
expect(devMarkup).toContain("var(--stage-art-bottom)");
expect(devMarkup).toContain("var(--stage-art-line)");
expect(nightlyMarkup).not.toMatch(/#[0-9a-f]{3,8}/i);
expect(devMarkup).not.toMatch(/#[0-9a-f]{3,8}/i);
});
it.each([
["nightly", "96 0 8192 96"],
["dev", "64 0 8192 96"],
] as const)("uses the compact %s crop inside the send button", (variant, viewBox) => {
const markup = renderToStaticMarkup(<StageBackdropButtonArt variant={variant} />);
expect(markup).toContain(`viewBox="${viewBox}"`);
expect(markup).toContain(`stage-${variant === "dev" ? "blueprint" : "nightly"}`);
});
});
@@ -23,6 +23,14 @@ export function resolveSidebarStageBackdropVariant(
return null;
}
export function resolveSidebarStageFocusRingOffsetClass(
variant: SidebarStageBackdropVariant,
): string {
return variant === "nightly"
? "focus-visible:ring-offset-(--stage-night-bottom)"
: "focus-visible:ring-offset-(--stage-art-bottom)";
}
export function resolveEnvironmentIdentificationPillLabel(
stageLabel: string,
): EnvironmentIdentificationPillLabel | null {
@@ -108,10 +116,10 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
return (
<svg
className="h-full w-full"
className="stage-art stage-nightly h-full w-full"
fill="none"
preserveAspectRatio="xMinYMin slice"
viewBox={compact ? "0 0 96 96" : STAGE_BACKDROP_VIEW_BOX}
viewBox={compact ? "96 0 8192 96" : STAGE_BACKDROP_VIEW_BOX}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
@@ -124,9 +132,9 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
gradientUnits="userSpaceOnUse"
spreadMethod="reflect"
>
<stop stopColor="#07152F" />
<stop offset="0.5" stopColor="#151443" />
<stop offset="1" stopColor="#32155B" />
<stop style={{ stopColor: "var(--stage-night-bottom)" }} />
<stop offset="0.5" style={{ stopColor: "var(--stage-night-mid)" }} />
<stop offset="1" style={{ stopColor: "var(--stage-night-top)" }} />
</linearGradient>
<radialGradient
id={glowId}
@@ -136,20 +144,28 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
gradientTransform="translate(216 18) rotate(137) scale(120 84)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#5165D8" stopOpacity="0.4" />
<stop offset="0.5" stopColor="#283075" stopOpacity="0.16" />
<stop offset="1" stopColor="#111635" stopOpacity="0" />
<stop style={{ stopColor: "var(--stage-night-highlight)" }} stopOpacity="0.4" />
<stop
offset="0.5"
style={{ stopColor: "var(--stage-night-secondary)" }}
stopOpacity="0.16"
/>
<stop offset="1" style={{ stopColor: "var(--stage-night-bottom)" }} stopOpacity="0" />
</radialGradient>
<linearGradient id={cloudId} x1="0" y1="60" x2="288" y2="96" gradientUnits="userSpaceOnUse">
<stop stopColor="#4EA4FF" stopOpacity="0.5" />
<stop offset="0.52" stopColor="#696FEA" stopOpacity="0.62" />
<stop offset="1" stopColor="#A85BEA" stopOpacity="0.5" />
<stop style={{ stopColor: "var(--stage-night-highlight)" }} stopOpacity="0.5" />
<stop
offset="0.52"
style={{ stopColor: "var(--stage-night-secondary)" }}
stopOpacity="0.62"
/>
<stop offset="1" style={{ stopColor: "var(--stage-night-tertiary)" }} stopOpacity="0.5" />
</linearGradient>
<filter id={softId} x="-24" y="-24" width="336" height="144" filterUnits="userSpaceOnUse">
<feGaussianBlur stdDeviation="4" />
</filter>
<pattern id={starsId} width="288" height="96" patternUnits="userSpaceOnUse">
<g fill="#E4EAFF">
<g style={{ fill: "var(--stage-night-line)" }}>
{NIGHTLY_STARS.map((star) => (
<circle
key={`${star.cx}-${star.cy}`}
@@ -160,7 +176,12 @@ function NightlySkyArt({ compact = false }: { compact?: boolean }) {
/>
))}
</g>
<g stroke="#C8D7FF" strokeLinecap="round" strokeOpacity="0.7" strokeWidth="0.6">
<g
style={{ stroke: "var(--stage-night-line)" }}
strokeLinecap="round"
strokeOpacity="0.7"
strokeWidth="0.6"
>
{NIGHTLY_SPARKLES.map((sparkle) => (
<g key={`${sparkle.x}-${sparkle.y}`}>
<path d={`M${sparkle.x - 1.5} ${sparkle.y}H${sparkle.x + 1.5}`} />
@@ -209,10 +230,10 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
return (
<svg
className="stage-blueprint h-full w-full"
className="stage-art stage-blueprint h-full w-full"
fill="none"
preserveAspectRatio="xMinYMin slice"
viewBox={compact ? "0 0 96 96" : STAGE_BACKDROP_VIEW_BOX}
viewBox={compact ? "64 0 8192 96" : STAGE_BACKDROP_VIEW_BOX}
xmlns="http://www.w3.org/2000/svg"
>
<defs>
@@ -225,9 +246,9 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
gradientUnits="userSpaceOnUse"
spreadMethod="reflect"
>
<stop style={{ stopColor: "var(--stage-bp-bottom)" }} />
<stop offset="0.5" style={{ stopColor: "var(--stage-bp-mid)" }} />
<stop offset="1" style={{ stopColor: "var(--stage-bp-top)" }} />
<stop style={{ stopColor: "var(--stage-art-bottom)" }} />
<stop offset="0.5" style={{ stopColor: "var(--stage-art-mid)" }} />
<stop offset="1" style={{ stopColor: "var(--stage-art-top)" }} />
</linearGradient>
<radialGradient
id={glowId}
@@ -237,9 +258,13 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
gradientTransform="translate(216 14) rotate(137) scale(120 84)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#D4F6FF" stopOpacity="0.4" />
<stop offset="0.52" stopColor="#65C8FF" stopOpacity="0.16" />
<stop offset="1" stopColor="#276AF1" stopOpacity="0" />
<stop style={{ stopColor: "var(--stage-art-highlight)" }} stopOpacity="0.4" />
<stop
offset="0.52"
style={{ stopColor: "var(--stage-art-secondary)" }}
stopOpacity="0.16"
/>
<stop offset="1" style={{ stopColor: "var(--stage-art-bottom)" }} stopOpacity="0" />
</radialGradient>
<radialGradient
id={celesteGlowId}
@@ -249,9 +274,13 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
gradientTransform="translate(474 44) rotate(166) scale(156 92)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#D2FFFF" stopOpacity="0.34" />
<stop offset="0.5" stopColor="#48DCF5" stopOpacity="0.18" />
<stop offset="1" stopColor="#277EF1" stopOpacity="0" />
<stop style={{ stopColor: "var(--stage-art-highlight)" }} stopOpacity="0.34" />
<stop
offset="0.5"
style={{ stopColor: "var(--stage-art-secondary)" }}
stopOpacity="0.18"
/>
<stop offset="1" style={{ stopColor: "var(--stage-art-bottom)" }} stopOpacity="0" />
</radialGradient>
<radialGradient
id={violetGlowId}
@@ -261,20 +290,34 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
gradientTransform="translate(704 18) rotate(145) scale(132 88)"
gradientUnits="userSpaceOnUse"
>
<stop stopColor="#D9D8FF" stopOpacity="0.3" />
<stop offset="0.52" stopColor="#7C8BFF" stopOpacity="0.14" />
<stop offset="1" stopColor="#3155DF" stopOpacity="0" />
<stop style={{ stopColor: "var(--stage-art-highlight)" }} stopOpacity="0.3" />
<stop
offset="0.52"
style={{ stopColor: "var(--stage-art-tertiary)" }}
stopOpacity="0.14"
/>
<stop offset="1" style={{ stopColor: "var(--stage-art-bottom)" }} stopOpacity="0" />
</radialGradient>
<pattern id={minorGridId} width="8" height="8" patternUnits="userSpaceOnUse">
<path d="M8 0H0V8" stroke="#EAF6FF" strokeOpacity="0.14" strokeWidth="0.5" />
<path
d="M8 0H0V8"
style={{ stroke: "var(--stage-art-line)" }}
strokeOpacity="0.14"
strokeWidth="0.5"
/>
</pattern>
<pattern id={majorGridId} width="32" height="32" patternUnits="userSpaceOnUse">
<path d="M32 0H0V32" stroke="#EAF6FF" strokeOpacity="0.26" strokeWidth="0.6" />
<path
d="M32 0H0V32"
style={{ stroke: "var(--stage-art-line)" }}
strokeOpacity="0.26"
strokeWidth="0.6"
/>
</pattern>
<pattern id={rulerId} width="32" height="6" patternUnits="userSpaceOnUse">
<path
d="M4 0V2.5M12 0V2.5M20 0V4M28 0V2.5"
stroke="#DDF7FF"
style={{ stroke: "var(--stage-art-line)" }}
strokeOpacity="0.5"
strokeWidth="0.5"
/>
@@ -285,7 +328,12 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
<rect width="768" height="96" fill={`url(#${violetGlowId})`} />
</pattern>
<pattern id={annotationsId} width="768" height="96" patternUnits="userSpaceOnUse">
<g stroke="#DDF7FF" strokeLinecap="round" strokeOpacity="0.6" strokeWidth="0.7">
<g
style={{ stroke: "var(--stage-art-line)" }}
strokeLinecap="round"
strokeOpacity="0.6"
strokeWidth="0.7"
>
<path d="M180 64H264" strokeDasharray="5 4" />
<path d="M180 61V67M264 61V67" />
<path d="M276 10V44" strokeDasharray="4 4" strokeOpacity="0.5" />
@@ -298,7 +346,12 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
<path d="M590 67V73M724 67V73" strokeOpacity="0.55" />
</g>
<g stroke="#DDF7FF" strokeLinecap="round" strokeOpacity="0.55" strokeWidth="0.6">
<g
style={{ stroke: "var(--stage-art-line)" }}
strokeLinecap="round"
strokeOpacity="0.55"
strokeWidth="0.6"
>
<g>
<path d="M34 60L38 64M38 60L34 64" />
</g>
@@ -322,7 +375,7 @@ function DevBlueprintArt({ compact = false }: { compact?: boolean }) {
</g>
</g>
<g stroke="#DDF7FF" strokeOpacity="0.35" strokeWidth="0.6">
<g style={{ stroke: "var(--stage-art-line)" }} strokeOpacity="0.35" strokeWidth="0.6">
<circle cx="196" cy="38" r="13" strokeDasharray="3.5 4" />
<path d="M196 33V43M191 38H201" strokeOpacity="0.6" strokeWidth="0.4" />
<circle cx="414" cy="64" r="10" strokeDasharray="2.5 3.5" />
@@ -23,6 +23,14 @@ describe("ChangedFilesCard", () => {
expect(markup).toContain('data-changed-files-state="expanded"');
expect(markup).toContain('aria-expanded="true"');
expect(markup).toContain("whitespace-nowrap");
expect(markup).toContain(
'class="group flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden',
);
expect(markup).toContain('class="flex shrink-0 items-center gap-1 whitespace-nowrap');
expect(markup).toContain('class="ml-1 hidden min-w-0 flex-1 truncate');
expect(markup).toContain("@[24rem]/changed-files:inline");
expect(markup).not.toContain("sm:inline");
expect(markup).toContain('class="flex shrink-0 items-center gap-1.5"');
expect(markup).toContain("!size-[22px]");
expect(markup).toContain("size-3");
expect(markup).toContain('aria-label="Collapse all folders"');
@@ -56,7 +56,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
return (
<div
className="mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
className="@container/changed-files mt-4 rounded-2xl border border-border/70 bg-secondary p-2 dark:border-transparent dark:bg-input/32"
data-changed-files-state={
expanded ? "expanded" : compactPreviewVisible ? "preview" : "collapsed"
}
@@ -73,7 +73,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
type="button"
aria-expanded={expanded}
data-scroll-anchor-ignore
className="group flex min-w-0 flex-1 items-center gap-1.5 rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
className="group flex min-w-0 flex-1 items-center gap-1.5 overflow-hidden rounded-lg px-1 py-1.5 text-left transition-colors hover:bg-accent/60 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => onExpandedChange(!expanded)}
>
<ChevronRightIcon
@@ -83,7 +83,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
expanded && "rotate-90",
)}
/>
<span className="flex min-w-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span className="flex shrink-0 items-center gap-1 whitespace-nowrap font-medium text-foreground text-xs leading-4">
<span>
{files.length} changed file{files.length === 1 ? "" : "s"}
</span>
@@ -96,11 +96,11 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
/>
)}
</span>
<span className="ml-1 hidden truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 sm:inline">
<span className="ml-1 hidden min-w-0 flex-1 truncate text-[11px] text-muted-foreground group-hover:text-foreground/80 @[24rem]/changed-files:inline">
{expanded ? "Hide files" : "Show files"}
</span>
</button>
<div className="flex items-center gap-1.5">
<div className="flex shrink-0 items-center gap-1.5">
{expanded ? (
<Tooltip>
<TooltipTrigger
@@ -142,7 +142,7 @@ export const ChangedFilesCard = memo(function ChangedFilesCard(props: {
}
>
<FileDiffIcon className="size-3" />
<span className="hidden sm:inline">Open diff</span>
<span className="hidden @[24rem]/changed-files:inline">Open diff</span>
</TooltipTrigger>
<TooltipPopup side="top">Open the full diff</TooltipPopup>
</Tooltip>
@@ -3106,7 +3106,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
showMobilePendingAnswerActions && "hidden sm:flex",
)}
>
<div className="-m-1 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
<div className="-m-1 -ms-3.5 flex min-w-0 flex-1 items-center gap-1 overflow-x-auto p-1 ps-3.5 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
{noProviderAvailable ? (
<Button
type="button"
@@ -3129,7 +3129,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
instanceEntries={providerInstanceEntries}
keybindings={keybindings}
modelOptionsByInstance={modelOptionsByInstance}
triggerClassName="-ms-px"
triggerClassName="-ms-2.5"
terminalOpen={terminalOpen}
open={isComposerModelPickerOpen}
{...(composerProviderState.modelPickerIconClassName
@@ -1,18 +1,18 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
const stageMock = vi.hoisted(() => ({
artworkEnabled: false,
variant: null as "dev" | "nightly" | null,
const stageArtworkState = vi.hoisted(() => ({
mode: "none" as "artwork" | "none",
variant: null as "nightly" | "dev" | null,
}));
vi.mock("~/hooks/useSettings", () => ({
useDefaultEnvironmentArtworkEnabled: () => stageMock.artworkEnabled,
useEnvironmentIdentificationMode: () => stageArtworkState.mode,
}));
vi.mock("../SidebarStageBackdrop", () => ({
StageBackdropButtonArt: ({ variant }: { variant: "dev" | "nightly" }) => `stage-${variant}`,
useSidebarStageBackdropVariant: (enabled: boolean) => (enabled ? stageMock.variant : null),
StageBackdropButtonArt: ({ variant }: { variant: string }) => `stage-${variant}`,
useSidebarStageBackdropVariant: (enabled = true) => (enabled ? stageArtworkState.variant : null),
}));
import { ComposerPrimaryActions, formatPendingPrimaryActionLabel } from "./ComposerPrimaryActions";
@@ -65,28 +65,20 @@ function renderStandaloneStop() {
);
}
function renderSendAction(
input: Partial<{
hasSendableContent: boolean;
isConnecting: boolean;
isSendBusy: boolean;
isEnvironmentUnavailable: boolean;
sendDisabledReason: string | null;
}> = {},
) {
function renderSendButton() {
return renderToStaticMarkup(
createElement(ComposerPrimaryActions, {
compact: true,
pendingAction: null,
isRunning: false,
showPlanFollowUpPrompt: false,
promptHasText: false,
isSendBusy: input.isSendBusy ?? false,
sendDisabledReason: input.sendDisabledReason ?? null,
isConnecting: input.isConnecting ?? false,
isEnvironmentUnavailable: input.isEnvironmentUnavailable ?? false,
promptHasText: true,
isSendBusy: false,
sendDisabledReason: null,
isConnecting: false,
isEnvironmentUnavailable: false,
isPreparingWorktree: false,
hasSendableContent: input.hasSendableContent ?? true,
hasSendableContent: true,
onPreviousPendingQuestion: () => {},
onInterrupt: () => {},
onImplementPlanInNewThread: () => {},
@@ -94,6 +86,11 @@ function renderSendAction(
);
}
afterEach(() => {
stageArtworkState.mode = "none";
stageArtworkState.variant = null;
});
describe("formatPendingPrimaryActionLabel", () => {
it("returns 'Submitting...' while responding", () => {
expect(
@@ -199,40 +196,23 @@ describe("ComposerPrimaryActions", () => {
expect(renderStandaloneStop()).not.toContain("sm:size-7");
});
it.each(["dev", "nightly"] as const)(
"uses %s artwork on the send action in artwork mode",
(variant) => {
stageMock.artworkEnabled = true;
stageMock.variant = variant;
it("renders stage artwork inside the send button when artwork identification is active", () => {
stageArtworkState.mode = "artwork";
stageArtworkState.variant = "nightly";
const markup = renderSendAction();
const markup = renderSendButton();
expect(markup).toContain(`stage-${variant}`);
expect(markup).toContain("bg-transparent");
expect(markup).toContain('aria-label="Send message"');
},
);
it("keeps the standard send action when default-theme artwork is disabled", () => {
stageMock.artworkEnabled = false;
stageMock.variant = "dev";
const markup = renderSendAction();
expect(markup).not.toContain("stage-dev");
expect(markup).toContain("bg-message-action");
expect(markup).toContain("stage-nightly");
expect(markup).toContain("bg-transparent text-white");
expect(markup).not.toContain("bg-message-action text-message-action-foreground");
});
it("preserves busy and disabled labels with artwork", () => {
stageMock.artworkEnabled = true;
stageMock.variant = "nightly";
it("keeps the normal send-button fill when artwork identification is inactive", () => {
stageArtworkState.variant = "nightly";
expect(renderSendAction({ isSendBusy: true })).toContain('aria-label="Sending"');
expect(renderSendAction({ isEnvironmentUnavailable: true })).toContain(
'aria-label="Environment disconnected"',
);
expect(renderSendAction({ sendDisabledReason: "Choose a provider" })).toContain(
'aria-label="Choose a provider"',
);
const markup = renderSendButton();
expect(markup).not.toContain("stage-nightly");
expect(markup).toContain("bg-message-action text-message-action-foreground");
});
});
@@ -1,6 +1,6 @@
import { memo, type PointerEventHandler } from "react";
import { ChevronDownIcon, ChevronLeftIcon } from "lucide-react";
import { useDefaultEnvironmentArtworkEnabled } from "~/hooks/useSettings";
import { useEnvironmentIdentificationMode } from "~/hooks/useSettings";
import { cn } from "~/lib/utils";
import { StageBackdropButtonArt, useSidebarStageBackdropVariant } from "../SidebarStageBackdrop";
import { Button } from "../ui/button";
@@ -75,9 +75,11 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
const pointerFocusProps = preserveComposerFocusOnPointerDown
? { onPointerDown: preventPointerFocus }
: undefined;
const defaultEnvironmentArtworkEnabled = useDefaultEnvironmentArtworkEnabled();
const environmentIdentificationMode = useEnvironmentIdentificationMode();
const isSendDisabled = sendDisabledReason !== null;
const stageBackdropVariant = useSidebarStageBackdropVariant(defaultEnvironmentArtworkEnabled);
const stageBackdropVariant = useSidebarStageBackdropVariant(
environmentIdentificationMode === "artwork",
);
const renderStopGenerationButton = (insidePendingAction: boolean) => (
<button
@@ -216,10 +218,10 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
<button
type="submit"
className={cn(
"relative isolate flex h-9 w-9 items-center justify-center overflow-hidden rounded-full text-message-action-foreground shadow-xs transition-all duration-150 enabled:cursor-pointer enabled:inset-shadow-[0_1px_--theme(--color-white/16%)] hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none disabled:pointer-events-none disabled:opacity-30 disabled:shadow-none disabled:hover:scale-100 sm:h-8 sm:w-8",
"relative isolate flex h-9 w-9 items-center justify-center overflow-hidden rounded-full shadow-xs transition-all duration-150 enabled:cursor-pointer enabled:inset-shadow-[0_1px_--theme(--color-white/16%)] hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none disabled:pointer-events-none disabled:opacity-30 disabled:shadow-none disabled:hover:scale-100 sm:h-8 sm:w-8",
stageBackdropVariant
? "bg-transparent enabled:shadow-black/24 enabled:hover:brightness-110"
: "bg-message-action enabled:shadow-message-action/24 hover:bg-message-action-hover",
? "bg-transparent text-white enabled:shadow-black/24 enabled:hover:brightness-110"
: "bg-message-action text-message-action-foreground enabled:shadow-message-action/24 hover:bg-message-action-hover",
)}
{...pointerFocusProps}
disabled={
@@ -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,
@@ -0,0 +1,91 @@
import { describe, expect, it } from "vite-plus/test";
import {
EMBER_THEME,
GROVE_THEME,
IRIS_THEME,
OCEAN_THEME,
T3_CHAT_THEME,
themeColorToHex,
type ThemeColors,
} from "../../themePalette";
import { clerkAppearance } from "./clerkAppearance";
function contrastRatio(first: string, second: string): number {
const toRgb = (value: string) => {
const hex = themeColorToHex(value)?.slice(1, 7);
if (!hex) throw new Error(`Expected a theme color, received ${value}`);
return [0, 1, 2].map(
(channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16) / 255,
);
};
const luminance = (value: string) =>
toRgb(value)
.map((channel) => (channel <= 0.03928 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4))
.reduce((sum, channel, index) => sum + channel * [0.2126, 0.7152, 0.0722][index]!, 0);
const lighter = Math.max(luminance(first), luminance(second));
const darker = Math.min(luminance(first), luminance(second));
return (lighter + 0.05) / (darker + 0.05);
}
function mixThemeColors(first: string, second: string, firstWeight: number): string {
const channels = [first, second].map((value) => {
const hex = themeColorToHex(value)?.slice(1, 7);
if (!hex) throw new Error(`Expected a theme color, received ${value}`);
return [0, 1, 2].map((channel) => Number.parseInt(hex.slice(channel * 2, channel * 2 + 2), 16));
});
const mixed = channels[0]!.map((channel, index) =>
Math.round(channel * firstWeight + channels[1]![index]! * (1 - firstWeight)),
);
return `#${mixed.map((channel) => channel.toString(16).padStart(2, "0")).join("")}`;
}
const builtInThemeModes = [
T3_CHAT_THEME,
GROVE_THEME,
OCEAN_THEME,
EMBER_THEME,
IRIS_THEME,
].flatMap((theme) =>
[theme.colors, theme.variants?.dark].filter((colors): colors is ThemeColors => !!colors),
);
describe("clerkAppearance", () => {
it("maps theme colors without overriding Clerk's component structure", () => {
expect(clerkAppearance).toEqual({
variables: {
colorPrimary: "var(--update-foreground)",
colorPrimaryForeground: "var(--card)",
colorDanger: "var(--error)",
colorSuccess: "var(--success)",
colorWarning: "var(--warning)",
colorNeutral: "var(--foreground)",
colorForeground: "var(--foreground)",
colorMuted: "color-mix(in srgb, var(--card) 98%, var(--foreground))",
colorMutedForeground: "var(--muted-foreground)",
colorBackground: "var(--card)",
colorInputForeground: "var(--foreground)",
colorInput: "var(--secondary)",
colorRing: "var(--ring)",
},
elements: {
formFieldErrorText: { color: "var(--error-foreground)" },
formFieldWarningText: { color: "var(--warning-foreground)" },
formFieldSuccessText: { color: "var(--success-foreground)" },
otpCodeFieldErrorText: { color: "var(--error-foreground)" },
otpCodeFieldSuccessText: { color: "var(--success-foreground)" },
},
});
});
it.each(builtInThemeModes)("keeps Clerk text readable across a built-in palette", (colors) => {
const mutedSurface = mixThemeColors(colors.surface, colors.text, 0.98);
expect(contrastRatio(colors.text, colors.surface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.mutedForeground, mutedSurface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.text, colors.secondary)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.updateForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.errorForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);
expect(contrastRatio(colors.warningForeground, colors.surface)).toBeGreaterThanOrEqual(4.5);
});
});
@@ -0,0 +1,34 @@
import type { ClerkProviderProps } from "@clerk/react";
/** Keeps Clerk's stock component structure while binding its color system to
* the live T3 Code palette. CSS variables make theme changes propagate to
* portaled sign-in and profile surfaces without remounting Clerk. */
export const clerkAppearance = {
variables: {
// Clerk reuses its primary color for filled buttons and bare links. The
// app's update foreground is the palette's action hue cast for readable
// text, while the card surface provides the inverse filled-control pair.
colorPrimary: "var(--update-foreground)",
colorPrimaryForeground: "var(--card)",
colorDanger: "var(--error)",
colorSuccess: "var(--success)",
colorWarning: "var(--warning)",
colorNeutral: "var(--foreground)",
colorForeground: "var(--foreground)",
// The stock dark theme's muted token is translucent. Clerk uses this as
// the footer's background, so derive an opaque muted surface from the card.
colorMuted: "color-mix(in srgb, var(--card) 98%, var(--foreground))",
colorMutedForeground: "var(--muted-foreground)",
colorBackground: "var(--card)",
colorInputForeground: "var(--foreground)",
colorInput: "var(--secondary)",
colorRing: "var(--ring)",
},
elements: {
formFieldErrorText: { color: "var(--error-foreground)" },
formFieldWarningText: { color: "var(--warning-foreground)" },
formFieldSuccessText: { color: "var(--success-foreground)" },
otpCodeFieldErrorText: { color: "var(--error-foreground)" },
otpCodeFieldSuccessText: { color: "var(--success-foreground)" },
},
} satisfies NonNullable<ClerkProviderProps["appearance"]>;
@@ -44,8 +44,10 @@ const invalidLinkMessage = {
} as const;
/**
* /connect: the URL a headless CLI prints. Waits for a Clerk session, then
* forwards the CLI's PKCE request to Clerk's authorize endpoint.
* /connect: the URL the CLI prints for both flows. Waits for a Clerk session,
* then forwards the CLI's PKCE request to Clerk's authorize endpoint — with a
* loopback redirect URI when the request carries a port, so the code returns
* straight to the waiting CLI, and the hosted callback page otherwise.
*/
export function ConnectCliAuthorizeSurface() {
const [request] = useState(() => readConnectAuthorizeRequest(new URL(window.location.href)));
@@ -85,7 +87,11 @@ export function ConnectCliAuthorizeSurface() {
return (
<AuthSurfaceShell>
<ConnectCliAuthMessage
eyebrow="Step 1 of 2 · Browser authorization"
eyebrow={
request.loopbackPort === undefined
? "Step 1 of 2 · Browser authorization"
: "Browser authorization"
}
title="Connecting your terminal"
description={
isSignedIn
@@ -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>
@@ -165,7 +165,6 @@ export function ThemeEditorPanel({
const isEditing = editingTheme !== null;
const [name, setName] = useState("");
const [activeAppearance, setActiveAppearance] = useState<ThemeAppearance>(initialAppearance);
const [sidebarArtwork, setSidebarArtwork] = useState(false);
const [isAdvanced, setIsAdvanced] = useState(false);
const [colorsByAppearance, setColorsByAppearance] = useState<ThemeEditorColorsByAppearance>(() =>
getThemeEditorColorsByAppearance(),
@@ -179,7 +178,6 @@ export function ThemeEditorPanel({
const [isInspecting, setIsInspecting] = useState(false);
const [selectedRole, setSelectedRole] = useState<ThemeColorRole | null>(null);
const [usageCount, setUsageCount] = useState<number | null>(null);
const previousMergeTargetIdRef = useRef<string | null>(null);
// Null parks the panel at its default corner; a value is a dragged spot,
// kept clamped so the header can always be grabbed again.
const [position, setPosition] = useState<{ x: number; y: number } | null>(null);
@@ -230,7 +228,6 @@ export function ThemeEditorPanel({
};
window.addEventListener("resize", clamp);
return () => window.removeEventListener("resize", clamp);
// oxlint-disable-next-line exhaustive-deps -- clampPosition reads live layout only.
}, [isMinimized, open]);
// The draft only reaches the live app once this open has been seeded;
@@ -261,9 +258,6 @@ export function ThemeEditorPanel({
setName(editingTheme?.label ?? seedName ?? "");
setActiveAppearance(nextAppearance);
// Artwork is opt-in for new themes, including duplicates. Editing keeps
// the theme's existing choice.
setSidebarArtwork(editingTheme?.sidebarArtwork === true);
// Themes saved by the guided editor carry the managed flag; anything
// else (imports, hand-edited files, older saves) opens in advanced mode
// so guided regeneration cannot silently discard hand-tuned colors. A
@@ -320,18 +314,6 @@ export function ThemeEditorPanel({
// an explanation instead.
const mergeTargetId = mergeTarget?.id ?? null;
const takenAppearancesKey = takenAppearances.join(",");
useEffect(() => {
if (previousMergeTargetIdRef.current === mergeTargetId) return;
previousMergeTargetIdRef.current = mergeTargetId;
// A matching name makes that existing theme the surviving merge target.
// Seed theme-level options from it so adding a palette or renaming onto it
// does not silently reset them. Leaving the merge restores the edited
// theme's option (or the off-by-default choice for a new theme).
setSidebarArtwork(
mergeTarget ? mergeTarget.sidebarArtwork === true : editingTheme?.sidebarArtwork === true,
);
}, [editingTheme, mergeTarget, mergeTargetId]);
useEffect(() => {
if (isEditing || mergeTargetId === null) return;
const taken = takenAppearancesKey.split(",").filter(Boolean) as ThemeAppearance[];
@@ -347,8 +329,8 @@ export function ThemeEditorPanel({
// comes back when the editor closes, including on cancel.
useEffect(() => {
if (!open || !isDraftSeeded) return;
applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance, sidebarArtwork);
}, [activeAppearance, colorsByAppearance, isDraftSeeded, open, sidebarArtwork]);
applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance);
}, [activeAppearance, colorsByAppearance, isDraftSeeded, open]);
useEffect(() => {
if (!open) return;
@@ -628,7 +610,7 @@ export function ThemeEditorPanel({
[activeAppearance, editingTheme, selectedRole],
);
const handleSubmit = useCallback(() => {
const handleSubmit = () => {
if (!name.trim()) {
setError("Name your theme first.");
return;
@@ -663,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,
@@ -674,10 +656,10 @@ export function ThemeEditorPanel({
...mergeTarget.variants,
...Object.fromEntries(editedModes.map((mode) => [mode, colorsForSave[mode]])),
},
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
}),
);
...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
});
retiredTheme = editingTheme;
try {
removeCustomTheme(editingTheme.id);
@@ -695,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,
@@ -705,10 +687,10 @@ export function ThemeEditorPanel({
...(getThemeModes(editingTheme).length > 1
? { variants: { [variantAppearance]: colorsForSave[variantAppearance] } }
: {}),
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(isAdvanced ? {} : { managed: true }),
}),
);
...(editingTheme.collection ? { collection: editingTheme.collection } : {}),
});
} else if (mergeTarget) {
if (takenAppearances.includes(activeAppearance)) {
setError(
@@ -721,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,
@@ -732,10 +714,10 @@ export function ThemeEditorPanel({
...mergeTarget.variants,
[activeAppearance]: colorsForSave[activeAppearance],
},
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(mergeTarget.managed === true && !isAdvanced ? { managed: true } : {}),
}),
);
...(mergeTarget.collection ? { collection: mergeTarget.collection } : {}),
});
} else {
savedTheme = installCustomTheme(
parseThemeFile({
@@ -743,7 +725,6 @@ export function ThemeEditorPanel({
name,
appearance: activeAppearance,
colors: colorsForSave[activeAppearance],
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
...(isAdvanced ? {} : { managed: true }),
}),
);
@@ -784,20 +765,7 @@ export function ThemeEditorPanel({
: "Could not create the theme.",
);
}
}, [
activeAppearance,
colorsByAppearance,
editingTheme,
isAdvanced,
isEditing,
mergeTarget,
name,
onOpenChange,
onSaved,
sidebarArtwork,
simpleColorsDirtyByAppearance,
takenAppearances,
]);
};
const renderNameField = () => (
<label className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
@@ -854,20 +822,6 @@ export function ThemeEditorPanel({
</div>
);
const renderSidebarArtworkToggle = () => (
<label className="grid cursor-pointer grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-center gap-3">
<span className="text-sm font-medium">Sidebar artwork</span>
<span className="flex items-center justify-between gap-3 text-xs text-muted-foreground">
<span>Show T3 Code environment artwork</span>
<Switch
aria-label="Allow sidebar artwork with this theme"
checked={sidebarArtwork}
onCheckedChange={(checked) => setSidebarArtwork(Boolean(checked))}
/>
</span>
</label>
);
const renderColorsHeader = () => (
<div className="grid grid-cols-[minmax(0,1fr)_minmax(0,2fr)] items-start gap-3">
<div>
@@ -1124,7 +1078,6 @@ export function ThemeEditorPanel({
</p>
) : null}
{renderAppearanceButtons()}
{renderSidebarArtworkToggle()}
<div className="space-y-3">
{renderColorsHeader()}
{renderColorFields()}
@@ -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";
@@ -8,6 +13,7 @@ import { usePrimaryEnvironment } from "../../state/environments";
import {
resolveEnvironmentIdentificationPillLabel,
resolveSidebarStageBackdropVariant,
resolveSidebarStageFocusRingOffsetClass,
SidebarStageBackdrop,
useEnvironmentStageLabel,
} from "../SidebarStageBackdrop";
@@ -21,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,
@@ -52,7 +59,8 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({
className={cn(
"relative z-10 md:hidden",
backdropVariant &&
"[:hover,[data-pressed]]:bg-white/15 focus-visible:ring-white/90 focus-visible:ring-offset-blue-700 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white!",
"focus-visible:ring-white/90 [&_svg]:stroke-white/90! [&_svg]:opacity-100! [&_svg]:hover:stroke-white! [:hover,[data-pressed]]:bg-white/15",
backdropVariant && resolveSidebarStageFocusRingOffsetClass(backdropVariant),
)}
/>
<SidebarBrand onBackdrop={backdropVariant !== null} />
@@ -112,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;
@@ -136,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}
+8 -25
View File
@@ -31,6 +31,7 @@ import {
getThemePreviewSidebarArtwork,
resolveThemeHalf,
subscribeToThemePreview,
themeAllowsSidebarArtwork,
} from "~/themePalette";
import * as Struct from "effect/Struct";
import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
@@ -236,17 +237,16 @@ export function resolveEnvironmentIdentificationMode(input: {
}): EnvironmentIdentificationMode {
// Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
if (!input.settingsHydrated) return "none";
// Stage artwork has fixed colors that can clash with palette themes. Keep an
// explicit "none", but use the theme-aware pill in place of artwork.
// Artwork palettes are maintained for built-ins only. Keep an explicit
// "none", but use the theme-aware pill for user-controlled palettes.
return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
? "pill"
: input.mode;
}
function useEnvironmentIdentificationThemeState(): {
paletteThemeActive: boolean;
paletteThemeAllowsArtwork: boolean;
} {
export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
const settingsHydrated = useClientSettingsHydrated();
const mode = useClientSettingsValue().environmentIdentificationMode;
const { resolvedTheme, theme, themeHalves } = useTheme();
const previewSidebarArtwork = useSyncExternalStore(
subscribeToThemePreview,
@@ -255,31 +255,14 @@ function useEnvironmentIdentificationThemeState(): {
);
const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
const activeThemeDefinition = getThemeDefinition(activeTheme);
return {
paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
paletteThemeAllowsArtwork:
previewSidebarArtwork ?? activeThemeDefinition?.sidebarArtwork === true,
};
}
export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
const settingsHydrated = useClientSettingsHydrated();
const mode = useClientSettingsValue().environmentIdentificationMode;
return resolveEnvironmentIdentificationMode({
mode,
settingsHydrated,
...useEnvironmentIdentificationThemeState(),
paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
paletteThemeAllowsArtwork: previewSidebarArtwork ?? themeAllowsSidebarArtwork(activeTheme),
});
}
/** Whether fixed-color artwork is safe to use outside the theme-aware sidebar. */
export function useDefaultEnvironmentArtworkEnabled(): boolean {
const settingsHydrated = useClientSettingsHydrated();
const mode = useClientSettingsValue().environmentIdentificationMode;
const { paletteThemeActive } = useEnvironmentIdentificationThemeState();
return settingsHydrated && mode === "artwork" && !paletteThemeActive;
}
/**
* Whether the legacy sidebar (Settings → General → Legacy features) replaces
* the default one.
+175 -12
View File
@@ -265,6 +265,51 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
}
@layer base {
:root {
/* Dev artwork defaults. Built-in themes override these seven pigments in
the components layer; Nightly derives a darker matching palette. */
--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,
var(--stage-art-secondary) 55%,
var(--stage-night-mid)
);
--stage-night-tertiary: color-mix(
in oklch,
var(--stage-art-tertiary) 60%,
var(--stage-night-top)
);
--stage-night-line: color-mix(in oklch, var(--stage-art-line) 82%, oklch(1 0 0));
}
.dark {
--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);
}
* {
@apply border-border outline-ring/50;
}
@@ -295,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) {
@@ -335,16 +378,136 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
);
}
.stage-blueprint {
--stage-bp-top: #67c2ff;
--stage-bp-mid: #347ff8;
--stage-bp-bottom: #1538d0;
/* Each maintainer palette gives the same line art its own material: rose
vellum, forest drafting paper, marine cyanotype, copper, and violet ink.
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: 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);
}
.dark .stage-blueprint {
--stage-bp-top: #3a7ad1;
--stage-bp-mid: #2050ae;
--stage-bp-bottom: #101f6e;
html.dark[data-theme-id="t3-chat"] {
--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: 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: 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: 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: 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: 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: 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: 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: 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 {
+7 -2
View File
@@ -16,6 +16,7 @@ import {
syncDocumentWindowControlsOverlayClass,
} from "./lib/windowControlsOverlay";
import { AppRoot } from "./AppRoot";
import { clerkAppearance } from "./components/clerk/clerkAppearance";
// Electron loads the app from a file-backed shell, so hash history avoids path resolution issues.
const history = isElectron ? createHashHistory() : createBrowserHistory();
@@ -35,11 +36,15 @@ ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
{clerkPublishableKey && hasCloudPublicConfig() ? (
isElectron ? (
<ElectronClerkProvider publishableKey={clerkPublishableKey} passkeys={passkeys}>
<ElectronClerkProvider
appearance={clerkAppearance}
publishableKey={clerkPublishableKey}
passkeys={passkeys}
>
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
</ElectronClerkProvider>
) : (
<ClerkProvider publishableKey={clerkPublishableKey}>
<ClerkProvider appearance={clerkAppearance} publishableKey={clerkPublishableKey}>
<ManagedRelayAuthProvider>{app}</ManagedRelayAuthProvider>
</ClerkProvider>
)
+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 }));
}
@@ -0,0 +1,20 @@
// @effect-diagnostics nodeBuiltinImport:off - Regression coverage compares the onboarding header with the shared titlebar contract.
import * as NodeFS from "node:fs";
import { describe, expect, it } from "vite-plus/test";
describe("hosted static onboarding header", () => {
it("uses the shared workspace topbar geometry", () => {
const routeSource = NodeFS.readFileSync(new URL("./_chat.index.tsx", import.meta.url), "utf8");
const onboardingStart = routeSource.indexOf("function HostedStaticOnboardingState()");
const onboardingEnd = routeSource.indexOf('<Empty className="flex-1">', onboardingStart);
expect(onboardingStart).toBeGreaterThanOrEqual(0);
expect(onboardingEnd).toBeGreaterThan(onboardingStart);
const onboardingHeader = routeSource.slice(onboardingStart, onboardingEnd);
expect(onboardingHeader).toContain("workspace-topbar");
expect(onboardingHeader).not.toMatch(/(?:^|\s)(?:[\w-]+:)*py-/);
});
});
+1 -1
View File
@@ -145,7 +145,7 @@ function HostedStaticOnboardingState() {
<div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden bg-background">
<header
className={cn(
"border-b border-border px-3 py-2 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5 sm:py-3",
"workspace-topbar border-b border-border px-3 transition-[padding-left] duration-200 ease-linear motion-reduce:transition-none sm:px-5",
COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS,
)}
>
+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);
});
+544 -61
View File
@@ -10,16 +10,21 @@ import {
getThemePreferenceMode,
isKnownThemePreference,
getCustomThemes,
getStoredCustomThemeCollection,
invalidateCustomThemes,
installCustomTheme,
canonicalThemePreference,
parseThemeFile,
parseThemeHalves,
removeCustomTheme,
removeCustomThemes,
replaceCustomThemeCollection,
resolveDesktopTheme,
resolveThemeAppearance,
serializeThemeFile,
subscribeToThemePreview,
subscribeToCustomThemes,
themeAllowsSidebarArtwork,
T3_CHAT_THEME,
EMBER_THEME,
GROVE_THEME,
@@ -30,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,
);
@@ -55,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);
@@ -72,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,
@@ -91,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", () => {
@@ -107,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);
@@ -130,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);
}
});
@@ -169,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({
@@ -193,27 +263,47 @@ 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("keeps sidebar artwork opt-in through theme files", () => {
const withoutArtwork = parseThemeFile({
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,
name: "Plain sidebar",
appearance: "light",
colors: { accent: "#5b6cff" },
id: theme.id,
name: theme.label,
appearance: "dark",
collection: theme.collection,
});
const withArtwork = parseThemeFile({
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,
name: "Art sidebar",
appearance: "light",
@@ -221,12 +311,11 @@ describe("theme files", () => {
sidebarArtwork: true,
});
expect(withoutArtwork.sidebarArtwork).toBeUndefined();
expect(withArtwork.sidebarArtwork).toBe(true);
expect(JSON.parse(serializeThemeFile(withArtwork)).sidebarArtwork).toBe(true);
expect(theme.sidebarArtwork).toBeUndefined();
expect(JSON.parse(serializeThemeFile(theme))).not.toHaveProperty("sidebarArtwork");
});
it("publishes sidebar artwork changes from the live theme preview", () => {
it("suppresses sidebar artwork during a live custom-theme preview", () => {
const listener = vi.fn();
const unsubscribe = subscribeToThemePreview(listener);
vi.stubGlobal("document", {
@@ -237,8 +326,8 @@ describe("theme files", () => {
},
});
applyThemeColorPreview(T3_CHAT_THEME.colors, "light", true);
expect(getThemePreviewSidebarArtwork()).toBe(true);
applyThemeColorPreview(T3_CHAT_THEME.colors, "light");
expect(getThemePreviewSidebarArtwork()).toBe(false);
expect(listener).toHaveBeenCalledTimes(1);
applyThemePalette("system");
@@ -263,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");
@@ -272,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",
@@ -293,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",
@@ -325,8 +414,10 @@ describe("theme files", () => {
for (const theme of [T3_CHAT_THEME, GROVE_THEME, OCEAN_THEME, EMBER_THEME, IRIS_THEME]) {
expect(getThemeDefinition(theme.id)).toBe(theme);
expect(getThemeModes(theme)).toEqual(["light", "dark"]);
expect(theme.colors.accent).toMatch(/^#[0-9a-f]{6}$/i);
expect(theme.variants?.dark?.accent).toMatch(/^#[0-9a-f]{6}$/i);
expect(theme.sidebarArtwork).toBe(true);
expect(themeAllowsSidebarArtwork(theme.id)).toBe(true);
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);
@@ -359,6 +450,7 @@ describe("theme files", () => {
);
}
}
expect(themeAllowsSidebarArtwork("my-custom-theme")).toBe(false);
});
it("rejects a variant that repeats the base appearance", () => {
@@ -383,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();
});
@@ -422,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,
@@ -445,21 +719,225 @@ 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",
sidebarArtwork: true,
colors: { accent: canonical("hsl(263 70% 58%)") },
});
invalidateCustomThemes();
expect(getCustomThemes()).toEqual([updatedTheme]);
expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toMatchObject({
expect(updatedTheme).not.toHaveProperty("sidebarArtwork");
const storedThemes = JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]");
expect(storedThemes[0]).toEqual(untouchedTheme);
expect(storedThemes[1]).toMatchObject({
id: "aurora",
label: "Aurora Night",
sidebarArtwork: true,
colors: { accent: canonical("hsl(263 70% 58%)") },
});
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();
@@ -531,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();
@@ -556,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,
+11 -3
View File
@@ -90,9 +90,17 @@ In **Clerk Dashboard > OAuth applications**:
5. Set `T3CODE_CLERK_CLI_OAUTH_CLIENT_ID` in the repository-root `.env` file and release build
environment to the generated public client ID.
The CLI derives Clerk's frontend API URL from the publishable key and calls Clerk's
`/oauth/authorize` and `/oauth/token` endpoints directly. The relay is not involved in the OAuth
handshake; it only validates the issued Clerk bearer token when the CLI manages an environment link.
Both CLI flows start at the hosted `/connect` page (`buildConnectAuthorizeRequestUrl` in
`packages/shared/src/connectAuth.ts`), which waits for a Clerk session and then forwards the request
to Clerk's `/oauth/authorize`. The CLI never opens `/oauth/authorize` directly: a signed-out browser
sent there goes through Clerk's sign-in redirect, which drops the authorize query parameters and
fails the flow with `unsupported_response_type` or an empty `state` (#5051). The loopback flow marks
the request with a `port` fragment parameter so the hosted page asks Clerk to redirect the
authorization code straight to `http://127.0.0.1:<port>/callback`; the out-of-band flow omits it and
uses the hosted `/connect/callback` page instead. The CLI derives Clerk's frontend API URL from the
publishable key and calls only the `/oauth/token` endpoint directly. The relay is not involved in
the OAuth handshake; it only validates the issued Clerk bearer token when the CLI manages an
environment link.
The connect command group is:
+11
View File
@@ -11,3 +11,14 @@ other connected devices.
If reordering is unavailable for one environment, update the T3 Code server running in that
environment. Older servers can still pin and unpin threads, but do not understand synced ordering;
their pinned threads keep the default newest-first order below the ones you have arranged.
## Environment artwork
Dev and Nightly environments can identify themselves with artwork at the top of the sidebar and in
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.
+26
View File
@@ -4,6 +4,7 @@ import {
buildConnectAuthorizeRequestUrl,
buildConnectClerkAuthorizeUrl,
connectCallbackUrl,
connectLoopbackRedirectUri,
encodeConnectAuthCode,
parseConnectAuthCode,
readConnectAuthorizeRequest,
@@ -37,6 +38,31 @@ describe("connectAuth", () => {
).toBeNull();
});
it("round-trips the loopback port through the authorize URL fragment", () => {
const url = buildConnectAuthorizeRequestUrl({
hostedAppUrl: "https://app.t3.codes",
state: "state-1",
challenge: "challenge-1",
loopbackPort: 34338,
});
expect(readConnectAuthorizeRequest(new URL(url))).toEqual({
state: "state-1",
challenge: "challenge-1",
loopbackPort: 34338,
});
expect(connectLoopbackRedirectUri(34338)).toBe("http://127.0.0.1:34338/callback");
});
it("rejects authorize requests whose loopback port is corrupted", () => {
for (const port of ["", "abc", "-1", "0", "65536", "34338x", "34 38"]) {
const url = new URL(
`https://app.t3.codes/connect#state=state-1&challenge=challenge-1&port=${encodeURIComponent(port)}`,
);
expect(readConnectAuthorizeRequest(url), port).toBeNull();
}
});
it("builds a PKCE authorize URL against the Clerk endpoint", () => {
const url = new URL(
buildConnectClerkAuthorizeUrl({
+50 -4
View File
@@ -2,7 +2,9 @@ import { readHashParams } from "./remote.ts";
const CONNECT_AUTH_STATE_PARAM = "state";
const CONNECT_AUTH_CHALLENGE_PARAM = "challenge";
const CONNECT_AUTH_PORT_PARAM = "port";
const CONNECT_AUTH_CODE_SEPARATOR = ".";
const CONNECT_LOOPBACK_CALLBACK_PATH = "/callback";
const CONNECT_AUTHORIZE_PATH = "/connect";
const CONNECT_CALLBACK_PATH = "/connect/callback";
@@ -23,22 +25,39 @@ export const CONNECT_OAUTH_SCOPES = ["openid", "profile", "email"] as const;
export interface ConnectAuthorizeRequest {
readonly state: string;
readonly challenge: string;
/**
* Present when a loopback CLI initiated the request: the hosted /connect
* page then asks Clerk to redirect the authorization code straight to
* `http://127.0.0.1:<port>/callback` instead of the hosted callback page.
*/
readonly loopbackPort?: number;
}
/**
* The URL a headless CLI prints for the user to open on a machine with a
* browser. `state` and `code_challenge` ride the fragment so they never reach
* the hosted app's server or CDN logs; neither is a secret.
* The URL the CLI prints for the user to open in a browser. `state` and
* `code_challenge` ride the fragment so they never reach the hosted app's
* server or CDN logs; neither is a secret.
*
* Both CLI flows route through the hosted /connect page rather than hitting
* Clerk's /oauth/authorize directly: a signed-out browser sent straight to
* /oauth/authorize goes through Clerk's sign-in redirect, which does not
* reliably preserve the authorize query parameters (state, response_type,
* code_challenge). The hosted page waits for a Clerk session first, then
* forwards the request with the parameters intact.
*/
export function buildConnectAuthorizeRequestUrl(input: {
readonly hostedAppUrl: string;
readonly state: string;
readonly challenge: string;
readonly loopbackPort?: number;
}): string {
const url = new URL(CONNECT_AUTHORIZE_PATH, input.hostedAppUrl);
url.hash = new URLSearchParams([
[CONNECT_AUTH_STATE_PARAM, input.state],
[CONNECT_AUTH_CHALLENGE_PARAM, input.challenge],
...(input.loopbackPort === undefined
? []
: [[CONNECT_AUTH_PORT_PARAM, String(input.loopbackPort)] as [string, string]]),
]).toString();
return url.toString();
}
@@ -50,7 +69,34 @@ export function readConnectAuthorizeRequest(url: URL): ConnectAuthorizeRequest |
if (!state || !challenge) {
return null;
}
return { state, challenge };
const port = params.get(CONNECT_AUTH_PORT_PARAM);
if (port === null) {
return { state, challenge };
}
// A present-but-invalid port means the link was corrupted; reject the whole
// request rather than silently downgrading a loopback flow to the
// out-of-band one, which would strand the waiting CLI.
const loopbackPort = parseLoopbackPort(port.trim());
if (loopbackPort === null) {
return null;
}
return { state, challenge, loopbackPort };
}
function parseLoopbackPort(value: string): number | null {
if (!/^\d{1,5}$/.test(value)) {
return null;
}
const port = Number(value);
return port >= 1 && port <= 65535 ? port : null;
}
/**
* Redirect URI for the CLI's local callback listener. Must stay in sync with
* the redirect URI registered on the Clerk CLI OAuth application.
*/
export function connectLoopbackRedirectUri(port: number): string {
return `http://127.0.0.1:${port}${CONNECT_LOOPBACK_CALLBACK_PATH}`;
}
export function connectCallbackUrl(hostedAppUrl: string): string {
+12
View File
@@ -4,6 +4,8 @@ import {
isUncPath,
isWindowsAbsolutePath,
isWindowsDrivePath,
normalizeProjectPathForComparison,
normalizeProjectPathForDispatch,
} from "./path.ts";
describe("path helpers", () => {
@@ -31,4 +33,14 @@ describe("path helpers", () => {
expect(isExplicitRelativePath("..\\repo")).toBe(true);
expect(isExplicitRelativePath("~/repo")).toBe(false);
});
it("normalizes a bare Windows drive root the same as one with a trailing separator", () => {
// `C:`, `C:\` and `C:/` all refer to the drive root and must compare equal.
expect(normalizeProjectPathForDispatch("C:")).toBe("C:\\");
expect(normalizeProjectPathForComparison("C:")).toBe("c:\\");
expect(normalizeProjectPathForComparison("C:")).toBe(normalizeProjectPathForComparison("C:\\"));
expect(normalizeProjectPathForComparison("C:")).toBe(normalizeProjectPathForComparison("C:/"));
// Non-root drive paths keep their trailing separator trimmed as before.
expect(normalizeProjectPathForDispatch("C:\\repo\\")).toBe("C:\\repo");
});
});
+5 -1
View File
@@ -22,7 +22,11 @@ export function isExplicitRelativePath(value: string): boolean {
}
function isRootPath(value: string): boolean {
return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]?$/.test(value);
// The drive separator is required: a bare `C:` is not the drive root (it
// means "current directory on C:"), and treating it as already-canonical
// would leave it as `C:` while `C:\` and `C:/` normalize to the drive root,
// so the same location would fail project identity/dedup comparisons.
return value === "/" || value === "\\" || /^[a-zA-Z]:[/\\]$/.test(value);
}
function trimTrailingPathSeparators(value: string): string {
+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