Compare commits
22
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee0d31d5e6 | ||
|
|
dd8a0db88b | ||
|
|
62d130714d | ||
|
|
af4383e893 | ||
|
|
a33718663d | ||
|
|
59e1bd230c | ||
|
|
bd9e3f953d | ||
|
|
7bcd756fc5 | ||
|
|
4b78960aff | ||
|
|
784493f144 | ||
|
|
d11283bac6 | ||
|
|
8779f184bb | ||
|
|
4e5bafcff7 | ||
|
|
64490d4c65 | ||
|
|
d1d74f1397 | ||
|
|
31891a1a0c | ||
|
|
45d9aa90ba | ||
|
|
7a84f6cf10 | ||
|
|
f0fb406acf | ||
|
|
82406bce99 | ||
|
|
72d673a855 | ||
|
|
e2cd2383ce |
No files matched your search
@@ -11,6 +11,7 @@
|
||||
# Keep entries sorted alphabetically.
|
||||
github:adityavardhansharma
|
||||
github:binbandit
|
||||
github:chrisdeeming
|
||||
github:chuks-qua
|
||||
github:cursoragent
|
||||
github:gbarros-dev
|
||||
@@ -26,6 +27,7 @@ github:notkainoa
|
||||
github:PatrickBauer
|
||||
github:realAhmedRoach
|
||||
github:shiroyasha9
|
||||
github:StiensWout
|
||||
github:Yash-Singh1
|
||||
github:eggfriedrice24
|
||||
github:Ymit24
|
||||
|
||||
@@ -2199,7 +2199,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
it("starts a new streaming assistant message segment after approval", async () => {
|
||||
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||
const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } });
|
||||
const startedAt = "2026-03-28T07:00:00.000Z";
|
||||
const pausedAt = "2026-03-28T07:00:01.000Z";
|
||||
const resumedAt = "2026-03-28T07:00:02.000Z";
|
||||
@@ -2306,7 +2306,7 @@ describe("ProviderRuntimeIngestion", () => {
|
||||
});
|
||||
|
||||
it("streams assistant deltas when thread.turn.start requests streaming mode", async () => {
|
||||
const harness = await createHarness({ serverSettings: { enableAssistantStreaming: true } });
|
||||
const harness = await createHarness({ serverSettings: { enableLegacyTokenStreaming: true } });
|
||||
const now = "2026-01-01T00:00:00.000Z";
|
||||
|
||||
await Effect.runPromise(
|
||||
|
||||
@@ -1655,7 +1655,7 @@ const make = Effect.gen(function* () {
|
||||
|
||||
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
|
||||
(settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"),
|
||||
);
|
||||
if (assistantDeliveryMode === "buffered") {
|
||||
const spillChunk = yield* appendBufferedAssistantText(assistantMessageId, assistantDelta);
|
||||
@@ -1691,7 +1691,7 @@ const make = Effect.gen(function* () {
|
||||
const detailedThread = yield* getLoadedThreadDetail();
|
||||
const assistantDeliveryMode: AssistantDeliveryMode = yield* Effect.map(
|
||||
serverSettingsService.getSettings,
|
||||
(settings) => (settings.enableAssistantStreaming ? "streaming" : "buffered"),
|
||||
(settings) => (settings.enableLegacyTokenStreaming ? "streaming" : "buffered"),
|
||||
);
|
||||
const flushedMessageIds =
|
||||
assistantDeliveryMode === "buffered"
|
||||
|
||||
@@ -34,36 +34,6 @@ const [CHILD_A, CHILD_B] = wireFixture.childThreadIds as [string, string];
|
||||
*/
|
||||
function buildScript() {
|
||||
const captured = wireFixture.notifications;
|
||||
// Re-address the capture's schema-valid tool lifecycle pair to child A.
|
||||
// Hand-written item shapes can drift from the generated Codex schema.
|
||||
const childToolLifecycle = captured
|
||||
.filter(
|
||||
(entry) =>
|
||||
(entry.method === "item/started" || entry.method === "item/completed") &&
|
||||
(entry.params as { item?: { type?: string } }).item?.type === "collabAgentToolCall",
|
||||
)
|
||||
.map((entry) => {
|
||||
const params = entry.params as {
|
||||
readonly threadId: string;
|
||||
readonly turnId: string;
|
||||
readonly item: Record<string, unknown>;
|
||||
};
|
||||
return {
|
||||
...entry,
|
||||
params: {
|
||||
...params,
|
||||
threadId: CHILD_A,
|
||||
turnId: `${CHILD_A}-turn-1`,
|
||||
item: {
|
||||
...params.item,
|
||||
id: "call_fixture_child_tool",
|
||||
senderThreadId: CHILD_A,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
const childCompletionOnly = childToolLifecycle.find((entry) => entry.method === "item/completed");
|
||||
assert.isDefined(childCompletionOnly);
|
||||
const extras = [
|
||||
{
|
||||
method: "item/completed",
|
||||
@@ -79,19 +49,6 @@ function buildScript() {
|
||||
},
|
||||
},
|
||||
},
|
||||
// Codex emits started + completed for one child item. They are one
|
||||
// logical activity and must not become two synthetic agent updates.
|
||||
...childToolLifecycle,
|
||||
{
|
||||
...childCompletionOnly,
|
||||
params: {
|
||||
...childCompletionOnly.params,
|
||||
item: {
|
||||
...childCompletionOnly.params.item,
|
||||
id: "call_fixture_child_completion_only",
|
||||
},
|
||||
},
|
||||
},
|
||||
// Child terminal lifecycle AFTER the receiver map knows the children —
|
||||
// pre-fix, the legacy suppressor dropped these before interception saw
|
||||
// them, so no synthetic agent events were emitted.
|
||||
@@ -166,29 +123,6 @@ describe("CodexSessionRuntime collab integration", () => {
|
||||
);
|
||||
assert.isDefined(childClosed, "child B's close becomes an agent event");
|
||||
|
||||
const childToolItems = events.filter(
|
||||
(event) =>
|
||||
event.method === "collabAgent/item" &&
|
||||
(event.payload as { item?: { id?: string } }).item?.id === "call_fixture_child_tool",
|
||||
);
|
||||
assert.lengthOf(childToolItems, 1, "one child item must emit one agent activity");
|
||||
assert.equal(childToolItems[0]?.itemId, "call_fixture_child_tool");
|
||||
assert.equal(
|
||||
(childToolItems[0]?.payload as { itemLifecycle?: string }).itemLifecycle,
|
||||
"started",
|
||||
);
|
||||
|
||||
const completionOnly = events.find(
|
||||
(event) =>
|
||||
event.method === "collabAgent/item" &&
|
||||
(event.payload as { item?: { id?: string } }).item?.id ===
|
||||
"call_fixture_child_completion_only",
|
||||
);
|
||||
assert.equal(
|
||||
(completionOnly?.payload as { itemLifecycle?: string }).itemLifecycle,
|
||||
"completed",
|
||||
);
|
||||
|
||||
// Parent-owned resolution passes through — not swallowed, not
|
||||
// re-labelled as an agent event.
|
||||
assert.include(methods, "serverRequest/resolved");
|
||||
|
||||
@@ -855,8 +855,6 @@ export const makeCodexSessionRuntime = (
|
||||
const pendingUserInputsRef = yield* Ref.make(new Map<ApprovalRequestId, PendingUserInput>());
|
||||
const collabReceiverTurnsRef = yield* Ref.make(new Map<string, TurnId>());
|
||||
const collabChildAgentsRef = yield* Ref.make(new Map<string, CollabChildAgentState>());
|
||||
/** Child provider-thread id → item ids already emitted during its lifetime. */
|
||||
const collabChildSeenItemsRef = yield* Ref.make(new Map<string, ReadonlySet<string>>());
|
||||
/** Child provider-thread id → its currently running provider turn id. */
|
||||
const collabChildLiveTurnsRef = yield* Ref.make(new Map<string, string>());
|
||||
const closedRef = yield* Ref.make(false);
|
||||
@@ -1181,38 +1179,18 @@ export const makeCodexSessionRuntime = (
|
||||
});
|
||||
return true;
|
||||
case "item/started":
|
||||
case "item/completed": {
|
||||
const item = notification.params.item;
|
||||
const shouldEmit = yield* Ref.modify(collabChildSeenItemsRef, (current) => {
|
||||
const seen = current.get(child.agentThreadId);
|
||||
if (seen?.has(item.id) === true) {
|
||||
return [false, current];
|
||||
}
|
||||
const next = new Map(current);
|
||||
next.set(child.agentThreadId, new Set([...(seen ?? []), item.id]));
|
||||
return [true, next];
|
||||
});
|
||||
// Codex emits both lifecycle notifications for the same child
|
||||
// tool item. The adapter turns each synthetic event into agent
|
||||
// activity, so only the first one is useful; completion-only
|
||||
// items still pass through when no start was observed.
|
||||
if (!shouldEmit) {
|
||||
return true;
|
||||
}
|
||||
case "item/completed":
|
||||
yield* emitEvent({
|
||||
kind: "notification",
|
||||
threadId: options.threadId,
|
||||
itemId: ProviderItemId.make(item.id),
|
||||
...(child.spawnTurnId ? { turnId: child.spawnTurnId } : {}),
|
||||
method: "collabAgent/item",
|
||||
payload: {
|
||||
...childIdentity,
|
||||
itemLifecycle: notification.method === "item/started" ? "started" : "completed",
|
||||
item,
|
||||
item: notification.params.item,
|
||||
},
|
||||
});
|
||||
return true;
|
||||
}
|
||||
case "thread/closed":
|
||||
// The child is gone: drop its live-turn entry so a later Stop
|
||||
// doesn't waste a turn/interrupt RPC on a closed thread before
|
||||
@@ -1222,11 +1200,6 @@ export const makeCodexSessionRuntime = (
|
||||
next.delete(child.agentThreadId);
|
||||
return next;
|
||||
});
|
||||
yield* Ref.update(collabChildSeenItemsRef, (current) => {
|
||||
const next = new Map(current);
|
||||
next.delete(child.agentThreadId);
|
||||
return next;
|
||||
});
|
||||
yield* emitEvent({
|
||||
kind: "notification",
|
||||
threadId: options.threadId,
|
||||
|
||||
@@ -23,6 +23,7 @@
|
||||
"@formkit/auto-animate": "^0.9.0",
|
||||
"@legendapp/list": "3.3.3",
|
||||
"@lexical/react": "^0.41.0",
|
||||
"@noble/hashes": "catalog:",
|
||||
"@pierre/diffs": "catalog:",
|
||||
"@pierre/trees": "1.0.0-beta.4",
|
||||
"@t3tools/client-runtime": "workspace:*",
|
||||
@@ -33,6 +34,8 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"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",
|
||||
|
||||
@@ -7,7 +7,8 @@ import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
|
||||
import { readPreparedConnection } from "~/state/session";
|
||||
|
||||
const normalizeHostname = (host: string): string => host.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
export const normalizeHostname = (host: string): string =>
|
||||
host.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
|
||||
const parseIpv4Address = (host: string): readonly number[] | null => {
|
||||
const parts = normalizeHostname(host).split(".").map(Number);
|
||||
@@ -17,7 +18,7 @@ const parseIpv4Address = (host: string): readonly number[] | null => {
|
||||
: null;
|
||||
};
|
||||
|
||||
const isLocalLoopbackHost = (host: string): boolean => {
|
||||
export const isLocalLoopbackHost = (host: string): boolean => {
|
||||
const normalized = normalizeHostname(host);
|
||||
if (normalized === "localhost" || normalized === "::1") return true;
|
||||
return parseIpv4Address(normalized)?.[0] === 127;
|
||||
|
||||
@@ -0,0 +1,444 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
|
||||
|
||||
const { readPreparedConnection } = vi.hoisted(() => ({
|
||||
readPreparedConnection: vi.fn<() => { httpBaseUrl: string } | null>(() => null),
|
||||
}));
|
||||
|
||||
vi.mock("~/state/session", () => ({ readPreparedConnection }));
|
||||
|
||||
import {
|
||||
BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
|
||||
BROWSER_HISTORY_MAX_PROJECTS,
|
||||
BROWSER_HISTORY_MAX_TITLE_LENGTH,
|
||||
type BrowserHistoryEntry,
|
||||
evictExcessProjects,
|
||||
mergeBrowserHistoryState,
|
||||
migratePersistedBrowserHistoryState,
|
||||
normalizeHistoryUrl,
|
||||
recordVisitForThread,
|
||||
removeUrlForThread,
|
||||
resetBrowserHistoryForTests,
|
||||
setTitleForThreadUrl,
|
||||
upsertHistoryEntry,
|
||||
useBrowserHistoryStore,
|
||||
} from "./browserHistoryStore";
|
||||
|
||||
function entry(overrides: Partial<BrowserHistoryEntry> = {}): BrowserHistoryEntry {
|
||||
return { url: "http://localhost:3000/", lastVisitedAt: 1000, ...overrides };
|
||||
}
|
||||
|
||||
beforeEach(() => readPreparedConnection.mockReturnValue(null));
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
function spyOnPersistWrites() {
|
||||
const storage = useBrowserHistoryStore.persist.getOptions().storage;
|
||||
if (!storage) throw new Error("Browser history persistence storage is unavailable.");
|
||||
return vi.spyOn(storage, "setItem");
|
||||
}
|
||||
|
||||
describe("normalizeHistoryUrl", () => {
|
||||
it("normalizes bare loopback hosts to http and keeps path/query", () => {
|
||||
expect(normalizeHistoryUrl("localhost:3000/admin?tab=1")).toBe(
|
||||
"http://localhost:3000/admin?tab=1",
|
||||
);
|
||||
});
|
||||
|
||||
it("normalizes bare public hosts to https", () => {
|
||||
expect(normalizeHistoryUrl("myapp.test")).toBe("https://myapp.test/");
|
||||
});
|
||||
|
||||
it("preserves hash routes and strips credentials", () => {
|
||||
expect(normalizeHistoryUrl("http://localhost:3000/app#/route")).toBe(
|
||||
"http://localhost:3000/app#/route",
|
||||
);
|
||||
expect(normalizeHistoryUrl("https://user:[email protected]/")).toBe("https://example.com/");
|
||||
});
|
||||
|
||||
it("rejects non-http(s), unparseable, and oversized urls", () => {
|
||||
expect(normalizeHistoryUrl("ftp://example.com")).toBeNull();
|
||||
expect(normalizeHistoryUrl("")).toBeNull();
|
||||
expect(normalizeHistoryUrl(`http://localhost/${"a".repeat(2048)}`)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("upsertHistoryEntry", () => {
|
||||
it("prepends new urls", () => {
|
||||
const next = upsertHistoryEntry([entry()], "http://localhost:5173/", 2000);
|
||||
expect(next.map((e) => e.url)).toEqual(["http://localhost:5173/", "http://localhost:3000/"]);
|
||||
expect(next[0]).toEqual({ url: "http://localhost:5173/", lastVisitedAt: 2000 });
|
||||
});
|
||||
|
||||
it("moves revisits to front, updates the timestamp, and keeps the title", () => {
|
||||
const existing = [
|
||||
entry({ url: "http://a.test/", lastVisitedAt: 500, title: "A" }),
|
||||
entry({ url: "http://b.test/", lastVisitedAt: 400 }),
|
||||
];
|
||||
const next = upsertHistoryEntry(existing, "http://b.test/", 3000);
|
||||
expect(next.map((e) => e.url)).toEqual(["http://b.test/", "http://a.test/"]);
|
||||
expect(next[0]?.lastVisitedAt).toBe(3000);
|
||||
expect(next[1]?.title).toBe("A");
|
||||
});
|
||||
|
||||
it("caps the list at the per-project limit", () => {
|
||||
const full = Array.from({ length: BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT }, (_, i) =>
|
||||
entry({ url: `http://localhost:${3000 + i}/`, lastVisitedAt: i }),
|
||||
);
|
||||
const next = upsertHistoryEntry(full, "http://new.test/", 9999);
|
||||
expect(next).toHaveLength(BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
|
||||
expect(next[0]?.url).toBe("http://new.test/");
|
||||
const lastPort = 3000 + BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT - 1;
|
||||
expect(next.some((e) => e.url === `http://localhost:${lastPort}/`)).toBe(false);
|
||||
expect(next.some((e) => e.url === "http://localhost:3000/")).toBe(true);
|
||||
});
|
||||
|
||||
it("with insertOrdered, slots an older entry below a newer one instead of prepending", () => {
|
||||
const existing = [entry({ url: "http://newer.test/", lastVisitedAt: 2000 })];
|
||||
const next = upsertHistoryEntry(existing, "http://older.test/", 1000, {
|
||||
insertOrdered: true,
|
||||
});
|
||||
expect(next.map((e) => e.url)).toEqual(["http://newer.test/", "http://older.test/"]);
|
||||
});
|
||||
|
||||
it("with insertOrdered, replaying an older visit for an existing entry keeps its newer timestamp", () => {
|
||||
const existing = [entry({ url: "http://a.test/", lastVisitedAt: 2000 })];
|
||||
const next = upsertHistoryEntry(existing, "http://a.test/", 1000, { insertOrdered: true });
|
||||
expect(next).toEqual([{ url: "http://a.test/", lastVisitedAt: 2000 }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("evictExcessProjects", () => {
|
||||
it("keeps the most recently visited projects when over the cap", () => {
|
||||
const byProjectKey = Object.fromEntries(
|
||||
Array.from({ length: BROWSER_HISTORY_MAX_PROJECTS + 2 }, (_, i) => [
|
||||
`project-${i}`,
|
||||
[entry({ lastVisitedAt: i })],
|
||||
]),
|
||||
);
|
||||
const next = evictExcessProjects(byProjectKey);
|
||||
expect(Object.keys(next)).toHaveLength(BROWSER_HISTORY_MAX_PROJECTS);
|
||||
expect(next["project-0"]).toBeUndefined();
|
||||
expect(next["project-1"]).toBeUndefined();
|
||||
expect(next[`project-${BROWSER_HISTORY_MAX_PROJECTS + 1}`]).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("migratePersistedBrowserHistoryState", () => {
|
||||
it("drops malformed state and invalid entries", () => {
|
||||
expect(migratePersistedBrowserHistoryState(null)).toEqual({ byProjectKey: {} });
|
||||
expect(migratePersistedBrowserHistoryState({ byProjectKey: 42 })).toEqual({ byProjectKey: {} });
|
||||
const migrated = migratePersistedBrowserHistoryState({
|
||||
byProjectKey: {
|
||||
good: [
|
||||
{ url: "http://a.test/", lastVisitedAt: 100, title: "A" },
|
||||
{ url: "", lastVisitedAt: 100 },
|
||||
{ url: "ftp://ghost.test/", lastVisitedAt: 100 },
|
||||
{ url: "http://b.test/", lastVisitedAt: Number.NaN },
|
||||
"junk",
|
||||
],
|
||||
bad: "junk",
|
||||
},
|
||||
});
|
||||
expect(migrated.byProjectKey["good"]).toEqual([
|
||||
{ url: "http://a.test/", lastVisitedAt: 100, title: "A" },
|
||||
]);
|
||||
expect(migrated.byProjectKey["bad"]).toBeUndefined();
|
||||
});
|
||||
|
||||
it("normalizes persisted urls with the same rules as live writes", () => {
|
||||
const migrated = migratePersistedBrowserHistoryState({
|
||||
byProjectKey: {
|
||||
good: [{ url: "a.test/path#section", lastVisitedAt: 100 }],
|
||||
},
|
||||
});
|
||||
expect(migrated.byProjectKey["good"]).toEqual([
|
||||
{ url: "https://a.test/path#section", lastVisitedAt: 100 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("restores MRU ordering, deduplicates normalized urls, and enforces project bounds", () => {
|
||||
const byProjectKey = Object.fromEntries(
|
||||
Array.from({ length: BROWSER_HISTORY_MAX_PROJECTS + 1 }, (_, index) => [
|
||||
`project-${index}`,
|
||||
[{ url: `http://project-${index}.test/`, lastVisitedAt: index }],
|
||||
]),
|
||||
);
|
||||
byProjectKey["project-1"] = [
|
||||
{ url: "a.test/", lastVisitedAt: 1 },
|
||||
{ url: "http://newer.test/", lastVisitedAt: 3 },
|
||||
{ url: "https://a.test/", lastVisitedAt: 2 },
|
||||
];
|
||||
|
||||
const migrated = migratePersistedBrowserHistoryState({ byProjectKey });
|
||||
|
||||
expect(Object.keys(migrated.byProjectKey)).toHaveLength(BROWSER_HISTORY_MAX_PROJECTS);
|
||||
expect(migrated.byProjectKey["project-0"]).toBeUndefined();
|
||||
expect(migrated.byProjectKey["project-1"]).toEqual([
|
||||
{ url: "http://newer.test/", lastVisitedAt: 3 },
|
||||
{ url: "https://a.test/", lastVisitedAt: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects a lastVisitedAt outside Date's valid range", () => {
|
||||
const migrated = migratePersistedBrowserHistoryState({
|
||||
byProjectKey: {
|
||||
good: [
|
||||
{ url: "http://a.test/", lastVisitedAt: 100 },
|
||||
{ url: "http://b.test/", lastVisitedAt: 1e20 },
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(migrated.byProjectKey["good"]).toEqual([{ url: "http://a.test/", lastVisitedAt: 100 }]);
|
||||
});
|
||||
|
||||
it("truncates oversized persisted titles to the contract bound", () => {
|
||||
const oversized = "x".repeat(BROWSER_HISTORY_MAX_TITLE_LENGTH + 100);
|
||||
const migrated = migratePersistedBrowserHistoryState({
|
||||
byProjectKey: {
|
||||
good: [{ url: "http://a.test/", lastVisitedAt: 100, title: oversized }],
|
||||
},
|
||||
});
|
||||
expect(migrated.byProjectKey["good"]?.[0]?.title).toHaveLength(
|
||||
BROWSER_HISTORY_MAX_TITLE_LENGTH,
|
||||
);
|
||||
expect(migrated.byProjectKey["good"]?.[0]?.title).toBe(
|
||||
oversized.slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const threadRef = {
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
};
|
||||
|
||||
describe("useBrowserHistoryStore", () => {
|
||||
beforeEach(() => {
|
||||
resetBrowserHistoryForTests();
|
||||
});
|
||||
|
||||
it("records visits for registered threads under the project key", () => {
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
recordVisitForThread(threadRef, "myapp.test/admin#section", 1234);
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]).toEqual([
|
||||
{ url: "https://myapp.test/admin#section", lastVisitedAt: 1234 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not persist when a thread is already registered to the same project", () => {
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
const persist = spyOnPersistWrites();
|
||||
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
|
||||
expect(persist).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("ignores invalid urls whether queued pending or recorded post-registration", () => {
|
||||
recordVisitForThread(threadRef, "ftp://a.test/", 1);
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
recordVisitForThread(threadRef, "ftp://a.test/", 2);
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
|
||||
});
|
||||
|
||||
it("sets titles update-only via the thread helper", () => {
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
setTitleForThreadUrl(threadRef, "http://a.test/", "Should not create");
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
|
||||
recordVisitForThread(threadRef, "http://a.test/#/settings", 1);
|
||||
setTitleForThreadUrl(threadRef, "http://a.test/#/settings", "My App");
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("My App");
|
||||
});
|
||||
|
||||
it("does not persist when the title is already set", () => {
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
recordVisitForThread(threadRef, "http://a.test/", 1);
|
||||
setTitleForThreadUrl(threadRef, "http://a.test/", "My App");
|
||||
const persist = spyOnPersistWrites();
|
||||
const byProjectKey = useBrowserHistoryStore.getState().byProjectKey;
|
||||
|
||||
setTitleForThreadUrl(threadRef, "http://a.test/", "My App");
|
||||
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey).toBe(byProjectKey);
|
||||
expect(persist).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sets a title against a settled url that differs from the stored one only by a trailing slash", () => {
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
recordVisitForThread(threadRef, "http://a.test/community", 1);
|
||||
setTitleForThreadUrl(threadRef, "http://a.test/community/", "Community");
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]).toMatchObject({
|
||||
url: "http://a.test/community",
|
||||
title: "Community",
|
||||
});
|
||||
|
||||
useBrowserHistoryStore.setState({ byProjectKey: {} });
|
||||
recordVisitForThread(threadRef, "http://a.test/community/", 1);
|
||||
setTitleForThreadUrl(threadRef, "http://a.test/community", "Community");
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]).toMatchObject({
|
||||
url: "http://a.test/community/",
|
||||
title: "Community",
|
||||
});
|
||||
});
|
||||
|
||||
it("matches a requested localhost URL to the resolved environment host", () => {
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
recordVisitForThread(threadRef, "http://localhost:5173/app", 1);
|
||||
setTitleForThreadUrl(threadRef, "http://192.168.64.2:5173/app", "Local App", "192.168.64.2");
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("Local App");
|
||||
});
|
||||
|
||||
it("deduplicates loopback aliases and the resolved environment host", () => {
|
||||
readPreparedConnection.mockReturnValue({ httpBaseUrl: "http://192.168.64.2:3773" });
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
recordVisitForThread(threadRef, "http://localhost:5173/app", 1);
|
||||
recordVisitForThread(threadRef, "http://127.0.0.1:5173/app", 2);
|
||||
recordVisitForThread(threadRef, "http://192.168.64.2:5173/app", 3);
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]).toEqual([
|
||||
{ url: "http://localhost:5173/app", lastVisitedAt: 3 },
|
||||
]);
|
||||
|
||||
useBrowserHistoryStore.setState({ byProjectKey: {} });
|
||||
recordVisitForThread(threadRef, "http://192.168.64.2:5173/app", 4);
|
||||
recordVisitForThread(threadRef, "http://localhost:5173/app", 5);
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]).toEqual([
|
||||
{ url: "http://localhost:5173/app", lastVisitedAt: 5 },
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not match a genuinely different path via the trailing-slash comparison", () => {
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
recordVisitForThread(threadRef, "http://a.test/community", 1);
|
||||
setTitleForThreadUrl(threadRef, "http://a.test/community/foo", "Foo");
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBeUndefined();
|
||||
});
|
||||
|
||||
it("updates only the most recent entry when several share a trailing-slash comparison key", () => {
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
recordVisitForThread(threadRef, "http://a.test/community/", 1);
|
||||
recordVisitForThread(threadRef, "http://a.test/community", 2);
|
||||
setTitleForThreadUrl(threadRef, "http://a.test/community/", "Community");
|
||||
const entries = useBrowserHistoryStore.getState().byProjectKey["proj-a"];
|
||||
expect(entries?.[0]).toMatchObject({ url: "http://a.test/community", title: "Community" });
|
||||
expect(entries?.[1]).toMatchObject({ url: "http://a.test/community/" });
|
||||
expect(entries?.[1]?.title).toBeUndefined();
|
||||
});
|
||||
|
||||
it("truncates oversized titles to the contract bound", () => {
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
recordVisitForThread(threadRef, "http://a.test/", 1);
|
||||
const oversized = "y".repeat(BROWSER_HISTORY_MAX_TITLE_LENGTH + 50);
|
||||
setTitleForThreadUrl(threadRef, "http://a.test/", oversized);
|
||||
const title = useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title;
|
||||
expect(title).toHaveLength(BROWSER_HISTORY_MAX_TITLE_LENGTH);
|
||||
expect(title).toBe(oversized.slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH));
|
||||
});
|
||||
|
||||
it("removes entries", () => {
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
recordVisitForThread(threadRef, "http://a.test/", 1);
|
||||
recordVisitForThread(threadRef, "http://b.test/", 2);
|
||||
removeUrlForThread(threadRef, "http://a.test/");
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.map((e) => e.url)).toEqual([
|
||||
"http://b.test/",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pendingVisitsByThreadKey", () => {
|
||||
beforeEach(() => {
|
||||
resetBrowserHistoryForTests();
|
||||
});
|
||||
|
||||
it("queues a visit recorded before registration and drains it in order on registration", () => {
|
||||
recordVisitForThread(threadRef, "http://a.test/", 1);
|
||||
recordVisitForThread(threadRef, "http://b.test/", 2);
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.map((e) => e.url)).toEqual([
|
||||
"http://b.test/",
|
||||
"http://a.test/",
|
||||
]);
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.lastVisitedAt).toBe(2);
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[1]?.lastVisitedAt).toBe(1);
|
||||
expect(useBrowserHistoryStore.getState().pendingVisitsByThreadKey).toEqual({});
|
||||
});
|
||||
|
||||
it("caps the per-thread pending list at 10, dropping the oldest", () => {
|
||||
for (let i = 0; i < 12; i++) {
|
||||
recordVisitForThread(threadRef, `http://a.test/${i}`, i);
|
||||
}
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
const urls = useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.map((e) => e.url);
|
||||
expect(urls).toHaveLength(10);
|
||||
expect(urls).not.toContain("http://a.test/0");
|
||||
expect(urls).not.toContain("http://a.test/1");
|
||||
expect(urls?.[0]).toBe("http://a.test/11");
|
||||
});
|
||||
|
||||
it("slots a replayed visit by timestamp instead of hoisting it above a newer live visit", () => {
|
||||
const otherThreadRef = {
|
||||
environmentId: EnvironmentId.make("env-1"),
|
||||
threadId: ThreadId.make("thread-2"),
|
||||
};
|
||||
useBrowserHistoryStore.getState().registerThreadProject(otherThreadRef, "proj-a");
|
||||
recordVisitForThread(otherThreadRef, "http://newer.test/", 2000);
|
||||
recordVisitForThread(threadRef, "http://older.test/", 1000);
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
|
||||
const entries = useBrowserHistoryStore.getState().byProjectKey["proj-a"];
|
||||
expect(entries?.map((e) => e.url)).toEqual(["http://newer.test/", "http://older.test/"]);
|
||||
// `entries[0]` being the most recent is the invariant `evictExcessProjects` relies on.
|
||||
expect(entries?.[0]?.lastVisitedAt).toBe(2000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("pendingTitlesByThreadKey", () => {
|
||||
beforeEach(() => {
|
||||
resetBrowserHistoryForTests();
|
||||
});
|
||||
|
||||
it("buffers a title set before registration and applies it once the matching visit drains", () => {
|
||||
recordVisitForThread(threadRef, "http://a.test/", 1);
|
||||
setTitleForThreadUrl(threadRef, "http://a.test/", "My App");
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey).toEqual({});
|
||||
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
|
||||
const entries = useBrowserHistoryStore.getState().byProjectKey["proj-a"];
|
||||
expect(entries?.[0]).toMatchObject({ url: "http://a.test/", title: "My App" });
|
||||
expect(useBrowserHistoryStore.getState().pendingTitlesByThreadKey).toEqual({});
|
||||
});
|
||||
|
||||
it("preserves environment host matching while a title is pending", () => {
|
||||
recordVisitForThread(threadRef, "http://localhost:5173/app", 1);
|
||||
setTitleForThreadUrl(threadRef, "http://192.168.64.2:5173/app", "Local App", "192.168.64.2");
|
||||
useBrowserHistoryStore.getState().registerThreadProject(threadRef, "proj-a");
|
||||
expect(useBrowserHistoryStore.getState().byProjectKey["proj-a"]?.[0]?.title).toBe("Local App");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeBrowserHistoryState", () => {
|
||||
it("sanitizes same-version corrupt persisted data and preserves actions", () => {
|
||||
// `migrate` only runs when versions differ; `merge` runs on every rehydrate.
|
||||
const current = useBrowserHistoryStore.getState();
|
||||
const merged = mergeBrowserHistoryState(
|
||||
{
|
||||
byProjectKey: {
|
||||
a: [{ url: "ftp://bad.test/", lastVisitedAt: 1 }],
|
||||
b: [{ url: "http://ok.test/", lastVisitedAt: 5 }],
|
||||
},
|
||||
projectKeyByThreadKey: { good: "b", stale: "a", malformed: 42 },
|
||||
},
|
||||
current,
|
||||
);
|
||||
expect(merged.byProjectKey).toEqual({
|
||||
b: [{ url: "http://ok.test/", lastVisitedAt: 5 }],
|
||||
});
|
||||
expect(typeof merged.recordVisit).toBe("function");
|
||||
expect(merged.projectKeyByThreadKey).toEqual({ good: "b" });
|
||||
expect(merged.pendingVisitsByThreadKey).toEqual({});
|
||||
expect(merged.pendingTitlesByThreadKey).toEqual({});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,398 @@
|
||||
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
|
||||
import type { ScopedThreadRef } from "@t3tools/contracts";
|
||||
import { create } from "zustand";
|
||||
import { createJSONStorage, persist } from "zustand/middleware";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
|
||||
import { normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import { readPreparedConnection } from "~/state/session";
|
||||
|
||||
import { isLocalLoopbackHost, normalizeHostname } from "./browser/browserTargetResolver";
|
||||
import { resolveStorage } from "./lib/storage";
|
||||
|
||||
export type BrowserHistoryEntry = { url: string; lastVisitedAt: number; title?: string };
|
||||
|
||||
export const BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT = 50;
|
||||
export const BROWSER_HISTORY_MAX_PROJECTS = 20;
|
||||
export const BROWSER_HISTORY_MAX_URL_LENGTH = 2048;
|
||||
export const BROWSER_HISTORY_MAX_TITLE_LENGTH = 512;
|
||||
const MAX_VALID_DATE_MS = 8_640_000_000_000_000;
|
||||
|
||||
export function isValidHistoryTimestamp(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === "number" && Number.isFinite(value) && Math.abs(value) <= MAX_VALID_DATE_MS
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeHistoryUrl(raw: string): string | null {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(normalizePreviewUrl(raw));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
parsed.username = parsed.password = "";
|
||||
return parsed.href.length > BROWSER_HISTORY_MAX_URL_LENGTH ? null : parsed.href;
|
||||
}
|
||||
|
||||
export function titleLookupKey(normalized: string, environmentHostname?: string | null): string {
|
||||
const parsed = new URL(visitLookupKey(normalized, environmentHostname));
|
||||
if (parsed.pathname !== "/" && parsed.pathname.endsWith("/"))
|
||||
parsed.pathname = parsed.pathname.slice(0, -1);
|
||||
return parsed.href;
|
||||
}
|
||||
|
||||
function visitLookupKey(normalized: string, environmentHostname?: string | null): string {
|
||||
const parsed = new URL(normalized);
|
||||
const host = normalizeHostname(parsed.hostname);
|
||||
const environmentHost = environmentHostname && normalizeHostname(environmentHostname);
|
||||
if (isLocalLoopbackHost(host) || host === "0.0.0.0" || host === environmentHost)
|
||||
parsed.hostname = "local";
|
||||
return parsed.href;
|
||||
}
|
||||
|
||||
function isStableLocalUrl(normalized: string): boolean {
|
||||
const host = normalizeHostname(new URL(normalized).hostname);
|
||||
return isLocalLoopbackHost(host) || host === "0.0.0.0";
|
||||
}
|
||||
|
||||
export function upsertHistoryEntry(
|
||||
entries: ReadonlyArray<BrowserHistoryEntry>,
|
||||
url: string,
|
||||
at: number,
|
||||
options?: { insertOrdered?: boolean; environmentHostname?: string | null },
|
||||
): BrowserHistoryEntry[] {
|
||||
const key = visitLookupKey(url, options?.environmentHostname);
|
||||
const existing = entries.find(
|
||||
(candidate) => visitLookupKey(candidate.url, options?.environmentHostname) === key,
|
||||
);
|
||||
const rest = entries.filter(
|
||||
(candidate) => visitLookupKey(candidate.url, options?.environmentHostname) !== key,
|
||||
);
|
||||
const visitedAt =
|
||||
options?.insertOrdered && existing && existing.lastVisitedAt > at ? existing.lastVisitedAt : at;
|
||||
const storedUrl =
|
||||
existing && (isStableLocalUrl(existing.url) || !isStableLocalUrl(url)) ? existing.url : url;
|
||||
const entry: BrowserHistoryEntry = existing
|
||||
? { ...existing, url: storedUrl, lastVisitedAt: visitedAt }
|
||||
: { url, lastVisitedAt: visitedAt };
|
||||
if (!options?.insertOrdered)
|
||||
return [entry, ...rest].slice(0, BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
|
||||
const index = rest.findIndex((candidate) => candidate.lastVisitedAt < entry.lastVisitedAt);
|
||||
const next = index === -1 ? [...rest, entry] : rest.toSpliced(index, 0, entry);
|
||||
return next.slice(0, BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
|
||||
}
|
||||
|
||||
export function evictExcessProjects(
|
||||
byProjectKey: Record<string, BrowserHistoryEntry[]>,
|
||||
): Record<string, BrowserHistoryEntry[]> {
|
||||
const keys = Object.keys(byProjectKey);
|
||||
if (keys.length <= BROWSER_HISTORY_MAX_PROJECTS) return byProjectKey;
|
||||
const kept = keys
|
||||
.toSorted(
|
||||
(a, b) =>
|
||||
(byProjectKey[b]?.[0]?.lastVisitedAt ?? 0) - (byProjectKey[a]?.[0]?.lastVisitedAt ?? 0),
|
||||
)
|
||||
.slice(0, BROWSER_HISTORY_MAX_PROJECTS);
|
||||
return Object.fromEntries(kept.map((key) => [key, byProjectKey[key] ?? []]));
|
||||
}
|
||||
|
||||
export function migratePersistedBrowserHistoryState(persistedState: unknown): {
|
||||
byProjectKey: Record<string, BrowserHistoryEntry[]>;
|
||||
} {
|
||||
if (!persistedState || typeof persistedState !== "object") return { byProjectKey: {} };
|
||||
const raw = (persistedState as { byProjectKey?: unknown }).byProjectKey;
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { byProjectKey: {} };
|
||||
const byProjectKey: Record<string, BrowserHistoryEntry[]> = {};
|
||||
for (const [projectKey, value] of Object.entries(raw as Record<string, unknown>)) {
|
||||
if (!Array.isArray(value)) continue;
|
||||
const seenUrls = new Set<string>();
|
||||
const entries = value
|
||||
.flatMap<BrowserHistoryEntry>((candidate) => {
|
||||
if (!candidate || typeof candidate !== "object") return [];
|
||||
const { url, lastVisitedAt, title } = candidate as Record<string, unknown>;
|
||||
if (typeof url !== "string") return [];
|
||||
const normalizedUrl = normalizeHistoryUrl(url);
|
||||
if (!normalizedUrl) return [];
|
||||
if (!isValidHistoryTimestamp(lastVisitedAt)) return [];
|
||||
return [
|
||||
{
|
||||
url: normalizedUrl,
|
||||
lastVisitedAt,
|
||||
...(typeof title === "string" && title.length > 0
|
||||
? { title: title.slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH) }
|
||||
: {}),
|
||||
},
|
||||
];
|
||||
})
|
||||
.toSorted((a, b) => b.lastVisitedAt - a.lastVisitedAt)
|
||||
.filter((entry) => {
|
||||
const key = visitLookupKey(entry.url);
|
||||
if (seenUrls.has(key)) return false;
|
||||
seenUrls.add(key);
|
||||
return true;
|
||||
})
|
||||
.slice(0, BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT);
|
||||
if (entries.length > 0) byProjectKey[projectKey] = entries;
|
||||
}
|
||||
return { byProjectKey: evictExcessProjects(byProjectKey) };
|
||||
}
|
||||
|
||||
const BROWSER_HISTORY_STORAGE_KEY = "t3code:browser-history:v1";
|
||||
|
||||
const PENDING_MAX_PER_THREAD = 10;
|
||||
const PENDING_MAX_THREADS = 20;
|
||||
|
||||
type PendingVisit = { url: string; at: number; environmentHostname: string | null };
|
||||
type PendingTitle = { url: string; title: string; environmentHostname: string | null | undefined };
|
||||
|
||||
interface BrowserHistoryStoreState {
|
||||
byProjectKey: Record<string, BrowserHistoryEntry[]>;
|
||||
projectKeyByThreadKey: Record<string, string>;
|
||||
pendingVisitsByThreadKey: Record<string, PendingVisit[]>;
|
||||
pendingTitlesByThreadKey: Record<string, PendingTitle[]>;
|
||||
recordVisit: (
|
||||
projectKey: string,
|
||||
url: string,
|
||||
at: number,
|
||||
options?: { insertOrdered?: boolean; environmentHostname?: string | null },
|
||||
) => void;
|
||||
setTitleForUrl: (
|
||||
projectKey: string,
|
||||
url: string,
|
||||
title: string,
|
||||
environmentHostname?: string | null,
|
||||
) => void;
|
||||
removeUrl: (projectKey: string, url: string) => void;
|
||||
registerThreadProject: (ref: ScopedThreadRef, projectKey: string) => void;
|
||||
}
|
||||
|
||||
function addPendingByThread<T>(
|
||||
pendingByThreadKey: Record<string, T[]>,
|
||||
threadKey: string,
|
||||
item: T,
|
||||
): Record<string, T[]> {
|
||||
const existing = pendingByThreadKey[threadKey] ?? [];
|
||||
const next = { ...pendingByThreadKey };
|
||||
next[threadKey] = [...existing, item].slice(-PENDING_MAX_PER_THREAD);
|
||||
const keys = Object.keys(next);
|
||||
if (keys.length > PENDING_MAX_THREADS) {
|
||||
const oldestKey = keys[0];
|
||||
if (oldestKey !== undefined && oldestKey !== threadKey) delete next[oldestKey];
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export const useBrowserHistoryStore = create<BrowserHistoryStoreState>()(
|
||||
persist(
|
||||
(set, get) => ({
|
||||
byProjectKey: {},
|
||||
projectKeyByThreadKey: {},
|
||||
pendingVisitsByThreadKey: {},
|
||||
pendingTitlesByThreadKey: {},
|
||||
recordVisit: (projectKey, url, at, options) => {
|
||||
const normalized = normalizeHistoryUrl(url);
|
||||
if (!normalized) return;
|
||||
set((state) => {
|
||||
return {
|
||||
byProjectKey: evictExcessProjects({
|
||||
...state.byProjectKey,
|
||||
[projectKey]: upsertHistoryEntry(
|
||||
state.byProjectKey[projectKey] ?? [],
|
||||
normalized,
|
||||
at,
|
||||
options,
|
||||
),
|
||||
}),
|
||||
};
|
||||
});
|
||||
},
|
||||
setTitleForUrl: (projectKey, url, title, environmentHostname) => {
|
||||
const normalized = normalizeHistoryUrl(url);
|
||||
const state = get();
|
||||
const entries = state.byProjectKey[projectKey];
|
||||
const trimmed = title.trim().slice(0, BROWSER_HISTORY_MAX_TITLE_LENGTH);
|
||||
if (!normalized || !entries || trimmed.length === 0) return;
|
||||
const key = titleLookupKey(normalized, environmentHostname);
|
||||
const index = entries.findIndex(
|
||||
(candidate) => titleLookupKey(candidate.url, environmentHostname) === key,
|
||||
);
|
||||
if (index === -1 || entries[index]?.title === trimmed) return;
|
||||
set({
|
||||
byProjectKey: {
|
||||
...state.byProjectKey,
|
||||
[projectKey]: entries.map((candidate, candidateIndex) =>
|
||||
candidateIndex === index ? { ...candidate, title: trimmed } : candidate,
|
||||
),
|
||||
},
|
||||
});
|
||||
},
|
||||
removeUrl: (projectKey, url) => {
|
||||
const normalized = normalizeHistoryUrl(url);
|
||||
const state = get();
|
||||
const entries = state.byProjectKey[projectKey];
|
||||
if (!normalized || !entries) return;
|
||||
const next = entries.filter((candidate) => candidate.url !== normalized);
|
||||
if (next.length === entries.length) return;
|
||||
if (next.length === 0) {
|
||||
const { [projectKey]: _removed, ...rest } = state.byProjectKey;
|
||||
set({ byProjectKey: rest });
|
||||
return;
|
||||
}
|
||||
set({ byProjectKey: { ...state.byProjectKey, [projectKey]: next } });
|
||||
},
|
||||
registerThreadProject: (ref, projectKey) => {
|
||||
const threadKey = scopedThreadKey(ref);
|
||||
const state = get();
|
||||
const pendingVisits = state.pendingVisitsByThreadKey[threadKey];
|
||||
const pendingTitles = state.pendingTitlesByThreadKey[threadKey];
|
||||
if (
|
||||
state.projectKeyByThreadKey[threadKey] === projectKey &&
|
||||
!pendingVisits &&
|
||||
!pendingTitles
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const nextPendingVisits = { ...state.pendingVisitsByThreadKey };
|
||||
const nextPendingTitles = { ...state.pendingTitlesByThreadKey };
|
||||
delete nextPendingVisits[threadKey];
|
||||
delete nextPendingTitles[threadKey];
|
||||
set({
|
||||
projectKeyByThreadKey: { ...state.projectKeyByThreadKey, [threadKey]: projectKey },
|
||||
pendingVisitsByThreadKey: nextPendingVisits,
|
||||
pendingTitlesByThreadKey: nextPendingTitles,
|
||||
});
|
||||
for (const visit of pendingVisits ?? [])
|
||||
get().recordVisit(projectKey, visit.url, visit.at, {
|
||||
insertOrdered: true,
|
||||
environmentHostname: visit.environmentHostname,
|
||||
});
|
||||
for (const pendingTitle of pendingTitles ?? [])
|
||||
get().setTitleForUrl(
|
||||
projectKey,
|
||||
pendingTitle.url,
|
||||
pendingTitle.title,
|
||||
pendingTitle.environmentHostname,
|
||||
);
|
||||
},
|
||||
}),
|
||||
{
|
||||
name: BROWSER_HISTORY_STORAGE_KEY,
|
||||
version: 1,
|
||||
storage: createJSONStorage(() =>
|
||||
resolveStorage(typeof window !== "undefined" ? window.localStorage : undefined),
|
||||
),
|
||||
partialize: (state) => ({
|
||||
byProjectKey: state.byProjectKey,
|
||||
projectKeyByThreadKey: state.projectKeyByThreadKey,
|
||||
}),
|
||||
migrate: migratePersistedBrowserHistoryState,
|
||||
merge: mergeBrowserHistoryState,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
export function mergeBrowserHistoryState(
|
||||
persistedState: unknown,
|
||||
currentState: BrowserHistoryStoreState,
|
||||
): BrowserHistoryStoreState {
|
||||
const migrated = migratePersistedBrowserHistoryState(persistedState);
|
||||
return {
|
||||
...currentState,
|
||||
...migrated,
|
||||
projectKeyByThreadKey: migratePersistedThreadProjectKeys(persistedState, migrated.byProjectKey),
|
||||
pendingVisitsByThreadKey: {},
|
||||
pendingTitlesByThreadKey: {},
|
||||
};
|
||||
}
|
||||
|
||||
function migratePersistedThreadProjectKeys(
|
||||
persistedState: unknown,
|
||||
byProjectKey: Record<string, BrowserHistoryEntry[]>,
|
||||
): Record<string, string> {
|
||||
if (!persistedState || typeof persistedState !== "object") return {};
|
||||
const raw = (persistedState as { projectKeyByThreadKey?: unknown }).projectKeyByThreadKey;
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
||||
return Object.fromEntries(
|
||||
Object.entries(raw as Record<string, unknown>)
|
||||
.filter(
|
||||
(entry): entry is [string, string] =>
|
||||
typeof entry[1] === "string" && entry[1] in byProjectKey,
|
||||
)
|
||||
.slice(-100),
|
||||
);
|
||||
}
|
||||
|
||||
export function recordVisitForThread(ref: ScopedThreadRef, url: string, at?: number): void {
|
||||
const threadKey = scopedThreadKey(ref);
|
||||
const state = useBrowserHistoryStore.getState();
|
||||
const projectKey = state.projectKeyByThreadKey[threadKey];
|
||||
const visitAt = at ?? Date.now();
|
||||
const connection = readPreparedConnection(ref.environmentId);
|
||||
const environmentHostname = connection ? new URL(connection.httpBaseUrl).hostname : null;
|
||||
if (!projectKey) {
|
||||
useBrowserHistoryStore.setState({
|
||||
pendingVisitsByThreadKey: addPendingByThread(state.pendingVisitsByThreadKey, threadKey, {
|
||||
url,
|
||||
at: visitAt,
|
||||
environmentHostname,
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
state.recordVisit(projectKey, url, visitAt, { environmentHostname });
|
||||
}
|
||||
|
||||
export function setTitleForThreadUrl(
|
||||
ref: ScopedThreadRef,
|
||||
url: string,
|
||||
title: string,
|
||||
environmentHostname?: string | null,
|
||||
): void {
|
||||
const threadKey = scopedThreadKey(ref);
|
||||
const state = useBrowserHistoryStore.getState();
|
||||
const projectKey = state.projectKeyByThreadKey[threadKey];
|
||||
if (!projectKey) {
|
||||
useBrowserHistoryStore.setState({
|
||||
pendingTitlesByThreadKey: addPendingByThread(state.pendingTitlesByThreadKey, threadKey, {
|
||||
url,
|
||||
title,
|
||||
environmentHostname,
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
state.setTitleForUrl(projectKey, url, title, environmentHostname);
|
||||
}
|
||||
|
||||
export function removeUrlForThread(ref: ScopedThreadRef, url: string): void {
|
||||
const state = useBrowserHistoryStore.getState();
|
||||
const projectKey = state.projectKeyByThreadKey[scopedThreadKey(ref)];
|
||||
if (!projectKey) return;
|
||||
state.removeUrl(projectKey, url);
|
||||
}
|
||||
|
||||
const EMPTY_HISTORY: ReadonlyArray<BrowserHistoryEntry> = [];
|
||||
|
||||
export function useThreadRecentHistory(
|
||||
ref: ScopedThreadRef,
|
||||
limit: number,
|
||||
): ReadonlyArray<BrowserHistoryEntry> {
|
||||
return useBrowserHistoryStore(
|
||||
useShallow((state) => {
|
||||
const projectKey = state.projectKeyByThreadKey[scopedThreadKey(ref)];
|
||||
const entries = projectKey ? state.byProjectKey[projectKey] : undefined;
|
||||
return entries && entries.length > 0 ? entries.slice(0, limit) : EMPTY_HISTORY;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function resetBrowserHistoryForTests(): void {
|
||||
useBrowserHistoryStore.setState({
|
||||
byProjectKey: {},
|
||||
projectKeyByThreadKey: {},
|
||||
pendingVisitsByThreadKey: {},
|
||||
pendingTitlesByThreadKey: {},
|
||||
});
|
||||
useBrowserHistoryStore.persist.clearStorage();
|
||||
}
|
||||
@@ -126,7 +126,7 @@ const MobileRunContextSelector = memo(function MobileRunContextSelector({
|
||||
|
||||
if (isLocked) {
|
||||
return (
|
||||
<span className="inline-flex min-w-0 max-w-[48%] flex-1 items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 md:hidden">
|
||||
<span className="inline-flex h-7 min-w-0 max-w-[48%] flex-1 items-center justify-start gap-1 rounded-md border border-transparent px-[calc(--spacing(2)-1px)] text-sm font-medium text-muted-foreground/70 sm:h-6 md:hidden">
|
||||
{triggerContent}
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -50,7 +50,7 @@ export const BranchToolbarEnvModeSelector = memo(function BranchToolbarEnvModeSe
|
||||
|
||||
if (envLocked) {
|
||||
return (
|
||||
<span className="inline-flex shrink-0 items-center gap-1 border border-transparent px-[calc(--spacing(3)-1px)] text-sm font-medium text-muted-foreground/70 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">
|
||||
{activeWorktreePath ? (
|
||||
<>
|
||||
<FolderGitIcon className="size-3" />
|
||||
|
||||
@@ -41,9 +41,14 @@ export const BranchToolbarEnvironmentSelector = memo(function BranchToolbarEnvir
|
||||
[availableEnvironments],
|
||||
);
|
||||
|
||||
// The static label carries the xs control's height (h-7 sm:h-6) as well as
|
||||
// its padding: the composer context strip has no min-height of its own, and
|
||||
// the glass seam joining it to the composer assumes a fixed strip height, so
|
||||
// a shorter label would drag the seam out of line whenever this label is the
|
||||
// only thing in the strip.
|
||||
if (envLocked || onEnvironmentChange === undefined) {
|
||||
return (
|
||||
<span className="inline-flex 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: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">
|
||||
{activeEnvironment?.isPrimary ? (
|
||||
<MonitorIcon className="size-3 shrink-0" />
|
||||
) : (
|
||||
|
||||
@@ -52,6 +52,7 @@ import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "./ui/collapsi
|
||||
import { ScrollArea } from "./ui/scroll-area";
|
||||
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "./ui/menu";
|
||||
import { stackedThreadToast, toastManager } from "./ui/toast";
|
||||
import { recordVisitForThread } from "../browserHistoryStore";
|
||||
import { useOpenInPreferredEditor } from "../editorPreferences";
|
||||
import { resolveDiffThemeName, type DiffThemeName } from "../lib/diffRendering";
|
||||
import { fnv1a32 } from "../lib/diffRendering";
|
||||
@@ -1336,7 +1337,10 @@ function ChatMarkdown({
|
||||
),
|
||||
);
|
||||
}
|
||||
return openUrlInPreview({ threadRef, url, openPreview });
|
||||
return openUrlInPreview({ threadRef, url, openPreview }).then((result) => {
|
||||
if (result._tag === "Success") recordVisitForThread(threadRef, url);
|
||||
return result;
|
||||
});
|
||||
},
|
||||
[openPreview, threadRef],
|
||||
);
|
||||
|
||||
@@ -172,9 +172,14 @@ import {
|
||||
projectScriptIdFromCommand,
|
||||
} from "~/projectScripts";
|
||||
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
|
||||
import { useBrowserHistoryStore } from "~/browserHistoryStore";
|
||||
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
|
||||
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
|
||||
import { useClientSettings, useEnvironmentSettings } from "../hooks/useSettings";
|
||||
import {
|
||||
useClientSettings,
|
||||
useClientSettingsHydrated,
|
||||
useEnvironmentSettings,
|
||||
} from "../hooks/useSettings";
|
||||
import { useNowMinute } from "../hooks/useNowMinute";
|
||||
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
|
||||
import { resolveAppModelSelectionForInstance } from "../modelSelection";
|
||||
@@ -182,9 +187,11 @@ import { getTerminalFocusOwner } from "../lib/terminalFocus";
|
||||
import { preventRepeatedTerminalCloseShortcut } from "../lib/terminalCloseShortcut";
|
||||
import { resolveNewDraftStartFromOrigin } from "../lib/chatThreadActions";
|
||||
import {
|
||||
derivePhysicalProjectKey,
|
||||
deriveLogicalProjectKeyFromSettings,
|
||||
selectProjectGroupingSettings,
|
||||
} from "../logicalProject";
|
||||
import { buildPhysicalToLogicalProjectKeyMap } from "../sidebarProjectGrouping";
|
||||
import { buildDraftThreadRouteParams } from "../threadRoutes";
|
||||
import {
|
||||
type ComposerImageAttachment,
|
||||
@@ -1491,6 +1498,7 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const isLocalDraftThread = !isServerThread && localDraftThread !== undefined;
|
||||
const canCheckoutPullRequestIntoThread = isLocalDraftThread;
|
||||
const activeThreadId = activeThread?.id ?? null;
|
||||
const activeThreadEnvironmentId = activeThread?.environmentId ?? null;
|
||||
const runningTerminalIds = useThreadRunningTerminalIds({
|
||||
environmentId: activeThread?.environmentId ?? null,
|
||||
threadId: activeThreadId,
|
||||
@@ -1526,8 +1534,11 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
return labels;
|
||||
}, [activeThreadKnownSessions]);
|
||||
const activeThreadRef = useMemo(
|
||||
() => (activeThread ? scopeThreadRef(activeThread.environmentId, activeThread.id) : null),
|
||||
[activeThread],
|
||||
() =>
|
||||
activeThreadEnvironmentId && activeThreadId
|
||||
? scopeThreadRef(activeThreadEnvironmentId, activeThreadId)
|
||||
: null,
|
||||
[activeThreadEnvironmentId, activeThreadId],
|
||||
);
|
||||
const activeThreadKey = activeThreadRef ? scopedThreadKey(activeThreadRef) : null;
|
||||
const [timelineAnchor, setTimelineAnchor] = useState<{
|
||||
@@ -1652,6 +1663,8 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
const activeProjectKey = activeProject
|
||||
? `${activeProject.environmentId}:${activeProject.workspaceRoot}`
|
||||
: null;
|
||||
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
|
||||
const clientSettingsHydrated = useClientSettingsHydrated();
|
||||
const [pendingFileSurfaceIdsByProject, setPendingFileSurfaceIdsByProject] = useState<
|
||||
ReadonlyMap<string, ReadonlySet<string>>
|
||||
>(() => new Map());
|
||||
@@ -1690,6 +1703,31 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
// drive the environment picker in BranchToolbar.
|
||||
const allProjects = useProjects();
|
||||
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
|
||||
useEffect(() => {
|
||||
if (!clientSettingsHydrated || !activeThreadRef || !activeProject) return;
|
||||
// Reuse the sidebar's grouping so history follows the project rows the user
|
||||
// sees. Deriving the key from the active project alone would miss the
|
||||
// identity a duplicate row borrows from its siblings.
|
||||
const logicalKeyByPhysicalKey = buildPhysicalToLogicalProjectKeyMap({
|
||||
projects: allProjects,
|
||||
settings: projectGroupingSettings,
|
||||
primaryEnvironmentId,
|
||||
});
|
||||
useBrowserHistoryStore
|
||||
.getState()
|
||||
.registerThreadProject(
|
||||
activeThreadRef,
|
||||
logicalKeyByPhysicalKey.get(derivePhysicalProjectKey(activeProject)) ??
|
||||
deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings),
|
||||
);
|
||||
}, [
|
||||
activeProject,
|
||||
activeThreadRef,
|
||||
allProjects,
|
||||
clientSettingsHydrated,
|
||||
primaryEnvironmentId,
|
||||
projectGroupingSettings,
|
||||
]);
|
||||
const activeEnvironment =
|
||||
activeThread == null ? null : (environmentById.get(activeThread.environmentId) ?? null);
|
||||
const activeEnvironmentConnectionPhase = activeEnvironment?.connection.phase ?? "available";
|
||||
@@ -1723,7 +1761,6 @@ function ChatViewContent(props: ChatViewProps) {
|
||||
},
|
||||
[retryEnvironment],
|
||||
);
|
||||
const projectGroupingSettings = selectProjectGroupingSettings(settings);
|
||||
const logicalProjectEnvironments = useMemo(() => {
|
||||
if (!activeProject) return [];
|
||||
const logicalKey = deriveLogicalProjectKeyFromSettings(activeProject, projectGroupingSettings);
|
||||
|
||||
@@ -1,6 +1,64 @@
|
||||
import { describe, expect, it } from "vite-plus/test";
|
||||
import { createElement } from "react";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import { formatPendingPrimaryActionLabel } from "./ComposerPrimaryActions";
|
||||
vi.mock("~/hooks/useSettings", () => ({
|
||||
useEnvironmentIdentificationMode: () => "none",
|
||||
}));
|
||||
vi.mock("../SidebarStageBackdrop", () => ({
|
||||
StageBackdropButtonArt: () => null,
|
||||
useSidebarStageBackdropVariant: () => null,
|
||||
}));
|
||||
|
||||
import { ComposerPrimaryActions, formatPendingPrimaryActionLabel } from "./ComposerPrimaryActions";
|
||||
|
||||
function renderPendingActions(isRunning: boolean) {
|
||||
return renderToStaticMarkup(
|
||||
createElement(ComposerPrimaryActions, {
|
||||
compact: true,
|
||||
pendingAction: {
|
||||
questionIndex: 0,
|
||||
isLastQuestion: true,
|
||||
canAdvance: true,
|
||||
isResponding: false,
|
||||
isComplete: true,
|
||||
},
|
||||
isRunning,
|
||||
showPlanFollowUpPrompt: false,
|
||||
promptHasText: false,
|
||||
isSendBusy: false,
|
||||
sendDisabledReason: null,
|
||||
isConnecting: false,
|
||||
isEnvironmentUnavailable: false,
|
||||
isPreparingWorktree: false,
|
||||
hasSendableContent: false,
|
||||
onPreviousPendingQuestion: () => {},
|
||||
onInterrupt: () => {},
|
||||
onImplementPlanInNewThread: () => {},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
function renderStandaloneStop() {
|
||||
return renderToStaticMarkup(
|
||||
createElement(ComposerPrimaryActions, {
|
||||
compact: true,
|
||||
pendingAction: null,
|
||||
isRunning: true,
|
||||
showPlanFollowUpPrompt: false,
|
||||
promptHasText: false,
|
||||
isSendBusy: false,
|
||||
sendDisabledReason: null,
|
||||
isConnecting: false,
|
||||
isEnvironmentUnavailable: false,
|
||||
isPreparingWorktree: false,
|
||||
hasSendableContent: false,
|
||||
onPreviousPendingQuestion: () => {},
|
||||
onInterrupt: () => {},
|
||||
onImplementPlanInNewThread: () => {},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
describe("formatPendingPrimaryActionLabel", () => {
|
||||
it("returns 'Submitting...' while responding", () => {
|
||||
@@ -91,3 +149,19 @@ describe("formatPendingPrimaryActionLabel", () => {
|
||||
).toBe("Submit answers");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ComposerPrimaryActions", () => {
|
||||
it("offers Stop generation while a running turn is waiting for user input", () => {
|
||||
expect(renderPendingActions(true)).toContain('aria-label="Stop generation"');
|
||||
});
|
||||
|
||||
it("does not offer Stop generation for a pending request without a running turn", () => {
|
||||
expect(renderPendingActions(false)).not.toContain('aria-label="Stop generation"');
|
||||
});
|
||||
|
||||
it("matches the small pending action size without changing the standalone size", () => {
|
||||
expect(renderPendingActions(true)).toContain("size-8 sm:size-7");
|
||||
expect(renderStandaloneStop()).toContain("size-8 sm:h-8 sm:w-8");
|
||||
expect(renderStandaloneStop()).not.toContain("sm:size-7");
|
||||
});
|
||||
});
|
||||
@@ -75,9 +75,27 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
: undefined;
|
||||
const isSendDisabled = sendDisabledReason !== null;
|
||||
|
||||
const renderStopGenerationButton = (insidePendingAction: boolean) => (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"flex cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-destructive hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none",
|
||||
insidePendingAction ? "size-8 sm:size-7" : "size-8 sm:h-8 sm:w-8",
|
||||
)}
|
||||
{...pointerFocusProps}
|
||||
onClick={onInterrupt}
|
||||
aria-label="Stop generation"
|
||||
>
|
||||
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
|
||||
<rect x="2" y="2" width="8" height="8" rx="1.5" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
|
||||
if (pendingAction) {
|
||||
return (
|
||||
<div className={cn("flex items-center justify-end", compact ? "gap-1.5" : "gap-2")}>
|
||||
{isRunning ? renderStopGenerationButton(true) : null}
|
||||
{pendingAction.questionIndex > 0 ? (
|
||||
compact ? (
|
||||
<Button
|
||||
@@ -130,19 +148,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({
|
||||
}
|
||||
|
||||
if (isRunning) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className="flex size-8 cursor-pointer items-center justify-center rounded-full bg-destructive/90 text-white shadow-xs shadow-destructive/24 inset-shadow-[0_1px_--theme(--color-white/16%)] transition-all duration-150 hover:bg-destructive hover:scale-105 active:inset-shadow-[0_1px_--theme(--color-black/8%)] active:shadow-none sm:h-8 sm:w-8"
|
||||
{...pointerFocusProps}
|
||||
onClick={onInterrupt}
|
||||
aria-label="Stop generation"
|
||||
>
|
||||
<svg width="12" height="12" viewBox="0 0 12 12" fill="currentColor" aria-hidden="true">
|
||||
<rect x="2" y="2" width="8" height="8" rx="1.5" />
|
||||
</svg>
|
||||
</button>
|
||||
);
|
||||
return renderStopGenerationButton(false);
|
||||
}
|
||||
|
||||
if (showPlanFollowUpPrompt) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { cn } from "~/lib/utils";
|
||||
|
||||
/** Browser-window thumbnail glyph for the "Local" recommendation cards. */
|
||||
/** Browser-window thumbnail glyph for preview recommendation cards. */
|
||||
export function BrowserMockup({ className }: { className?: string }) {
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { EnvironmentId } from "@t3tools/contracts";
|
||||
import { renderToStaticMarkup } from "react-dom/server";
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
servers: [] as Array<{
|
||||
host: string;
|
||||
port: number;
|
||||
url: string;
|
||||
requestedUrl: string;
|
||||
processName: string | null;
|
||||
pid: number | null;
|
||||
terminal: null;
|
||||
source: "scanner";
|
||||
listening: boolean;
|
||||
}>,
|
||||
}));
|
||||
|
||||
vi.mock("./useDiscoveredLocalServers", () => ({
|
||||
useDiscoveredLocalServers: () => mocks.servers,
|
||||
}));
|
||||
|
||||
import { PreviewEmptyState } from "./PreviewEmptyState";
|
||||
|
||||
const environmentId = EnvironmentId.make("env-1");
|
||||
|
||||
function server(port: number) {
|
||||
return {
|
||||
host: "localhost",
|
||||
port,
|
||||
url: `http://localhost:${port}`,
|
||||
requestedUrl: `http://localhost:${port}`,
|
||||
processName: "node",
|
||||
pid: 1,
|
||||
terminal: null,
|
||||
source: "scanner" as const,
|
||||
listening: true,
|
||||
};
|
||||
}
|
||||
|
||||
function render(recentEntries: Array<{ url: string; lastVisitedAt: number; title?: string }>) {
|
||||
return renderToStaticMarkup(
|
||||
<PreviewEmptyState
|
||||
environmentId={environmentId}
|
||||
recentEntries={recentEntries}
|
||||
onRemoveRecent={() => undefined}
|
||||
onOpenUrl={() => undefined}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
describe("PreviewEmptyState", () => {
|
||||
it("renders a history entry in both groups when its host:port matches a live server", () => {
|
||||
mocks.servers = [server(5173)];
|
||||
const html = render([
|
||||
{ url: "https://myapp.test/admin#users", lastVisitedAt: Date.now(), title: "Admin" },
|
||||
{ url: "http://localhost:5173/", lastVisitedAt: Date.now(), title: "Recent Local" },
|
||||
]);
|
||||
expect(html).toContain("Recently used");
|
||||
expect(html).toContain("Local servers");
|
||||
expect(html).toContain("myapp.test/admin#users");
|
||||
expect(html).toContain("Admin");
|
||||
expect(html).toContain("Recent Local");
|
||||
expect(html).toContain("node");
|
||||
});
|
||||
|
||||
it("renders only the recents group when no servers are found", () => {
|
||||
mocks.servers = [];
|
||||
const html = render([{ url: "https://myapp.test/", lastVisitedAt: 0 }]);
|
||||
expect(html).toContain("Recently used");
|
||||
expect(html).not.toContain("Local servers");
|
||||
});
|
||||
|
||||
it("keeps the original empty state when both groups are empty", () => {
|
||||
mocks.servers = [];
|
||||
const html = render([]);
|
||||
expect(html).toContain("No preview yet");
|
||||
});
|
||||
|
||||
it("renders an out-of-range lastVisitedAt entry without throwing", () => {
|
||||
mocks.servers = [];
|
||||
let html = "";
|
||||
expect(() => {
|
||||
html = render([{ url: "https://myapp.test/", lastVisitedAt: 1e20 }]);
|
||||
}).not.toThrow();
|
||||
expect(html).toContain("myapp.test");
|
||||
expect(html).toContain("Remove");
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,19 @@
|
||||
import type { EnvironmentId } from "@t3tools/contracts";
|
||||
import { Globe, RadioTower } from "lucide-react";
|
||||
import { Globe, History, RadioTower } from "lucide-react";
|
||||
|
||||
import type { BrowserHistoryEntry } from "~/browserHistoryStore";
|
||||
import { Empty, EmptyDescription, EmptyMedia, EmptyTitle } from "~/components/ui/empty";
|
||||
|
||||
import { PreviewLocalServerCard } from "./PreviewLocalServerCard";
|
||||
import { PreviewRecentUrlCard } from "./PreviewRecentUrlCard";
|
||||
import { useDiscoveredLocalServers } from "./useDiscoveredLocalServers";
|
||||
|
||||
interface Props {
|
||||
environmentId: EnvironmentId;
|
||||
configuredUrls?: ReadonlyArray<string> | undefined;
|
||||
recentlySeenUrls?: ReadonlyArray<string> | undefined;
|
||||
recentEntries: ReadonlyArray<BrowserHistoryEntry>;
|
||||
onRemoveRecent: (url: string) => void;
|
||||
onOpenUrl: (url: string) => void;
|
||||
}
|
||||
|
||||
@@ -17,6 +21,8 @@ export function PreviewEmptyState({
|
||||
environmentId,
|
||||
configuredUrls,
|
||||
recentlySeenUrls,
|
||||
recentEntries,
|
||||
onRemoveRecent,
|
||||
onOpenUrl,
|
||||
}: Props) {
|
||||
const servers = useDiscoveredLocalServers({
|
||||
@@ -24,8 +30,9 @@ export function PreviewEmptyState({
|
||||
configuredUrls,
|
||||
recentlySeenUrls,
|
||||
});
|
||||
const recents = recentEntries.filter((entry) => URL.canParse(entry.url)).slice(0, 8);
|
||||
|
||||
if (servers.length === 0) {
|
||||
if (servers.length === 0 && recents.length === 0) {
|
||||
return (
|
||||
<Empty>
|
||||
<EmptyMedia variant="icon">
|
||||
@@ -42,23 +49,45 @@ export function PreviewEmptyState({
|
||||
|
||||
return (
|
||||
<div className="flex h-full min-h-0 overflow-y-auto px-5 py-8">
|
||||
<div className="m-auto flex w-full max-w-xl flex-col gap-3">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<RadioTower className="size-4 shrink-0" />
|
||||
<h2 className="font-medium">Local servers</h2>
|
||||
</div>
|
||||
<div className="flex flex-col divide-y divide-border/60 overflow-hidden rounded-xl border border-border/70 bg-background">
|
||||
{servers.map((server) => (
|
||||
<PreviewLocalServerCard
|
||||
key={`${server.host}:${server.port}`}
|
||||
server={server}
|
||||
onOpen={() => onOpenUrl(server.url)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<p className="px-1 text-xs text-muted-foreground">
|
||||
Select a listening port to open it in this browser tab.
|
||||
</p>
|
||||
<div className="m-auto flex w-full max-w-xl flex-col gap-6">
|
||||
{recents.length > 0 ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<History className="size-4 shrink-0" />
|
||||
<h2 className="font-medium">Recently used</h2>
|
||||
</div>
|
||||
<div className="flex flex-col divide-y divide-border/60 overflow-hidden rounded-xl border border-border/70 bg-background">
|
||||
{recents.map((entry) => (
|
||||
<PreviewRecentUrlCard
|
||||
key={entry.url}
|
||||
entry={entry}
|
||||
onOpen={() => onOpenUrl(entry.url)}
|
||||
onRemove={() => onRemoveRecent(entry.url)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
{servers.length > 0 ? (
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<RadioTower className="size-4 shrink-0" />
|
||||
<h2 className="font-medium">Local servers</h2>
|
||||
</div>
|
||||
<div className="flex flex-col divide-y divide-border/60 overflow-hidden rounded-xl border border-border/70 bg-background">
|
||||
{servers.map((server) => (
|
||||
<PreviewLocalServerCard
|
||||
key={`${server.host}:${server.port}`}
|
||||
server={server}
|
||||
onOpen={() => onOpenUrl(server.requestedUrl)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
<p className="px-1 text-xs text-muted-foreground">
|
||||
Select a listening port to open it in this browser tab.
|
||||
</p>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { X } from "lucide-react";
|
||||
|
||||
import { isValidHistoryTimestamp, type BrowserHistoryEntry } from "~/browserHistoryStore";
|
||||
import { useNowMinute } from "~/hooks/useNowMinute";
|
||||
import { formatRelativeTimeLabel } from "~/timestampFormat";
|
||||
|
||||
import { BrowserMockup } from "./BrowserMockup";
|
||||
|
||||
interface Props {
|
||||
entry: BrowserHistoryEntry;
|
||||
onOpen: () => void;
|
||||
onRemove: () => void;
|
||||
}
|
||||
|
||||
export function PreviewRecentUrlCard({ entry, onOpen, onRemove }: Props) {
|
||||
const parsed = new URL(entry.url);
|
||||
const path = parsed.pathname === "/" ? "" : parsed.pathname;
|
||||
const label = `${parsed.host}${path}${parsed.search}${parsed.hash}`;
|
||||
const visitedAt = isValidHistoryTimestamp(entry.lastVisitedAt)
|
||||
? formatRelativeTimeLabel(new Date(entry.lastVisitedAt).toISOString())
|
||||
: "";
|
||||
useNowMinute();
|
||||
return (
|
||||
<div className="group relative flex w-full items-center">
|
||||
<button
|
||||
type="button"
|
||||
onClick={onOpen}
|
||||
className="flex w-full items-center gap-3 px-3 py-3 pr-10 text-left hover:bg-accent/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
|
||||
>
|
||||
<BrowserMockup className="size-7 shrink-0" />
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<span className="truncate text-sm font-medium text-foreground">
|
||||
{entry.title ?? label}
|
||||
</span>
|
||||
<span className="truncate text-xs text-muted-foreground">
|
||||
{entry.title ? `${label} · ` : ""}
|
||||
{visitedAt}
|
||||
</span>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Remove ${label} from history`}
|
||||
onClick={onRemove}
|
||||
className="absolute right-3 rounded p-1 text-muted-foreground opacity-0 hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring group-hover:opacity-100"
|
||||
>
|
||||
<X className="size-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -24,6 +24,17 @@ const mocks = vi.hoisted(() => ({
|
||||
toggleAnnotation: null as (() => void) | null,
|
||||
pictureInPicture: false,
|
||||
showEmptyState: false,
|
||||
recordVisitForThread: vi.fn(),
|
||||
}));
|
||||
|
||||
const EMPTY_HISTORY: never[] = [];
|
||||
|
||||
vi.mock("~/browserHistoryStore", () => ({
|
||||
recordVisitForThread: mocks.recordVisitForThread,
|
||||
setTitleForThreadUrl: vi.fn(),
|
||||
removeUrlForThread: vi.fn(),
|
||||
BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT: 50,
|
||||
useThreadRecentHistory: () => EMPTY_HISTORY,
|
||||
}));
|
||||
|
||||
vi.mock("~/state/session", () => ({
|
||||
@@ -232,6 +243,7 @@ describe("PreviewView navigation", () => {
|
||||
mocks.toggleAnnotation = null;
|
||||
mocks.pictureInPicture = false;
|
||||
mocks.showEmptyState = false;
|
||||
mocks.recordVisitForThread.mockClear();
|
||||
});
|
||||
|
||||
it.each([
|
||||
@@ -267,6 +279,27 @@ describe("PreviewView navigation", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("records a history visit with the normalized requested url on submit", async () => {
|
||||
renderToStaticMarkup(
|
||||
<PreviewView
|
||||
threadRef={{
|
||||
environmentId: EnvironmentId.make("environment-1"),
|
||||
threadId: ThreadId.make("thread-1"),
|
||||
}}
|
||||
tabId="tab-1"
|
||||
visible
|
||||
/>,
|
||||
);
|
||||
|
||||
mocks.submittedUrl?.("localhost:3000/admin");
|
||||
await vi.waitFor(() => {
|
||||
expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ threadId: expect.anything() }),
|
||||
"http://localhost:3000/admin",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("maps an empty-state localhost server onto the WSL host", async () => {
|
||||
mocks.showEmptyState = true;
|
||||
renderToStaticMarkup(
|
||||
@@ -296,6 +329,12 @@ describe("PreviewView navigation", () => {
|
||||
},
|
||||
"http://172.25.85.75:5173/app?mode=test#top",
|
||||
);
|
||||
await vi.waitFor(() =>
|
||||
expect(mocks.recordVisitForThread).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ threadId: expect.anything() }),
|
||||
"http://localhost:5173/app?mode=test#top",
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it("opens and closes a thread-scoped floating preview for the active tab", async () => {
|
||||
|
||||
@@ -11,6 +11,13 @@ import {
|
||||
import { normalizePreviewUrl } from "@t3tools/shared/preview";
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import {
|
||||
BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
|
||||
recordVisitForThread,
|
||||
removeUrlForThread,
|
||||
setTitleForThreadUrl,
|
||||
useThreadRecentHistory,
|
||||
} from "~/browserHistoryStore";
|
||||
import { type ComposerImageAttachment, useComposerDraftStore } from "~/composerDraftStore";
|
||||
import { previewAnnotationScreenshotFile } from "~/lib/previewAnnotation";
|
||||
import { ensureLocalApi } from "~/localApi";
|
||||
@@ -20,6 +27,7 @@ import {
|
||||
useThreadPreviewState,
|
||||
} from "~/previewStateStore";
|
||||
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
|
||||
import { useEnvironmentHttpBaseUrl } from "~/state/environments";
|
||||
import { previewEnvironment } from "~/state/preview";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
import { selectThreadPreviewMiniPlayer, usePreviewMiniPlayerStore } from "~/previewMiniPlayerStore";
|
||||
@@ -83,12 +91,24 @@ export function PreviewView({
|
||||
const activeRecordingTabIds = useActiveBrowserRecordingTabIds();
|
||||
const pickActiveRef = useRef(false);
|
||||
const isMountedRef = useRef(true);
|
||||
// Kept in sync so the title effect can depend on the stable thread key
|
||||
// instead of the thread object, which is recreated on every update.
|
||||
const threadRefRef = useRef(threadRef);
|
||||
threadRefRef.current = threadRef;
|
||||
const previewState = useThreadPreviewState(threadRef);
|
||||
const recentHistoryEntries = useThreadRecentHistory(
|
||||
threadRef,
|
||||
BROWSER_HISTORY_MAX_ENTRIES_PER_PROJECT,
|
||||
);
|
||||
const miniPlayer = usePreviewMiniPlayerStore((state) =>
|
||||
selectThreadPreviewMiniPlayer(state.byThreadKey, threadRef),
|
||||
);
|
||||
const addPreviewAnnotation = useComposerDraftStore((store) => store.addPreviewAnnotation);
|
||||
const addImage = useComposerDraftStore((store) => store.addImage);
|
||||
const environmentHttpBaseUrl = useEnvironmentHttpBaseUrl(threadRef.environmentId);
|
||||
const environmentHostname = environmentHttpBaseUrl
|
||||
? new URL(environmentHttpBaseUrl).hostname
|
||||
: null;
|
||||
const open = useAtomCommand(previewEnvironment.open);
|
||||
const resize = useAtomCommand(previewEnvironment.resize, "preview viewport resize");
|
||||
|
||||
@@ -128,20 +148,27 @@ export function PreviewView({
|
||||
runtimeTabId ? (state.byTabId[runtimeTabId]?.rect ?? null) : null,
|
||||
);
|
||||
|
||||
const navUrl = navStatus._tag === "Success" ? navStatus.url : null;
|
||||
const navTitle = navStatus._tag === "Success" ? navStatus.title : null;
|
||||
const latestHistoryUrl = recentHistoryEntries[0]?.url;
|
||||
const threadKey = scopedThreadKey(threadRef);
|
||||
useEffect(() => {
|
||||
if (!navUrl || !navTitle || !latestHistoryUrl) return;
|
||||
// Agent-driven pages only enrich an existing requested URL.
|
||||
setTitleForThreadUrl(threadRefRef.current, navUrl, navTitle, environmentHostname);
|
||||
// threadKey stands in for threadRef, whose identity churns on every thread update.
|
||||
}, [environmentHostname, latestHistoryUrl, navTitle, navUrl, threadKey]);
|
||||
|
||||
const navigateToResolvedUrl = useCallback(
|
||||
async (resolvedUrl: string) => {
|
||||
if (runtimeTabId && previewBridge) {
|
||||
// Drive the webview imperatively; `usePreviewBridge` mirrors the
|
||||
// resolved URL back to the server so other clients stay in sync.
|
||||
// The bridge mirrors the resolved URL back to the server.
|
||||
await previewBridge.navigate(runtimeTabId, resolvedUrl);
|
||||
rememberPreviewUrl(threadRef, resolvedUrl);
|
||||
} else {
|
||||
await openPreviewSession({
|
||||
openPreview: open,
|
||||
threadRef,
|
||||
url: resolvedUrl,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
const result = await openPreviewSession({ openPreview: open, threadRef, url: resolvedUrl });
|
||||
return result._tag === "Success";
|
||||
},
|
||||
[open, runtimeTabId, threadRef],
|
||||
);
|
||||
@@ -149,23 +176,29 @@ export function PreviewView({
|
||||
const handleSubmitUrl = useCallback(
|
||||
async (next: string) => {
|
||||
try {
|
||||
await navigateToResolvedUrl(normalizePreviewUrl(next));
|
||||
const normalized = normalizePreviewUrl(next);
|
||||
if (await navigateToResolvedUrl(normalized)) {
|
||||
recordVisitForThread(threadRef, normalized);
|
||||
}
|
||||
} catch {
|
||||
// Server-side `failed` event renders the unreachable view.
|
||||
}
|
||||
},
|
||||
[navigateToResolvedUrl],
|
||||
[navigateToResolvedUrl, threadRef],
|
||||
);
|
||||
|
||||
const handleOpenServerUrl = useCallback(
|
||||
async (next: string) => {
|
||||
try {
|
||||
await navigateToResolvedUrl(resolveDiscoveredServerUrl(threadRef.environmentId, next));
|
||||
const resolved = resolveDiscoveredServerUrl(threadRef.environmentId, next);
|
||||
if (await navigateToResolvedUrl(resolved)) {
|
||||
recordVisitForThread(threadRef, next);
|
||||
}
|
||||
} catch {
|
||||
// Server-side `failed` event renders the unreachable view.
|
||||
}
|
||||
},
|
||||
[navigateToResolvedUrl, threadRef.environmentId],
|
||||
[navigateToResolvedUrl, threadRef],
|
||||
);
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
@@ -680,6 +713,8 @@ export function PreviewView({
|
||||
environmentId={threadRef.environmentId}
|
||||
configuredUrls={configuredUrls}
|
||||
recentlySeenUrls={previewState.recentlySeenUrls}
|
||||
recentEntries={recentHistoryEntries}
|
||||
onRemoveRecent={(url) => removeUrlForThread(threadRef, url)}
|
||||
onOpenUrl={(next) => void handleOpenServerUrl(next)}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
|
||||
import { resolveDiscoveredServerUrl } from "~/browser/browserTargetResolver";
|
||||
import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
|
||||
import { recordVisitForThread } from "~/browserHistoryStore";
|
||||
import { useRightPanelStore } from "~/rightPanelStore";
|
||||
import { openPreviewSession } from "./openPreviewSession";
|
||||
|
||||
@@ -21,6 +22,7 @@ export async function openDiscoveredPort<E>(input: {
|
||||
url: resolvedUrl,
|
||||
});
|
||||
return mapAtomCommandResult(result, (snapshot) => {
|
||||
recordVisitForThread(input.threadRef, input.port.url);
|
||||
useRightPanelStore.getState().openBrowser(input.threadRef, snapshot.tabId);
|
||||
});
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { isPreviewableUrl } from "@t3tools/shared/preview";
|
||||
import * as Schema from "effect/Schema";
|
||||
|
||||
import type { OpenPreviewMutation } from "~/browser/openFileInPreview";
|
||||
import { recordVisitForThread } from "~/browserHistoryStore";
|
||||
import { applyPreviewServerSnapshot, isPreviewSupportedInRuntime } from "~/previewStateStore";
|
||||
import { useRightPanelStore } from "~/rightPanelStore";
|
||||
|
||||
@@ -98,6 +99,7 @@ export async function openTerminalLinkInPreview<E>(
|
||||
input.fallbackToBrowser();
|
||||
return;
|
||||
}
|
||||
recordVisitForThread(input.threadRef, input.url);
|
||||
applyPreviewServerSnapshot(input.threadRef, result.value);
|
||||
useRightPanelStore.getState().openBrowser(input.threadRef, result.value.tabId);
|
||||
return;
|
||||
|
||||
@@ -3,10 +3,13 @@ import { describe, expect, it } from "vite-plus/test";
|
||||
|
||||
import { mergeServers, type PreviewableServer } from "./useDiscoveredLocalServers";
|
||||
|
||||
const scannerServer = (overrides: Partial<DiscoveredLocalServer>): DiscoveredLocalServer => ({
|
||||
const scannerServer = (
|
||||
overrides: Partial<DiscoveredLocalServer & { requestedUrl: string }>,
|
||||
): DiscoveredLocalServer & { requestedUrl: string } => ({
|
||||
host: "localhost",
|
||||
port: 5173,
|
||||
url: "http://localhost:5173",
|
||||
requestedUrl: overrides.url ?? "http://localhost:5173",
|
||||
processName: "vite",
|
||||
pid: 1234,
|
||||
terminal: null,
|
||||
@@ -24,6 +27,7 @@ describe("mergeServers", () => {
|
||||
expect(result[0]).toMatchObject({
|
||||
host: "localhost",
|
||||
port: 5173,
|
||||
requestedUrl: "http://localhost:5173",
|
||||
source: "scanner",
|
||||
listening: true,
|
||||
processName: "vite",
|
||||
@@ -56,6 +60,7 @@ describe("mergeServers", () => {
|
||||
expect(result[0]).toMatchObject({
|
||||
source: "configured",
|
||||
listening: false,
|
||||
requestedUrl: "http://localhost:5173/",
|
||||
});
|
||||
});
|
||||
|
||||
@@ -68,6 +73,7 @@ describe("mergeServers", () => {
|
||||
expect(result.map((s) => s.port)).toEqual([5173, 8080]);
|
||||
expect(result.find((s) => s.port === 5173)?.source).toBe("scanner");
|
||||
expect(result.find((s) => s.port === 8080)?.source).toBe("recent");
|
||||
expect(result.find((s) => s.port === 8080)?.requestedUrl).toBe("http://localhost:8080/");
|
||||
});
|
||||
|
||||
it("ignores non-loopback URLs in configured/recent inputs", () => {
|
||||
@@ -102,6 +108,22 @@ describe("mergeServers", () => {
|
||||
});
|
||||
expect(result).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("keeps a scanner entry's pre-resolution requestedUrl distinct from a resolved url", () => {
|
||||
const result = mergeServers({
|
||||
scanner: [
|
||||
scannerServer({
|
||||
port: 5173,
|
||||
url: "https://env-42.example.dev:5173/",
|
||||
requestedUrl: "http://localhost:5173/",
|
||||
}),
|
||||
],
|
||||
configuredUrls: [],
|
||||
recentlySeenUrls: [],
|
||||
});
|
||||
expect(result[0]?.url).toBe("https://env-42.example.dev:5173/");
|
||||
expect(result[0]?.requestedUrl).toBe("http://localhost:5173/");
|
||||
});
|
||||
});
|
||||
|
||||
describe("PreviewableServer interface", () => {
|
||||
|
||||
@@ -13,6 +13,11 @@ export interface PreviewableServer extends DiscoveredLocalServer {
|
||||
* `configured` entry can also be `listening` when the scan enriched it.
|
||||
*/
|
||||
listening: boolean;
|
||||
/**
|
||||
* Pre-resolution loopback url. `url` is the resolved navigation target
|
||||
* (volatile on a remote environment); history must key off this instead.
|
||||
*/
|
||||
requestedUrl: string;
|
||||
}
|
||||
|
||||
interface UseDiscoveredLocalServersInput {
|
||||
@@ -36,6 +41,7 @@ export function useDiscoveredLocalServers(
|
||||
scanner: scannerSnapshot.map((server) => ({
|
||||
...server,
|
||||
url: resolveDiscoveredServerUrl(input.environmentId, server.url),
|
||||
requestedUrl: server.url,
|
||||
})),
|
||||
configuredUrls: input.configuredUrls ?? [],
|
||||
recentlySeenUrls: input.recentlySeenUrls ?? [],
|
||||
@@ -45,7 +51,7 @@ export function useDiscoveredLocalServers(
|
||||
}
|
||||
|
||||
export function mergeServers(input: {
|
||||
scanner: ReadonlyArray<DiscoveredLocalServer>;
|
||||
scanner: ReadonlyArray<DiscoveredLocalServer & { requestedUrl: string }>;
|
||||
configuredUrls: ReadonlyArray<string>;
|
||||
recentlySeenUrls: ReadonlyArray<string>;
|
||||
}): ReadonlyArray<PreviewableServer> {
|
||||
@@ -60,6 +66,7 @@ export function mergeServers(input: {
|
||||
host: parsed.host,
|
||||
port: parsed.port,
|
||||
url: parsed.url,
|
||||
requestedUrl: parsed.url,
|
||||
processName: null,
|
||||
pid: null,
|
||||
terminal: null,
|
||||
@@ -95,6 +102,7 @@ export function mergeServers(input: {
|
||||
host: parsed.host,
|
||||
port: parsed.port,
|
||||
url: parsed.url,
|
||||
requestedUrl: parsed.url,
|
||||
processName: null,
|
||||
pid: null,
|
||||
terminal: null,
|
||||
|
||||
@@ -60,7 +60,6 @@ export function BetaSettingsPanel() {
|
||||
const sidebarAutoSettleAfterDays = useClientSettings(
|
||||
(settings) => settings.sidebarAutoSettleAfterDays,
|
||||
);
|
||||
const planModeEnabled = useClientSettings((settings) => settings.planModeEnabled);
|
||||
const updateSettings = useUpdateClientSettings();
|
||||
|
||||
return (
|
||||
@@ -115,17 +114,6 @@ export function BetaSettingsPanel() {
|
||||
) : null}
|
||||
</>
|
||||
) : null}
|
||||
<SettingsRow
|
||||
{...searchableSetting("restore-plan-mode")}
|
||||
description="Legacy feature. Brings back the Build/Plan toggle in the composer along with the /plan and /default commands and the Shift+Tab shortcut. While off, every thread runs in build mode."
|
||||
control={
|
||||
<Switch
|
||||
checked={planModeEnabled}
|
||||
onCheckedChange={(checked) => updateSettings({ planModeEnabled: Boolean(checked) })}
|
||||
aria-label="Restore plan mode (legacy)"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { ArchiveIcon, ArchiveX, LoaderIcon, SettingsIcon } from "lucide-react";
|
||||
import { ArchiveIcon, ArchiveX, ChevronRightIcon, LoaderIcon, SettingsIcon } from "lucide-react";
|
||||
import { Link } from "@tanstack/react-router";
|
||||
import type { CSSProperties, ReactNode } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
@@ -79,6 +79,7 @@ import { useProjects } from "../../state/entities";
|
||||
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
|
||||
import { formatRelativeTimeLabel } from "../../timestampFormat";
|
||||
import { Button } from "../ui/button";
|
||||
import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from "../ui/collapsible";
|
||||
import {
|
||||
Dialog,
|
||||
DialogDescription,
|
||||
@@ -476,8 +477,9 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
...(settings.diffIgnoreWhitespace !== DEFAULT_UNIFIED_SETTINGS.diffIgnoreWhitespace
|
||||
? ["Diff whitespace changes"]
|
||||
: []),
|
||||
...(settings.enableAssistantStreaming !== DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming
|
||||
? ["Assistant output"]
|
||||
...(settings.enableLegacyTokenStreaming !==
|
||||
DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming
|
||||
? ["Stream token by token"]
|
||||
: []),
|
||||
...(settings.enableProviderUpdateChecks !==
|
||||
DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks
|
||||
@@ -521,7 +523,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
settings.fontSizePrompt,
|
||||
settings.fontSizeTerminal,
|
||||
settings.glassOpacity,
|
||||
settings.enableAssistantStreaming,
|
||||
settings.enableLegacyTokenStreaming,
|
||||
settings.enableProviderUpdateChecks,
|
||||
settings.sidebarProjectGroupingMode,
|
||||
settings.sidebarThreadPreviewCount,
|
||||
@@ -601,7 +603,7 @@ export function useSettingsRestore(onRestored?: () => void) {
|
||||
glassOpacity: DEFAULT_UNIFIED_SETTINGS.glassOpacity,
|
||||
sidebarThreadPreviewCount: DEFAULT_UNIFIED_SETTINGS.sidebarThreadPreviewCount,
|
||||
sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode,
|
||||
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
|
||||
enableLegacyTokenStreaming: DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming,
|
||||
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
|
||||
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
|
||||
backgroundActivityProfile: DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile,
|
||||
@@ -1504,6 +1506,96 @@ function FontFamilySettingsRow({
|
||||
);
|
||||
}
|
||||
|
||||
// Both legacy rows sit behind the fold, so a settings-search jump has to
|
||||
// expand the section before its target can mount and scroll.
|
||||
const LEGACY_FEATURE_TARGET_IDS: ReadonlySet<string> = new Set([
|
||||
"legacy-plan-mode",
|
||||
"legacy-token-streaming",
|
||||
]);
|
||||
|
||||
/**
|
||||
* Retired features kept only for users who still depend on them. Collapsed by
|
||||
* default so they stay out of the everyday settings path; a settings-search
|
||||
* jump to one of the rows unfolds the section.
|
||||
*/
|
||||
function LegacyFeaturesSection() {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
const [open, setOpen] = useState(false);
|
||||
const searchTargetId = useSettingsSearchTargetId();
|
||||
// Unfold once per search jump; tracking the handled id lets the user fold
|
||||
// the section back up without the still-set target immediately reopening it.
|
||||
const lastExpandedTargetRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (searchTargetId === null) {
|
||||
// A handled jump clears the target; forgetting it here lets a later
|
||||
// jump to the same row expand the section again.
|
||||
lastExpandedTargetRef.current = null;
|
||||
return;
|
||||
}
|
||||
if (!LEGACY_FEATURE_TARGET_IDS.has(searchTargetId)) return;
|
||||
if (lastExpandedTargetRef.current === searchTargetId) return;
|
||||
lastExpandedTargetRef.current = searchTargetId;
|
||||
setOpen(true);
|
||||
}, [searchTargetId]);
|
||||
|
||||
return (
|
||||
<section className="space-y-3">
|
||||
<Collapsible open={open} onOpenChange={setOpen}>
|
||||
<CollapsibleTrigger className="group flex min-h-8 w-full items-center gap-2 px-3 sm:px-4">
|
||||
<h2 className="text-lg font-semibold tracking-[-0.025em] text-muted-foreground transition-colors group-hover:text-foreground">
|
||||
Legacy features
|
||||
</h2>
|
||||
<ChevronRightIcon className="size-4 text-muted-foreground transition-transform duration-200 group-data-panel-open:rotate-90" />
|
||||
</CollapsibleTrigger>
|
||||
<CollapsiblePanel>
|
||||
<div className="relative space-y-1 overflow-visible pt-3 text-foreground">
|
||||
<SettingsRow
|
||||
{...searchableSetting("legacy-plan-mode")}
|
||||
description="Brings back the Build/Plan toggle in the composer along with the /plan and /default commands and the Shift+Tab shortcut. While off, every thread runs in build mode."
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.planModeEnabled}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({ planModeEnabled: Boolean(checked) })
|
||||
}
|
||||
aria-label="Plan mode (legacy)"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<SettingsRow
|
||||
{...searchableSetting("legacy-token-streaming")}
|
||||
description="Paints assistant output token by token instead of in complete chunks. Not recommended: it is significantly slower, and long responses become harder to follow. Kept only for compatibility with the old behavior."
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.enableLegacyTokenStreaming}
|
||||
onCheckedChange={(checked) => {
|
||||
if (!checked) {
|
||||
updateSettings({ enableLegacyTokenStreaming: false });
|
||||
return;
|
||||
}
|
||||
void (async () => {
|
||||
const api = readLocalApi();
|
||||
const confirmed = await (api ?? ensureLocalApi()).dialogs.confirm(
|
||||
[
|
||||
"Turn on token-by-token output?",
|
||||
"It is significantly slower than the default buffered output and hurts the reading experience. This switch exists only for backwards compatibility.",
|
||||
].join("\n"),
|
||||
);
|
||||
if (confirmed) updateSettings({ enableLegacyTokenStreaming: true });
|
||||
})();
|
||||
}}
|
||||
aria-label="Stream token by token (legacy)"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</CollapsiblePanel>
|
||||
</Collapsible>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
export function GeneralSettingsPanel() {
|
||||
const settings = usePrimarySettings();
|
||||
const updateSettings = useUpdatePrimarySettings();
|
||||
@@ -1664,33 +1756,6 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
{...searchableSetting("assistant-output")}
|
||||
description="Show token-by-token output while a response is in progress."
|
||||
resetAction={
|
||||
settings.enableAssistantStreaming !==
|
||||
DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming ? (
|
||||
<SettingResetButton
|
||||
label="assistant output"
|
||||
onClick={() =>
|
||||
updateSettings({
|
||||
enableAssistantStreaming: DEFAULT_UNIFIED_SETTINGS.enableAssistantStreaming,
|
||||
})
|
||||
}
|
||||
/>
|
||||
) : null
|
||||
}
|
||||
control={
|
||||
<Switch
|
||||
checked={settings.enableAssistantStreaming}
|
||||
onCheckedChange={(checked) =>
|
||||
updateSettings({ enableAssistantStreaming: Boolean(checked) })
|
||||
}
|
||||
aria-label="Stream assistant messages"
|
||||
/>
|
||||
}
|
||||
/>
|
||||
|
||||
<SettingsRow
|
||||
{...searchableSetting("provider-update-checks")}
|
||||
description="Check installed provider CLIs for newer available versions."
|
||||
@@ -2050,6 +2115,8 @@ export function GeneralSettingsPanel() {
|
||||
}
|
||||
/>
|
||||
</SettingsSection>
|
||||
|
||||
<LegacyFeaturesSection />
|
||||
</SettingsPageContainer>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -165,6 +165,7 @@ 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(),
|
||||
@@ -178,6 +179,7 @@ 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);
|
||||
@@ -259,6 +261,9 @@ 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
|
||||
@@ -315,6 +320,18 @@ 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[];
|
||||
@@ -330,8 +347,8 @@ export function ThemeEditorPanel({
|
||||
// comes back when the editor closes, including on cancel.
|
||||
useEffect(() => {
|
||||
if (!open || !isDraftSeeded) return;
|
||||
applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance);
|
||||
}, [activeAppearance, colorsByAppearance, isDraftSeeded, open]);
|
||||
applyThemeColorPreview(colorsByAppearance[activeAppearance], activeAppearance, sidebarArtwork);
|
||||
}, [activeAppearance, colorsByAppearance, isDraftSeeded, open, sidebarArtwork]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
@@ -646,8 +663,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,
|
||||
@@ -657,9 +674,11 @@ 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);
|
||||
@@ -677,8 +696,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,
|
||||
@@ -687,9 +706,11 @@ 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(
|
||||
@@ -702,8 +723,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,
|
||||
@@ -713,9 +734,11 @@ 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({
|
||||
@@ -723,6 +746,7 @@ export function ThemeEditorPanel({
|
||||
name,
|
||||
appearance: activeAppearance,
|
||||
colors: colorsForSave[activeAppearance],
|
||||
...(sidebarArtwork ? { sidebarArtwork: true } : {}),
|
||||
...(isAdvanced ? {} : { managed: true }),
|
||||
}),
|
||||
);
|
||||
@@ -773,6 +797,7 @@ export function ThemeEditorPanel({
|
||||
name,
|
||||
onOpenChange,
|
||||
onSaved,
|
||||
sidebarArtwork,
|
||||
simpleColorsDirtyByAppearance,
|
||||
takenAppearances,
|
||||
]);
|
||||
@@ -832,6 +857,20 @@ 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>
|
||||
@@ -1088,6 +1127,7 @@ 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,301 @@
|
||||
import {
|
||||
CheckCircle2Icon,
|
||||
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,
|
||||
} from "../../openVsxThemes";
|
||||
import {
|
||||
getCustomThemes,
|
||||
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 { Spinner } from "../ui/spinner";
|
||||
|
||||
const DOWNLOAD_FORMAT = new Intl.NumberFormat(undefined, {
|
||||
notation: "compact",
|
||||
maximumFractionDigits: 1,
|
||||
});
|
||||
const SUGGESTED_SEARCHES = ["Dracula", "Catppuccin", "Nord", "Tokyo Night"];
|
||||
|
||||
export function ThemeSearchSection({
|
||||
open,
|
||||
onInstalled,
|
||||
}: {
|
||||
open: boolean;
|
||||
onInstalled: (themes: ReadonlyArray<ThemeDefinition>, context: { updated: boolean }) => void;
|
||||
}) {
|
||||
const [query, setQuery] = useState("");
|
||||
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("");
|
||||
setResults(null);
|
||||
setError(null);
|
||||
setIsSearching(false);
|
||||
setInstallingId(null);
|
||||
setPendingUpdate(null);
|
||||
}
|
||||
return () => {
|
||||
requestRef.current?.abort();
|
||||
requestRef.current = null;
|
||||
};
|
||||
}, [open]);
|
||||
|
||||
const runSearch = useCallback(async (searchText: string) => {
|
||||
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, controller.signal);
|
||||
if (!controller.signal.aborted) setResults(nextResults);
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause instanceof Error ? cause.message : "Open VSX search failed.");
|
||||
}
|
||||
} finally {
|
||||
if (requestRef.current === controller) {
|
||||
requestRef.current = null;
|
||||
setIsSearching(false);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSearch = useCallback(
|
||||
(event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault();
|
||||
void runSearch(query);
|
||||
},
|
||||
[query, runSearch],
|
||||
);
|
||||
|
||||
const handleInstall = useCallback(
|
||||
async (extension: OpenVsxThemeExtension, allowUpdate: boolean) => {
|
||||
const updated = getCustomThemes().some(
|
||||
(theme) => theme.collection?.id === extension.collectionId,
|
||||
);
|
||||
if (updated && !allowUpdate) {
|
||||
setPendingUpdate(extension);
|
||||
return;
|
||||
}
|
||||
|
||||
requestRef.current?.abort();
|
||||
const controller = new AbortController();
|
||||
requestRef.current = controller;
|
||||
setInstallingId(extension.id);
|
||||
setError(null);
|
||||
try {
|
||||
const themes = await importOpenVsxThemeExtension(extension, controller.signal);
|
||||
if (controller.signal.aborted) return;
|
||||
const imported = replaceCustomThemeCollection(extension.collectionId, themes);
|
||||
onInstalled(imported, { updated });
|
||||
} catch (cause) {
|
||||
if (!controller.signal.aborted) {
|
||||
setError(cause instanceof Error ? cause.message : "That theme could not be added.");
|
||||
}
|
||||
} finally {
|
||||
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>
|
||||
|
||||
<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}
|
||||
|
||||
{results === null && !isSearching ? (
|
||||
<div className="flex flex-wrap items-center gap-1.5">
|
||||
<span className="mr-1 text-muted-foreground text-xs">Popular</span>
|
||||
{SUGGESTED_SEARCHES.map((suggestion) => (
|
||||
<Button
|
||||
key={suggestion}
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
onClick={() => void runSearch(suggestion)}
|
||||
>
|
||||
{suggestion}
|
||||
</Button>
|
||||
))}
|
||||
</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">
|
||||
<div className="flex size-10 shrink-0 items-center justify-center rounded-lg bg-muted text-muted-foreground">
|
||||
<PaletteIcon className="size-4" />
|
||||
</div>
|
||||
<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">
|
||||
<span className="inline-flex items-center gap-1 text-muted-foreground text-[11px]">
|
||||
<ShieldCheckIcon className="size-3" /> {extension.license}
|
||||
</span>
|
||||
<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}
|
||||
|
||||
<div className="flex items-center gap-1.5 text-muted-foreground text-[11px]">
|
||||
<CheckCircle2Icon className="size-3" /> Licensed themes only, with package integrity checks
|
||||
</div>
|
||||
|
||||
<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,4 +1,6 @@
|
||||
import {
|
||||
ChevronLeftIcon,
|
||||
ChevronRightIcon,
|
||||
CopyIcon,
|
||||
DownloadIcon,
|
||||
PenLineIcon,
|
||||
@@ -75,6 +77,7 @@ function ThemeLibraryCard({
|
||||
onDuplicate,
|
||||
onDownload,
|
||||
onRemove,
|
||||
variantNavigation,
|
||||
}: {
|
||||
theme: ThemeCardDefinition;
|
||||
isActive: boolean;
|
||||
@@ -85,6 +88,17 @@ function ThemeLibraryCard({
|
||||
onDuplicate?: () => void;
|
||||
onDownload?: () => void;
|
||||
onRemove?: () => void;
|
||||
variantNavigation?: {
|
||||
collectionLabel: string;
|
||||
index: number;
|
||||
count: number;
|
||||
activeAssignments: ReadonlyArray<{
|
||||
mode: ThemeAppearance;
|
||||
label: string;
|
||||
}>;
|
||||
onPrevious: () => void;
|
||||
onNext: () => void;
|
||||
};
|
||||
}) {
|
||||
// A one-appearance theme can only take its own side of the mix, so the card
|
||||
// tooltip promises exactly what clicking it does.
|
||||
@@ -111,11 +125,55 @@ function ThemeLibraryCard({
|
||||
onSelectMode={onUseMode}
|
||||
previews={theme.previews}
|
||||
/>
|
||||
{variantNavigation ? (
|
||||
<div
|
||||
className="flex items-center gap-1 border-t border-border/50 px-2 py-1"
|
||||
aria-label={variantNavigation.collectionLabel}
|
||||
>
|
||||
<Button
|
||||
aria-label={`Previous ${variantNavigation.collectionLabel} variant`}
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
variantNavigation.onPrevious();
|
||||
}}
|
||||
>
|
||||
<ChevronLeftIcon />
|
||||
</Button>
|
||||
<div
|
||||
className="min-w-0 flex-1 text-center text-xs text-muted-foreground"
|
||||
aria-live="polite"
|
||||
>
|
||||
<div className="truncate">
|
||||
{theme.label} · {variantNavigation.index + 1} of {variantNavigation.count}
|
||||
</div>
|
||||
{variantNavigation.activeAssignments.length > 0 ? (
|
||||
<div className="truncate text-[10px]">
|
||||
{variantNavigation.activeAssignments
|
||||
.map(({ mode, label }) => `${mode}: ${label}`)
|
||||
.join(" · ")}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
<Button
|
||||
aria-label={`Next ${variantNavigation.collectionLabel} variant`}
|
||||
size="icon-xs"
|
||||
variant="ghost"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
variantNavigation.onNext();
|
||||
}}
|
||||
>
|
||||
<ChevronRightIcon />
|
||||
</Button>
|
||||
</div>
|
||||
) : null}
|
||||
<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 +182,7 @@ function ThemeLibraryCard({
|
||||
onUse();
|
||||
}}
|
||||
>
|
||||
{theme.label}
|
||||
{variantNavigation?.collectionLabel ?? theme.label}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -224,6 +282,73 @@ function ThemeLibraryCard({
|
||||
);
|
||||
}
|
||||
|
||||
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 activeAssignments = (["light", "dark"] as const).flatMap((mode) => {
|
||||
const assignedTheme = themes.find((candidate) => activeModesFor(candidate.id).includes(mode));
|
||||
return assignedTheme ? [{ mode, label: assignedTheme.label }] : [];
|
||||
});
|
||||
const move = (offset: number) => {
|
||||
setVariantIndex((current) => (current + offset + themes.length) % themes.length);
|
||||
};
|
||||
|
||||
return (
|
||||
<ThemeLibraryCard
|
||||
activeModes={activeModesFor(theme.id)}
|
||||
isActive={false}
|
||||
onDownload={() => onDownload(theme)}
|
||||
onDuplicate={() => onDuplicate(theme)}
|
||||
onEdit={() => onEdit(theme)}
|
||||
onRemove={() => onRemove(theme)}
|
||||
onUse={() => onUse(theme)}
|
||||
onUseMode={(mode) => onUseMode(theme, mode)}
|
||||
theme={getThemeCardDefinition(theme)}
|
||||
{...(themes.length > 1
|
||||
? {
|
||||
variantNavigation: {
|
||||
collectionLabel,
|
||||
index: safeIndex,
|
||||
count: themes.length,
|
||||
activeAssignments,
|
||||
onPrevious: () => move(-1),
|
||||
onNext: () => move(1),
|
||||
},
|
||||
}
|
||||
: {})}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function ThemeLibrary({
|
||||
theme,
|
||||
setTheme,
|
||||
@@ -460,6 +585,18 @@ export function ThemeLibrary({
|
||||
</div>
|
||||
);
|
||||
|
||||
const customThemeCollections = [
|
||||
...customThemes
|
||||
.reduce((groups, customTheme) => {
|
||||
const groupId = 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
|
||||
@@ -501,43 +638,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={handleRemoveTheme}
|
||||
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>
|
||||
);
|
||||
@@ -553,9 +686,8 @@ 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
|
||||
className="h-7 rounded-md border border-border/70 bg-muted/30 px-2 text-xs font-medium text-foreground shadow-none hover:bg-accent/40"
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
onClick={() =>
|
||||
@@ -579,19 +711,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({
|
||||
|
||||
@@ -110,11 +110,6 @@ export const SETTINGS_SEARCH_ITEMS = [
|
||||
title: "Hide whitespace changes",
|
||||
to: "/settings/general",
|
||||
},
|
||||
{
|
||||
id: "assistant-output",
|
||||
title: "Assistant output",
|
||||
to: "/settings/general",
|
||||
},
|
||||
{
|
||||
id: "provider-update-checks",
|
||||
title: "Provider update checks",
|
||||
@@ -156,6 +151,16 @@ export const SETTINGS_SEARCH_ITEMS = [
|
||||
title: "Diagnostics",
|
||||
to: "/settings/general",
|
||||
},
|
||||
{
|
||||
id: "legacy-plan-mode",
|
||||
title: "Plan mode (legacy)",
|
||||
to: "/settings/general",
|
||||
},
|
||||
{
|
||||
id: "legacy-token-streaming",
|
||||
title: "Stream token by token (legacy)",
|
||||
to: "/settings/general",
|
||||
},
|
||||
{
|
||||
id: "keybindings",
|
||||
title: "Keybindings",
|
||||
@@ -187,11 +192,6 @@ export const SETTINGS_SEARCH_ITEMS = [
|
||||
to: "/settings/beta",
|
||||
targetId: "sidebar-v2",
|
||||
},
|
||||
{
|
||||
id: "restore-plan-mode",
|
||||
title: "Restore plan mode (legacy)",
|
||||
to: "/settings/beta",
|
||||
},
|
||||
{
|
||||
id: "archive",
|
||||
title: "Archived threads",
|
||||
|
||||
@@ -279,6 +279,11 @@ describe("environment grouping", () => {
|
||||
expect(physicalToLogicalKey.get(derivePhysicalProjectKey(staleWithoutRepositoryIdentity))).toBe(
|
||||
repositoryIdentity.canonicalKey,
|
||||
);
|
||||
// Deriving from the stale project alone misses the identity its sibling
|
||||
// carries, so consumers must go through the map to match the sidebar.
|
||||
expect(
|
||||
deriveLogicalProjectKeyFromSettings(staleWithoutRepositoryIdentity, defaultGroupingSettings),
|
||||
).not.toBe(repositoryIdentity.canonicalKey);
|
||||
});
|
||||
|
||||
it("builds one picker entry per logical project and targets the preferred environment", () => {
|
||||
|
||||
@@ -17,6 +17,37 @@ describe("resolveEnvironmentIdentificationMode", () => {
|
||||
"pill",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses a pill instead of artwork with a palette theme", () => {
|
||||
expect(
|
||||
resolveEnvironmentIdentificationMode({
|
||||
mode: "artwork",
|
||||
settingsHydrated: true,
|
||||
paletteThemeActive: true,
|
||||
}),
|
||||
).toBe("pill");
|
||||
});
|
||||
|
||||
it("respects none with a palette theme", () => {
|
||||
expect(
|
||||
resolveEnvironmentIdentificationMode({
|
||||
mode: "none",
|
||||
settingsHydrated: true,
|
||||
paletteThemeActive: true,
|
||||
}),
|
||||
).toBe("none");
|
||||
});
|
||||
|
||||
it("keeps artwork when the palette theme opts into it", () => {
|
||||
expect(
|
||||
resolveEnvironmentIdentificationMode({
|
||||
mode: "artwork",
|
||||
settingsHydrated: true,
|
||||
paletteThemeActive: true,
|
||||
paletteThemeAllowsArtwork: true,
|
||||
}),
|
||||
).toBe("artwork");
|
||||
});
|
||||
});
|
||||
|
||||
describe("mergeEnvironmentSettings", () => {
|
||||
|
||||
@@ -28,10 +28,17 @@ import { safeErrorLogAttributes } from "@t3tools/client-runtime/errors";
|
||||
import { APP_STAGE_LABEL } from "~/branding";
|
||||
import { resolveSidebarV2Enabled } from "~/branding.logic";
|
||||
import { ensureLocalApi } from "~/localApi";
|
||||
import {
|
||||
getThemeDefinition,
|
||||
getThemePreviewSidebarArtwork,
|
||||
resolveThemeHalf,
|
||||
subscribeToThemePreview,
|
||||
} from "~/themePalette";
|
||||
import * as Struct from "effect/Struct";
|
||||
import { primaryServerSettingsAtom, serverEnvironment } from "~/state/server";
|
||||
import { usePrimaryEnvironment } from "~/state/environments";
|
||||
import { useAtomCommand } from "~/state/use-atom-command";
|
||||
import { useTheme } from "./useTheme";
|
||||
|
||||
const CLIENT_SETTINGS_PERSISTENCE_ERROR_SCOPE = "[CLIENT_SETTINGS]";
|
||||
|
||||
@@ -226,15 +233,36 @@ export function useClientSettings<T = ClientSettings>(
|
||||
export function resolveEnvironmentIdentificationMode(input: {
|
||||
mode: EnvironmentIdentificationMode;
|
||||
settingsHydrated: boolean;
|
||||
paletteThemeActive?: boolean;
|
||||
paletteThemeAllowsArtwork?: boolean;
|
||||
}): EnvironmentIdentificationMode {
|
||||
// Avoid briefly rendering the default artwork before a persisted pill/none choice loads.
|
||||
return input.settingsHydrated ? input.mode : "none";
|
||||
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.
|
||||
return input.paletteThemeActive && !input.paletteThemeAllowsArtwork && input.mode === "artwork"
|
||||
? "pill"
|
||||
: input.mode;
|
||||
}
|
||||
|
||||
export function useEnvironmentIdentificationMode(): EnvironmentIdentificationMode {
|
||||
const settingsHydrated = useClientSettingsHydrated();
|
||||
const mode = useClientSettingsValue().environmentIdentificationMode;
|
||||
return resolveEnvironmentIdentificationMode({ mode, settingsHydrated });
|
||||
const { resolvedTheme, theme, themeHalves } = useTheme();
|
||||
const previewSidebarArtwork = useSyncExternalStore(
|
||||
subscribeToThemePreview,
|
||||
getThemePreviewSidebarArtwork,
|
||||
() => null,
|
||||
);
|
||||
const activeTheme = resolveThemeHalf(theme, themeHalves, resolvedTheme);
|
||||
const activeThemeDefinition = getThemeDefinition(activeTheme);
|
||||
return resolveEnvironmentIdentificationMode({
|
||||
mode,
|
||||
settingsHydrated,
|
||||
paletteThemeActive: previewSidebarArtwork !== null || activeThemeDefinition !== null,
|
||||
paletteThemeAllowsArtwork:
|
||||
previewSidebarArtwork ?? activeThemeDefinition?.sidebarArtwork === true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,396 @@
|
||||
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 } 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",
|
||||
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: "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("/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(".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("/demo/theme/1.0.0/file/package.json")) {
|
||||
return new Response(
|
||||
JSON.stringify({ 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,
|
||||
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("size")).toBe("16");
|
||||
});
|
||||
|
||||
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("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/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,
|
||||
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(paired.colors.canvas).toBe("#fafafa");
|
||||
expect(getThemeColorsForMode(paired, "dark")!.canvas).toBe("#111111");
|
||||
expect(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.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,
|
||||
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,
|
||||
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");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,723 @@
|
||||
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 OpenVsxThemeExtension = {
|
||||
id: string;
|
||||
collectionId: string;
|
||||
name: string;
|
||||
publisher: string;
|
||||
description: string;
|
||||
downloadCount: number;
|
||||
manifestUrl: string;
|
||||
sha256Url: string;
|
||||
vsixUrl: string;
|
||||
version: string;
|
||||
license: string;
|
||||
};
|
||||
|
||||
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 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 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,
|
||||
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?: AbortSignal,
|
||||
): 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");
|
||||
// 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);
|
||||
const candidates = isRecord(value) && Array.isArray(value.extensions) ? value.extensions : [];
|
||||
const identities = candidates.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");
|
||||
const packageLength = Number(packageResponse.headers.get("content-length"));
|
||||
if (
|
||||
packageResponse.ok &&
|
||||
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 ? 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 = {
|
||||
compressedSize?: unknown;
|
||||
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 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 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.");
|
||||
|
||||
let totalUncompressed = 0;
|
||||
for (const entry of entries) {
|
||||
if (entry.unsafeOriginalName) normalizePackagePath(entry.unsafeOriginalName);
|
||||
if (entry.dir) continue;
|
||||
const compressed = entry._data?.compressedSize;
|
||||
const uncompressed = entry._data?.uncompressedSize;
|
||||
if (typeof compressed !== "number" || typeof uncompressed !== "number") {
|
||||
throw new Error("That extension package has unreadable file 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.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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 (
|
||||
typeof packagedManifest.license !== "string" ||
|
||||
packagedManifest.license.trim().toLowerCase() !== extension.license.toLowerCase()
|
||||
) {
|
||||
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") 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 (parsed.length === 0) {
|
||||
throw new Error(failures[0] ?? "That extension has no compatible color themes.");
|
||||
}
|
||||
const extensionId = extension.id.toLowerCase();
|
||||
const resolved = resolveThemeLabelCollisions(parsed).map((theme, index) => ({
|
||||
...theme,
|
||||
id: openVsxThemeId(extensionId, parsed[index]!.sourcePath),
|
||||
}));
|
||||
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 }));
|
||||
}
|
||||
@@ -1,9 +1,12 @@
|
||||
import { describe, expect, it, vi } from "vite-plus/test";
|
||||
|
||||
import {
|
||||
applyThemeColorPreview,
|
||||
applyThemePalette,
|
||||
getThemeColorsForMode,
|
||||
getThemeDefinition,
|
||||
getThemeModes,
|
||||
getThemePreviewSidebarArtwork,
|
||||
getThemePreferenceMode,
|
||||
isKnownThemePreference,
|
||||
getCustomThemes,
|
||||
@@ -12,9 +15,11 @@ import {
|
||||
canonicalThemePreference,
|
||||
parseThemeFile,
|
||||
parseThemeHalves,
|
||||
replaceCustomThemeCollection,
|
||||
resolveDesktopTheme,
|
||||
resolveThemeAppearance,
|
||||
serializeThemeFile,
|
||||
subscribeToThemePreview,
|
||||
subscribeToCustomThemes,
|
||||
T3_CHAT_THEME,
|
||||
EMBER_THEME,
|
||||
@@ -191,13 +196,68 @@ describe("theme files", () => {
|
||||
});
|
||||
|
||||
it("serializes a theme back into the importable file shape", () => {
|
||||
const serialized = serializeThemeFile(T3_CHAT_THEME);
|
||||
const theme = {
|
||||
...parseThemeFile({
|
||||
version: THEME_FILE_VERSION,
|
||||
id: "community-demo",
|
||||
name: "Community Demo",
|
||||
appearance: "dark",
|
||||
colors: { canvas: "#111111" },
|
||||
}),
|
||||
collection: { id: "open-vsx:demo.theme", label: "Demo Theme" },
|
||||
};
|
||||
const serialized = serializeThemeFile(theme);
|
||||
expect(JSON.parse(serialized)).toMatchObject({
|
||||
version: THEME_FILE_VERSION,
|
||||
id: T3_CHAT_THEME.id,
|
||||
name: T3_CHAT_THEME.label,
|
||||
appearance: "light",
|
||||
id: theme.id,
|
||||
name: theme.label,
|
||||
appearance: "dark",
|
||||
collection: theme.collection,
|
||||
});
|
||||
expect(parseThemeFile(JSON.parse(serialized)).collection).toEqual(theme.collection);
|
||||
});
|
||||
|
||||
it("keeps sidebar artwork opt-in through theme files", () => {
|
||||
const withoutArtwork = parseThemeFile({
|
||||
version: THEME_FILE_VERSION,
|
||||
name: "Plain sidebar",
|
||||
appearance: "light",
|
||||
colors: { accent: "#5b6cff" },
|
||||
});
|
||||
const withArtwork = parseThemeFile({
|
||||
version: THEME_FILE_VERSION,
|
||||
name: "Art sidebar",
|
||||
appearance: "light",
|
||||
colors: { accent: "#5b6cff" },
|
||||
sidebarArtwork: true,
|
||||
});
|
||||
|
||||
expect(withoutArtwork.sidebarArtwork).toBeUndefined();
|
||||
expect(withArtwork.sidebarArtwork).toBe(true);
|
||||
expect(JSON.parse(serializeThemeFile(withArtwork)).sidebarArtwork).toBe(true);
|
||||
});
|
||||
|
||||
it("publishes sidebar artwork changes from the live theme preview", () => {
|
||||
const listener = vi.fn();
|
||||
const unsubscribe = subscribeToThemePreview(listener);
|
||||
vi.stubGlobal("document", {
|
||||
documentElement: {
|
||||
classList: { toggle: vi.fn() },
|
||||
dataset: {},
|
||||
style: { removeProperty: vi.fn(), setProperty: vi.fn() },
|
||||
},
|
||||
});
|
||||
|
||||
applyThemeColorPreview(T3_CHAT_THEME.colors, "light", true);
|
||||
expect(getThemePreviewSidebarArtwork()).toBe(true);
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
|
||||
applyThemePalette("system");
|
||||
expect(getThemePreviewSidebarArtwork()).toBeNull();
|
||||
expect(listener).toHaveBeenCalledTimes(2);
|
||||
|
||||
unsubscribe();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it("keeps optional light and dark palettes under one theme id", () => {
|
||||
@@ -370,6 +430,110 @@ describe("theme files", () => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
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 stored = new Map<string, string>([
|
||||
[
|
||||
CUSTOM_THEMES_STORAGE_KEY,
|
||||
JSON.stringify([
|
||||
{ id: "personal", label: "Personal", appearance: "dark", colors: { canvas: "#111111" } },
|
||||
{
|
||||
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 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)).toEqual(replacement);
|
||||
expect(getCustomThemes().map((theme) => theme.id)).toEqual([
|
||||
"personal",
|
||||
"old-light",
|
||||
"new-dark",
|
||||
]);
|
||||
expect(setItem).toHaveBeenCalledTimes(1);
|
||||
|
||||
vi.unstubAllGlobals();
|
||||
invalidateCustomThemes();
|
||||
});
|
||||
|
||||
it("updates a personal theme without changing its id", () => {
|
||||
const stored = new Map<string, string>();
|
||||
vi.stubGlobal("window", {
|
||||
@@ -387,6 +551,7 @@ describe("theme files", () => {
|
||||
name: "Aurora",
|
||||
appearance: "light",
|
||||
colors: { canvas: "#f8fbff", accent: "#5b6cff" },
|
||||
sidebarArtwork: true,
|
||||
}),
|
||||
);
|
||||
const updatedTheme = updateCustomTheme({
|
||||
@@ -395,11 +560,17 @@ describe("theme files", () => {
|
||||
colors: { ...createdTheme.colors, accent: "#7c3aed" },
|
||||
});
|
||||
|
||||
expect(updatedTheme).toMatchObject({ id: "aurora", label: "Aurora Night" });
|
||||
expect(updatedTheme).toMatchObject({
|
||||
id: "aurora",
|
||||
label: "Aurora Night",
|
||||
sidebarArtwork: true,
|
||||
});
|
||||
invalidateCustomThemes();
|
||||
expect(getCustomThemes()).toEqual([updatedTheme]);
|
||||
expect(JSON.parse(stored.get(CUSTOM_THEMES_STORAGE_KEY) ?? "[]")[0]).toMatchObject({
|
||||
id: "aurora",
|
||||
label: "Aurora Night",
|
||||
sidebarArtwork: true,
|
||||
});
|
||||
|
||||
vi.unstubAllGlobals();
|
||||
|
||||
@@ -90,12 +90,17 @@ export type ThemeColorOverrides = Readonly<Partial<Record<ThemeColorRole, string
|
||||
export type ThemeVariants = Readonly<Partial<Record<ThemeAppearance, ThemeColors>>>;
|
||||
export type ThemeVariantOverrides = Readonly<Partial<Record<ThemeAppearance, ThemeColorOverrides>>>;
|
||||
export type ThemePreferenceMode = ThemeAppearance | "system";
|
||||
export type ThemeCollection = Readonly<{ id: string; label: string }>;
|
||||
export type ThemeDefinition = Readonly<{
|
||||
id: string;
|
||||
label: string;
|
||||
appearance: ThemeAppearance;
|
||||
colors: ThemeColors;
|
||||
variants?: ThemeVariants;
|
||||
/** Groups related imported variants into one library card. */
|
||||
collection?: ThemeCollection;
|
||||
/** Allows fixed Dev/Nightly artwork to render over this theme's sidebar. */
|
||||
sidebarArtwork?: boolean;
|
||||
/** True when the palette was generated by the guided editor from its
|
||||
* canvas and accent; such themes reopen in guided mode. */
|
||||
managed?: boolean;
|
||||
@@ -107,6 +112,8 @@ export type ThemeFile = Readonly<{
|
||||
appearance: ThemeAppearance;
|
||||
colors: ThemeColorOverrides;
|
||||
variants?: ThemeVariantOverrides;
|
||||
collection?: ThemeCollection;
|
||||
sidebarArtwork?: boolean;
|
||||
managed?: boolean;
|
||||
}>;
|
||||
|
||||
@@ -128,6 +135,23 @@ const RESERVED_THEME_IDS = new Set([
|
||||
|
||||
const customThemeListeners = new Set<() => void>();
|
||||
let customThemesSnapshot: ReadonlyArray<ThemeDefinition> | null = null;
|
||||
const themePreviewListeners = new Set<() => void>();
|
||||
let themePreviewSidebarArtwork: boolean | null = null;
|
||||
|
||||
export function getThemePreviewSidebarArtwork(): boolean | null {
|
||||
return themePreviewSidebarArtwork;
|
||||
}
|
||||
|
||||
export function subscribeToThemePreview(listener: () => void): () => void {
|
||||
themePreviewListeners.add(listener);
|
||||
return () => themePreviewListeners.delete(listener);
|
||||
}
|
||||
|
||||
function setThemePreviewSidebarArtwork(next: boolean | null): void {
|
||||
if (themePreviewSidebarArtwork === next) return;
|
||||
themePreviewSidebarArtwork = next;
|
||||
for (const listener of themePreviewListeners) listener();
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
@@ -152,6 +176,15 @@ function isThemeLabel(value: unknown): value is string {
|
||||
return typeof value === "string" && value.trim().length > 0 && value.trim().length <= 48;
|
||||
}
|
||||
|
||||
function parseThemeCollection(value: unknown): ThemeCollection | undefined {
|
||||
return isRecord(value) &&
|
||||
typeof value.id === "string" &&
|
||||
/^[a-z0-9][a-z0-9.:-]{0,127}$/i.test(value.id) &&
|
||||
isThemeLabel(value.label)
|
||||
? { id: value.id, label: value.label.trim() }
|
||||
: undefined;
|
||||
}
|
||||
|
||||
function parseStoredThemeColors(value: unknown, appearance: ThemeAppearance): ThemeColors | null {
|
||||
if (!isRecord(value)) return null;
|
||||
|
||||
@@ -196,6 +229,7 @@ function parseStoredTheme(value: unknown): ThemeDefinition | null {
|
||||
if (!colors) return null;
|
||||
const variants = parseStoredThemeVariants(value.variants, value.appearance);
|
||||
if (value.variants !== undefined && variants === null) return null;
|
||||
const collection = parseThemeCollection(value.collection);
|
||||
|
||||
return {
|
||||
id: value.id,
|
||||
@@ -203,6 +237,8 @@ function parseStoredTheme(value: unknown): ThemeDefinition | null {
|
||||
appearance: value.appearance,
|
||||
colors,
|
||||
...(variants ? { variants } : {}),
|
||||
...(collection ? { collection } : {}),
|
||||
...(value.sidebarArtwork === true ? { sidebarArtwork: true } : {}),
|
||||
...(value.managed === true ? { managed: true } : {}),
|
||||
};
|
||||
}
|
||||
@@ -1464,6 +1500,42 @@ export function updateCustomTheme(theme: ThemeDefinition): ThemeDefinition {
|
||||
return theme;
|
||||
}
|
||||
|
||||
export function replaceCustomThemeCollection(
|
||||
collectionId: string,
|
||||
themes: ReadonlyArray<ThemeDefinition>,
|
||||
): ReadonlyArray<ThemeDefinition> {
|
||||
if (themes.length === 0) throw new Error("A theme collection cannot be empty.");
|
||||
|
||||
const validated = themes.map((theme) => parseStoredTheme(theme));
|
||||
if (
|
||||
validated.some((theme) => theme === null || theme.collection?.id !== collectionId) ||
|
||||
new Set(validated.map((theme) => theme?.id)).size !== validated.length
|
||||
) {
|
||||
throw new Error("That theme collection is invalid.");
|
||||
}
|
||||
const replacement = validated as ThemeDefinition[];
|
||||
const current = getCustomThemes();
|
||||
const firstCollectionIndex = current.findIndex((theme) => theme.collection?.id === collectionId);
|
||||
const withoutCollection = current.filter((theme) => theme.collection?.id !== collectionId);
|
||||
const occupiedIds = new Set([
|
||||
...BUILT_IN_THEME_DEFINITIONS.map((theme) => theme.id),
|
||||
...withoutCollection.map((theme) => theme.id),
|
||||
]);
|
||||
const conflictingTheme = replacement.find(
|
||||
(theme) => RESERVED_THEME_IDS.has(theme.id) || occupiedIds.has(theme.id),
|
||||
);
|
||||
if (conflictingTheme) {
|
||||
throw new Error(`A theme named "${conflictingTheme.label}" is already installed.`);
|
||||
}
|
||||
|
||||
const insertionIndex =
|
||||
firstCollectionIndex === -1 ? withoutCollection.length : firstCollectionIndex;
|
||||
const nextThemes = [...withoutCollection];
|
||||
nextThemes.splice(insertionIndex, 0, ...replacement);
|
||||
saveCustomThemes(nextThemes);
|
||||
return replacement;
|
||||
}
|
||||
|
||||
export function removeCustomTheme(themeId: string): void {
|
||||
const nextThemes = getCustomThemes().filter((theme) => theme.id !== themeId);
|
||||
if (nextThemes.length === getCustomThemes().length) return;
|
||||
@@ -1515,6 +1587,10 @@ export function parseThemeFile(value: unknown): ThemeDefinition {
|
||||
}
|
||||
|
||||
const overrides = parseThemeColorOverrides(rawColors);
|
||||
const collection = parseThemeCollection(value.collection);
|
||||
if (value.collection !== undefined && !collection) {
|
||||
throw new Error("Theme collections need a valid id and label.");
|
||||
}
|
||||
|
||||
const fallback = getDefaultThemeColors(appearance);
|
||||
const variants: Partial<Record<ThemeAppearance, ThemeColors>> = {};
|
||||
@@ -1541,6 +1617,8 @@ export function parseThemeFile(value: unknown): ThemeDefinition {
|
||||
appearance,
|
||||
colors: { ...fallback, ...overrides },
|
||||
...(Object.keys(variants).length > 0 ? { variants } : {}),
|
||||
...(collection ? { collection } : {}),
|
||||
...(value.sidebarArtwork === true ? { sidebarArtwork: true } : {}),
|
||||
...(value.managed === true ? { managed: true } : {}),
|
||||
};
|
||||
}
|
||||
@@ -1553,6 +1631,8 @@ export function serializeThemeFile(theme: ThemeDefinition): string {
|
||||
appearance: theme.appearance,
|
||||
colors: theme.colors,
|
||||
...(theme.variants ? { variants: theme.variants } : {}),
|
||||
...(theme.collection ? { collection: theme.collection } : {}),
|
||||
...(theme.sidebarArtwork ? { sidebarArtwork: true } : {}),
|
||||
...(theme.managed ? { managed: true } : {}),
|
||||
};
|
||||
return `${JSON.stringify(file, null, 2)}\n`;
|
||||
@@ -1630,11 +1710,16 @@ export const THEME_PREVIEW_ID = "__preview";
|
||||
* can be judged against the real interface instead of a miniature. Callers
|
||||
* restore the stored theme (refreshTheme) when the draft goes away.
|
||||
*/
|
||||
export function applyThemeColorPreview(colors: ThemeColors, appearance: ThemeAppearance): void {
|
||||
export function applyThemeColorPreview(
|
||||
colors: ThemeColors,
|
||||
appearance: ThemeAppearance,
|
||||
sidebarArtwork = false,
|
||||
): void {
|
||||
if (typeof document === "undefined") return;
|
||||
const root = document.documentElement;
|
||||
if (!root?.style) return;
|
||||
|
||||
setThemePreviewSidebarArtwork(sidebarArtwork);
|
||||
root.dataset.themeId = THEME_PREVIEW_ID;
|
||||
root.classList.toggle("dark", appearance === "dark");
|
||||
for (const [role, value] of Object.entries(colors) as Array<[ThemeColorRole, string]>) {
|
||||
@@ -1649,6 +1734,7 @@ export function applyThemePalette(theme: ThemePreference, appearance?: ThemeAppe
|
||||
const root = document.documentElement;
|
||||
if (!root?.style) return;
|
||||
|
||||
setThemePreviewSidebarArtwork(null);
|
||||
const palette = getThemeDefinition(theme);
|
||||
|
||||
if (palette) {
|
||||
|
||||
@@ -336,6 +336,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 +374,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,
|
||||
|
||||
@@ -538,7 +538,12 @@ export const BackgroundActivitySettings = Schema.Struct({
|
||||
export type BackgroundActivitySettings = typeof BackgroundActivitySettings.Type;
|
||||
|
||||
export const ServerSettings = Schema.Struct({
|
||||
enableAssistantStreaming: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
|
||||
// Legacy token-by-token assistant output. Deliberately a fresh key (was
|
||||
// `enableAssistantStreaming`): decoding drops the old key, so everyone,
|
||||
// including prior opt-ins, resets to the buffered default.
|
||||
enableLegacyTokenStreaming: Schema.Boolean.pipe(
|
||||
Schema.withDecodingDefault(Effect.succeed(false)),
|
||||
),
|
||||
enableProviderUpdateChecks: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
|
||||
backgroundActivity: BackgroundActivitySettings,
|
||||
// Legacy flat fields retained for old settings files and old clients. New
|
||||
@@ -701,7 +706,7 @@ const OpenCodeSettingsPatch = Schema.Struct({
|
||||
|
||||
export const ServerSettingsPatch = Schema.Struct({
|
||||
// Server settings
|
||||
enableAssistantStreaming: Schema.optionalKey(Schema.Boolean),
|
||||
enableLegacyTokenStreaming: Schema.optionalKey(Schema.Boolean),
|
||||
enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean),
|
||||
backgroundActivity: Schema.optionalKey(
|
||||
Schema.Struct({
|
||||
|
||||
Generated
+9
@@ -542,6 +542,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])
|
||||
@@ -572,6 +575,12 @@ importers:
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user