feat(desktop): add favicons to the Browser panel (#5644)

This commit is contained in:
Chris Deeming authored and GitHub committed 2026-08-13 22:02:09 -04:00
1 parent e15f655ba4
commit 710fd0eeb3
28 files changed
+4189 -71

No files matched your search

@@ -180,4 +180,135 @@ describe("browser target resolver", () => {
const { resolveDiscoveredServerUrl } = await import("./browserTargetResolver");
expect(resolveDiscoveredServerUrl(EnvironmentId.make("environment-1"), " ")).toBe(" ");
});
it("classifies exact private IPv4 and IPv6 boundaries", async () => {
const { isPrivateNetworkHost } = await import("./browserTargetResolver");
const privateHosts = [
"0.0.0.0",
"10.0.0.0",
"10.255.255.255",
"100.64.0.0",
"100.127.255.255",
"127.0.0.0",
"127.255.255.255",
"169.254.0.0",
"169.254.255.255",
"172.16.0.0",
"172.31.255.255",
"192.168.0.0",
"192.168.255.255",
"198.18.0.0",
"198.19.255.255",
"fc00::",
"fdff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
"fe80::",
"febf:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
"::ffff:192.168.1.1",
"localhost.",
"localhost..",
"devbox.",
"devbox..",
"printer.local.",
"printer.local..",
"printer.home.arpa.",
"printer.home.arpa..",
"devbox.example.ts.net.",
"devbox.example.ts.net..",
];
const publicHosts = [
"1.0.0.0",
"100.63.255.255",
"100.128.0.0",
"169.253.255.255",
"169.255.0.0",
"172.15.255.255",
"172.32.0.0",
"192.167.255.255",
"192.169.0.0",
"198.17.255.255",
"198.20.0.0",
"fbff:ffff::",
"fec0::",
"2001:4860:4860::8888",
"::ffff:8.8.8.8",
"example.com.",
];
expect(privateHosts.filter((host) => !isPrivateNetworkHost(host))).toEqual([]);
expect(publicHosts.filter(isPrivateNetworkHost)).toEqual([]);
});
it("allows only globally routable hosts to reach a public favicon provider", async () => {
const { isPublicFaviconHost } = await import("./browserTargetResolver");
const nonPublic = [
"192.0.0.0",
"192.0.0.255",
"192.0.2.0",
"192.0.2.255",
"192.88.99.0",
"192.88.99.255",
"198.51.100.0",
"198.51.100.255",
"203.0.113.0",
"203.0.113.255",
"224.0.0.0",
"255.255.255.255",
"::2",
"100::",
"100::ffff:ffff:ffff:ffff",
"100:0:0:1::",
"100:0:0:1:ffff:ffff:ffff:ffff",
"64:ff9b:1::1",
"64:ff9b::a00:1",
"64:ff9b::7f00:1",
"64:ff9b::c0a8:101",
"64:ff9b::c000:201",
"2001:5::1",
"2001:2::",
"2001:2:0:ffff:ffff:ffff:ffff:ffff",
"2001:db8::",
"2001:db8:ffff:ffff:ffff:ffff:ffff:ffff",
"3fff::",
"3fff:fff:ffff:ffff:ffff:ffff:ffff:ffff",
"5f00::1",
"fec0::",
"ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
"::ffff:192.0.2.1",
"app.test",
"app.test..",
"printer.local..",
"printer.home.arpa..",
"devbox.example.ts.net..",
"127.0.0.1..",
"127.1..",
"10.1..",
"172.16.1..",
"192.168.1..",
"service.internal",
"hidden.onion",
];
const publicHosts = [
"191.255.255.255",
"192.0.1.255",
"192.0.3.0",
"198.51.99.255",
"198.51.101.0",
"203.0.112.255",
"203.0.114.0",
"223.255.255.255",
"1.1.1.1",
"2001:4860:4860::8888",
"2606:4700:4700::1111",
"64:ff9b::808:808",
"2001:1::1",
"2001:3::1",
"2001:4:112::1",
"2001:20::1",
"2001:30::1",
"::ffff:8.8.8.8",
"example.com",
"example.com.",
];
expect(nonPublic.filter(isPublicFaviconHost)).toEqual([]);
expect(publicHosts.filter((host) => !isPublicFaviconHost(host))).toEqual([]);
});
});
+121 -13
View File
@@ -8,7 +8,10 @@ import { isLoopbackHost, normalizePreviewUrl } from "@t3tools/shared/preview";
import { readPreparedConnection } from "~/state/session";
export const normalizeHostname = (host: string): string =>
host.toLowerCase().replace(/^\[|\]$/g, "");
host
.toLowerCase()
.replace(/^\[|\]$/g, "")
.replace(/\.+$/u, "");
const parseIpv4Address = (host: string): readonly number[] | null => {
const parts = normalizeHostname(host).split(".").map(Number);
@@ -18,28 +21,91 @@ const parseIpv4Address = (host: string): readonly number[] | null => {
: null;
};
const parseIpv4MappedIpv6Address = (host: string): readonly number[] | null => {
const normalized = normalizeHostname(host);
if (!normalized.startsWith("::ffff:")) return null;
const suffix = normalized.slice("::ffff:".length);
const dotted = parseIpv4Address(suffix);
if (dotted) return dotted;
const hextets = suffix.split(":");
if (hextets.length !== 2 || hextets.some((part) => !/^[\da-f]{1,4}$/u.test(part))) return null;
const high = Number.parseInt(hextets[0]!, 16);
const low = Number.parseInt(hextets[1]!, 16);
return [high >>> 8, high & 0xff, low >>> 8, low & 0xff];
};
const parseIpv6Address = (host: string): readonly number[] | null => {
const normalized = normalizeHostname(host);
if (!normalized.includes(":")) return null;
const halves = normalized.split("::");
if (halves.length > 2) return null;
const head = halves[0] ? halves[0].split(":") : [];
const tail = halves[1] ? halves[1].split(":") : [];
if ([...head, ...tail].some((part) => !/^[\da-f]{1,4}$/u.test(part))) return null;
const missing = 8 - head.length - tail.length;
if ((halves.length === 1 && missing !== 0) || (halves.length === 2 && missing < 1)) return null;
return [...head, ...Array.from({ length: missing }, () => "0"), ...tail].map((part) =>
Number.parseInt(part, 16),
);
};
const ipv6PrefixMatches = (
address: readonly number[],
prefix: readonly number[],
prefixLength: number,
): boolean => {
const fullHextets = Math.floor(prefixLength / 16);
if (address.slice(0, fullHextets).some((part, index) => part !== prefix[index])) return false;
const remainingBits = prefixLength % 16;
if (remainingBits === 0) return true;
const mask = (0xffff << (16 - remainingBits)) & 0xffff;
return (address[fullHextets]! & mask) === (prefix[fullHextets]! & mask);
};
const isPrivateIpv4Address = (parts: readonly number[]): boolean =>
parts[0] === 0 ||
parts[0] === 10 ||
parts[0] === 127 ||
(parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) ||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
(parts[0] === 192 && parts[1] === 168) ||
(parts[0] === 169 && parts[1] === 254) ||
(parts[0] === 198 && parts[1]! >= 18 && parts[1]! <= 19);
const isSpecialPurposeIpv4Address = (parts: readonly number[]): boolean =>
isPrivateIpv4Address(parts) ||
parts[0]! >= 224 ||
// Deliberately suppress the whole protocol-assignment block. IANA marks
// .9 and .10 globally reachable, but privacy-safe false negatives are
// preferable to disclosing another special-purpose address by mistake.
(parts[0] === 192 && parts[1] === 0 && parts[2] === 0) ||
(parts[0] === 192 && parts[1] === 0 && parts[2] === 2) ||
(parts[0] === 192 && parts[1] === 88 && parts[2] === 99) ||
(parts[0] === 198 && parts[1] === 51 && parts[2] === 100) ||
(parts[0] === 203 && parts[1] === 0 && parts[2] === 113);
export const isLocalLoopbackHost = (host: string): boolean => {
const normalized = normalizeHostname(host);
if (normalized === "localhost" || normalized === "::1") return true;
return parseIpv4Address(normalized)?.[0] === 127;
};
const isPrivateNetworkHost = (host: string): boolean => {
export const isPrivateNetworkHost = (host: string): boolean => {
const normalized = normalizeHostname(host);
if (isLocalLoopbackHost(normalized) || normalized.endsWith(".local")) {
if (
normalized === "::" ||
isLocalLoopbackHost(normalized) ||
normalized.endsWith(".localhost") ||
normalized.endsWith(".local") ||
normalized === "home.arpa" ||
normalized.endsWith(".home.arpa") ||
(!normalized.includes(".") && !normalized.includes(":"))
) {
return true;
}
if (normalized.endsWith(".ts.net")) return true;
const parts = parseIpv4Address(normalized);
if (parts) {
return (
parts[0] === 10 ||
(parts[0] === 100 && parts[1]! >= 64 && parts[1]! <= 127) ||
(parts[0] === 172 && parts[1]! >= 16 && parts[1]! <= 31) ||
(parts[0] === 192 && parts[1] === 168) ||
(parts[0] === 169 && parts[1] === 254)
);
}
const parts = parseIpv4Address(normalized) ?? parseIpv4MappedIpv6Address(normalized);
if (parts) return isPrivateIpv4Address(parts);
const firstIpv6Token = normalized.split(":", 1)[0] ?? "";
if (!normalized.includes(":") || !/^[\da-f]{1,4}$/u.test(firstIpv6Token)) return false;
const firstIpv6Hextet = Number.parseInt(firstIpv6Token, 16);
@@ -49,6 +115,48 @@ const isPrivateNetworkHost = (host: string): boolean => {
);
};
/** Whether a hostname is eligible to be disclosed to a public favicon provider. */
export const isPublicFaviconHost = (host: string): boolean => {
// A single trailing dot is a valid absolute DNS name. Repeated trailing
// dots are malformed and can conceal legacy numeric forms such as 127.1.
if (host.endsWith("..")) return false;
const normalized = normalizeHostname(host);
if (isPrivateNetworkHost(normalized)) return false;
if (
[".alt", ".example", ".internal", ".invalid", ".onion", ".test"].some(
(suffix) => normalized === suffix.slice(1) || normalized.endsWith(suffix),
)
) {
return false;
}
const ipv4 = parseIpv4Address(normalized) ?? parseIpv4MappedIpv6Address(normalized);
if (ipv4) return !isSpecialPurposeIpv4Address(ipv4);
if (!normalized.includes(":")) return true;
const ipv6 = parseIpv6Address(normalized);
if (!ipv6) return false;
if (ipv6PrefixMatches(ipv6, [0x0064, 0xff9b, 0, 0, 0, 0, 0, 0], 96)) {
const embeddedIpv4 = [ipv6[6]! >>> 8, ipv6[6]! & 0xff, ipv6[7]! >>> 8, ipv6[7]! & 0xff];
return !isSpecialPurposeIpv4Address(embeddedIpv4);
}
const first = ipv6[0]!;
if ((first & 0xe000) !== 0x2000) return false;
if (ipv6PrefixMatches(ipv6, [0x2001, 0, 0, 0, 0, 0, 0, 0], 23)) {
const publicProtocolAssignment =
(ipv6[1] === 1 &&
ipv6.slice(2, 7).every((part) => part === 0) &&
[1, 2, 3].includes(ipv6[7]!)) ||
ipv6PrefixMatches(ipv6, [0x2001, 3, 0, 0, 0, 0, 0, 0], 32) ||
ipv6PrefixMatches(ipv6, [0x2001, 4, 0x0112, 0, 0, 0, 0, 0], 48) ||
ipv6PrefixMatches(ipv6, [0x2001, 0x20, 0, 0, 0, 0, 0, 0], 28) ||
ipv6PrefixMatches(ipv6, [0x2001, 0x30, 0, 0, 0, 0, 0, 0], 28);
return publicProtocolAssignment;
}
if (ipv6PrefixMatches(ipv6, [0x2001, 0x0db8, 0, 0, 0, 0, 0, 0], 32)) return false;
if (ipv6PrefixMatches(ipv6, [0x2002, 0, 0, 0, 0, 0, 0, 0], 16)) return false;
if (first === 0x3fff && (ipv6[1]! & 0xf000) === 0) return false;
return true;
};
const readEnvironmentUrl = (environmentId: EnvironmentId): URL => {
const connection = readPreparedConnection(environmentId);
if (!connection) throw new Error(`Environment ${environmentId} is not connected.`);
+124
View File
@@ -0,0 +1,124 @@
import { describe, expect, it } from "vite-plus/test";
import {
BROWSER_FAVICON_MAX_ENTRIES,
type BrowserFaviconEntry,
evictExcessFavicons,
faviconKey,
faviconStorageLocation,
isStorableFaviconDataUrl,
migratePersistedBrowserFaviconState,
} from "./browserFaviconLogic";
const PNG = "data:image/png;base64,AAAA";
function entry(capturedAt = 0): BrowserFaviconEntry {
return { dataUrl: PNG, capturedAt };
}
describe("browser favicon logic", () => {
it("keys valid origins canonically while keeping distinct scopes separate", () => {
expect(faviconKey("env:project", "http://myapp.test:3000/admin?x=1", null)).toBe(
"env:project http://myapp.test:3000",
);
expect(faviconKey("env:project", "http://192.168.64.2:3000/", "192.168.64.2")).toBe(
faviconKey("env:project", "http://localhost:3000/", "192.168.64.2"),
);
expect(faviconKey("env:project", "http://127.0.0.1:3000/", null)).toBe(
faviconKey("env:project", "http://0.0.0.0:3000/", null),
);
const keys = [
faviconKey("env:a", "http://localhost:3000/", null),
faviconKey("env:b", "http://localhost:3000/", null),
faviconKey("env:a", "http://localhost:5173/", null),
faviconKey("env:a", "https://localhost:3000/", null),
faviconKey("env:a", "http://192.168.1.50:3000/", "192.168.64.2"),
];
expect(new Set(keys).size).toBe(keys.length);
expect(faviconKey("env:a", "not a url", null)).toBeNull();
expect(faviconKey("env:a", "ftp://example.com/", null)).toBeNull();
expect(faviconKey("", "http://localhost/", null)).toBeNull();
expect(faviconKey("env:a", "http://local:3000/", null)).not.toBe(
faviconKey("env:a", "http://localhost:3000/", null),
);
});
it("retains an exact environment-host alias for offline lookup", () => {
const expected = {
aliases: ["192.168.64.2"],
key: "env:project http://localhost:3000",
};
expect(
faviconStorageLocation("env:project", "http://localhost:3000/app", "192.168.64.2"),
).toEqual(expected);
expect(
faviconStorageLocation("env:project", "http://192.168.64.2:3000/app", "192.168.64.2"),
).toEqual(expected);
expect(
faviconStorageLocation("env:project", "https://example.com/app", "192.168.64.2"),
).toEqual({ aliases: [], key: "env:project https://example.com:443" });
expect(faviconStorageLocation("env:project", "http://localhost:3000/app", "fd00::1")).toEqual({
aliases: ["fd00::1"],
key: "env:project http://localhost:3000",
});
expect(faviconKey("env:project", "http://[2001:4860:4860::8888]/", null)).toBe(
"env:project http://[2001:4860:4860::8888]:80",
);
});
it("accepts only bounded base64 PNG data", () => {
expect(isStorableFaviconDataUrl(PNG)).toBe(true);
expect(isStorableFaviconDataUrl("data:image/svg+xml;base64,AAAA")).toBe(false);
expect(isStorableFaviconDataUrl("data:image/png;base64,")).toBe(false);
expect(isStorableFaviconDataUrl("data:image/png;base64,%%%%")).toBe(false);
expect(isStorableFaviconDataUrl(`data:image/png;base64,${"A".repeat(8192)}`)).toBe(false);
});
it("evicts old entries and sanitizes hydrated state", () => {
const byKey = Object.fromEntries(
Array.from({ length: BROWSER_FAVICON_MAX_ENTRIES + 2 }, (_, index) => [
`key-${index}`,
entry(index),
]),
);
const result = evictExcessFavicons(byKey);
expect(Object.keys(result)).toHaveLength(BROWSER_FAVICON_MAX_ENTRIES);
expect(result["key-0"]).toBeUndefined();
expect(result["key-1"]).toBeUndefined();
expect(
migratePersistedBrowserFaviconState({
byKey: {
"env:project http://local:3000": entry(4),
"env:project http://localhost:3000": entry(5),
"env:project http://localhost:3003": {
...entry(6),
aliases: [
"192.168.64.2",
"192.168.64.2",
"192.168.64.3",
"192.168.64.4",
"192.168.64.5",
"192.168.64.6",
"Not Normalized",
"not a host/",
"x".repeat(5_000),
],
},
"env:project http://localhost:3001": {
dataUrl: "https://example.com/icon.png",
capturedAt: 6,
},
"env:project http://localhost:3002": { dataUrl: PNG, capturedAt: Number.NaN },
},
}),
).toEqual({
byKey: {
"env:project http://localhost:3000": entry(5),
"env:project http://localhost:3003": {
...entry(6),
aliases: ["192.168.64.2", "192.168.64.3", "192.168.64.4", "192.168.64.5"],
},
},
});
});
});
+201
View File
@@ -0,0 +1,201 @@
import { FAVICON_CAPTURED_AT_MAX, FAVICON_DATA_URL_MAX_LENGTH } from "@t3tools/contracts";
import { isLocalLoopbackHost, normalizeHostname } from "./browser/browserTargetResolver";
export type BrowserFaviconEntry = {
dataUrl: string;
capturedAt: number;
aliases?: ReadonlyArray<string>;
};
export const BROWSER_FAVICON_MAX_ENTRIES = 40;
export const BROWSER_FAVICON_MAX_KEY_LENGTH = 4_096;
const BROWSER_FAVICON_MAX_FUTURE_SKEW_MS = 5 * 60 * 1_000;
export const BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY = 4;
const BROWSER_FAVICON_MAX_ALIAS_LENGTH = 255;
function formatFaviconHost(host: string): string {
return host.includes(":") ? `[${host}]` : host;
}
export function canCanonicalizeFaviconWithoutEnvironment(url: string): boolean {
try {
const parsed = new URL(url);
const host = normalizeHostname(parsed.hostname);
return (
(parsed.protocol === "http:" || parsed.protocol === "https:") &&
(isLocalLoopbackHost(host) || host === "0.0.0.0")
);
} catch {
return false;
}
}
export function isValidFaviconCapturedAt(value: unknown): value is number {
return (
typeof value === "number" &&
Number.isFinite(value) &&
value >= 0 &&
value <= FAVICON_CAPTURED_AT_MAX &&
value <= Date.now() + BROWSER_FAVICON_MAX_FUTURE_SKEW_MS
);
}
function migratePersistedFaviconKey(key: string): string | null {
if (key.length === 0 || key.length > BROWSER_FAVICON_MAX_KEY_LENGTH) return null;
const separator = key.indexOf(" ");
if (separator <= 0) return null;
const scope = key.slice(0, separator);
const origin = key.slice(separator + 1);
try {
const parsed = new URL(origin);
if (
(parsed.protocol !== "http:" && parsed.protocol !== "https:") ||
parsed.pathname !== "/" ||
parsed.search !== "" ||
parsed.hash !== "" ||
parsed.username !== "" ||
parsed.password !== ""
)
return null;
if (normalizeHostname(parsed.hostname) !== "local") return key;
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
return `${scope} ${parsed.protocol}//localhost:${port}`;
} catch {
return null;
}
}
function persistedFaviconAlias(value: unknown): string | null {
if (typeof value !== "string" || value.length > BROWSER_FAVICON_MAX_ALIAS_LENGTH) return null;
const normalized = normalizeHostname(value);
if (!normalized || normalized !== value) return null;
try {
const parsed = new URL(`http://${formatFaviconHost(normalized)}`);
return normalizeHostname(parsed.hostname) === normalized ? normalized : null;
} catch {
return null;
}
}
export function faviconKey(
projectRefKey: string,
url: string,
environmentHostname: string | null,
): string | null {
if (projectRefKey.length === 0) return null;
try {
const parsed = new URL(url);
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return null;
const host = normalizeHostname(parsed.hostname);
const canonicalHost =
isLocalLoopbackHost(host) ||
host === "0.0.0.0" ||
(environmentHostname !== null && host === normalizeHostname(environmentHostname))
? "localhost"
: host;
const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
return `${projectRefKey} ${parsed.protocol}//${formatFaviconHost(canonicalHost)}:${port}`;
} catch {
return null;
}
}
export function faviconStorageLocation(
projectRefKey: string,
url: string,
environmentHostname: string | null,
): { readonly aliases: ReadonlyArray<string>; readonly key: string } | null {
const canonicalKey = faviconKey(projectRefKey, url, environmentHostname);
if (!canonicalKey) return null;
if (environmentHostname === null) return { aliases: [], key: canonicalKey };
try {
const parsed = new URL(url);
const host = normalizeHostname(parsed.hostname);
const normalizedEnvironmentHostname = normalizeHostname(environmentHostname);
if (
normalizedEnvironmentHostname.length === 0 ||
(!isLocalLoopbackHost(host) && host !== "0.0.0.0" && host !== normalizedEnvironmentHostname)
) {
return { aliases: [], key: canonicalKey };
}
return {
aliases:
isLocalLoopbackHost(normalizedEnvironmentHostname) ||
normalizedEnvironmentHostname === "0.0.0.0"
? []
: [normalizedEnvironmentHostname],
key: canonicalKey,
};
} catch {
return { aliases: [], key: canonicalKey };
}
}
export function isStorableFaviconDataUrl(value: unknown): value is string {
if (
typeof value !== "string" ||
!value.startsWith("data:image/png;base64,") ||
value.length > FAVICON_DATA_URL_MAX_LENGTH
) {
return false;
}
const payload = value.slice("data:image/png;base64,".length);
return (
payload.length > 0 &&
payload.length % 4 !== 1 &&
!/[^a-z0-9+/=]/i.test(payload) &&
/^[a-z0-9+/]*={0,2}$/i.test(payload)
);
}
export function evictExcessFavicons(
byKey: Record<string, BrowserFaviconEntry>,
): Record<string, BrowserFaviconEntry> {
const keys = Object.keys(byKey);
if (keys.length <= BROWSER_FAVICON_MAX_ENTRIES) return byKey;
return Object.fromEntries(
keys
.toSorted((left, right) => (byKey[right]?.capturedAt ?? 0) - (byKey[left]?.capturedAt ?? 0))
.slice(0, BROWSER_FAVICON_MAX_ENTRIES)
.map((key) => [key, byKey[key] as BrowserFaviconEntry]),
);
}
export function migratePersistedBrowserFaviconState(persistedState: unknown): {
byKey: Record<string, BrowserFaviconEntry>;
} {
if (!persistedState || typeof persistedState !== "object") return { byKey: {} };
const raw = "byKey" in persistedState ? (persistedState as { byKey?: unknown }).byKey : null;
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return { byKey: {} };
const byKey: Record<string, BrowserFaviconEntry> = {};
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
const migratedKey = migratePersistedFaviconKey(key);
if (!migratedKey) continue;
if (!value || typeof value !== "object") continue;
const { dataUrl, capturedAt } = value as Record<string, unknown>;
if (!isStorableFaviconDataUrl(dataUrl)) continue;
if (!isValidFaviconCapturedAt(capturedAt)) continue;
const rawAliases = (value as Record<string, unknown>).aliases;
const aliases = Array.isArray(rawAliases)
? [...new Set(rawAliases.map(persistedFaviconAlias).filter((alias) => alias !== null))].slice(
0,
BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
)
: [];
const existing = byKey[migratedKey];
const newest = !existing || capturedAt > existing.capturedAt;
const mergedAliases = [
...new Set([
...(newest ? aliases : (existing?.aliases ?? [])),
...(newest ? (existing?.aliases ?? []) : aliases),
]),
].slice(0, BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY);
byKey[migratedKey] = {
dataUrl: newest ? dataUrl : existing.dataUrl,
capturedAt: newest ? capturedAt : existing.capturedAt,
...(mergedAliases.length > 0 ? { aliases: mergedAliases } : {}),
};
}
return { byKey: evictExcessFavicons(byKey) };
}
+316
View File
@@ -0,0 +1,316 @@
import { scopeProjectRef } from "@t3tools/client-runtime/environment";
import { EnvironmentId, ProjectId, ThreadId } from "@t3tools/contracts";
import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
vi.mock("~/state/entities", () => ({ useThreadShell: () => null }));
vi.mock("~/state/session", () => ({ usePreparedConnection: () => ({ _tag: "None" }) }));
import {
flushPendingFaviconsForThread,
lookupFavicon,
mergeBrowserFaviconState,
recordFaviconForProject,
recordFaviconForThread,
registerFaviconProjectForThread,
resetBrowserFaviconsForTests,
resolveBrowserFaviconStorage,
useBrowserFaviconStore,
} from "./browserFaviconStore";
import {
BROWSER_FAVICON_MAX_ENTRIES,
migratePersistedBrowserFaviconState,
} from "./browserFaviconLogic";
const environmentId = EnvironmentId.make("env-1");
const projectRef = scopeProjectRef(environmentId, ProjectId.make("project-1"));
const threadRef = { environmentId, threadId: ThreadId.make("thread-1") };
const PNG = "data:image/png;base64,AAAA";
const favicon = (pageUrl: string, capturedAt: number, dataUrl = PNG) => ({
pageUrl,
capturedAt,
dataUrl,
});
describe("browser favicon store", () => {
beforeEach(resetBrowserFaviconsForTests);
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
it("keeps the newest capture for an origin and permits an identical later revisit", () => {
const recordFavicon = vi.spyOn(useBrowserFaviconStore.getState(), "recordFavicon");
recordFaviconForProject(projectRef, favicon("http://localhost:3000/", 20), null);
recordFaviconForProject(
projectRef,
favicon("http://localhost:3000/old", 10, "data:image/png;base64,QkJCQg=="),
null,
);
recordFaviconForProject(projectRef, favicon("http://localhost:3000/new", 30), null);
recordFaviconForProject(projectRef, favicon("http://localhost:3000/new", 30), null);
expect(Object.values(useBrowserFaviconStore.getState().byKey)).toEqual([
{ dataUrl: PNG, capturedAt: 30 },
]);
expect(recordFavicon).toHaveBeenCalledTimes(2);
});
it("does not share localhost icons across environments or physical projects", () => {
const otherEnvironment = scopeProjectRef(
EnvironmentId.make("env-2"),
ProjectId.make("project-1"),
);
const otherProject = scopeProjectRef(environmentId, ProjectId.make("project-2"));
recordFaviconForProject(projectRef, favicon("http://localhost:3000/", 1), null);
recordFaviconForProject(otherEnvironment, favicon("http://localhost:3000/", 2), null);
recordFaviconForProject(otherProject, favicon("http://localhost:3000/", 3), null);
expect(Object.keys(useBrowserFaviconStore.getState().byKey)).toEqual([
"env-1:project-1 http://localhost:3000",
"env-2:project-1 http://localhost:3000",
"env-1:project-2 http://localhost:3000",
]);
});
it("finds a persisted environment icon after shell hydration without a live connection", () => {
recordFaviconForProject(projectRef, favicon("http://192.168.64.2:3000/app", 5), "192.168.64.2");
const byKey = useBrowserFaviconStore.getState().byKey;
expect(lookupFavicon(byKey, null, "http://localhost:3000/app", null)).toBeNull();
expect(lookupFavicon(byKey, projectRef, "http://localhost:3000/app", null)).toBe(PNG);
expect(lookupFavicon(byKey, projectRef, "http://192.168.64.2:3000/app", null)).toBe(PNG);
expect(lookupFavicon(byKey, projectRef, "http://192.168.64.3:3000/app", null)).toBeNull();
expect(lookupFavicon(byKey, projectRef, "https://192.168.64.2:3000/app", null)).toBeNull();
expect(lookupFavicon(byKey, projectRef, "http://192.168.64.2:3001/app", null)).toBeNull();
expect(
lookupFavicon(
byKey,
scopeProjectRef(environmentId, ProjectId.make("project-2")),
"http://192.168.64.2:3000/app",
null,
),
).toBeNull();
});
it("finds a persisted IPv6 environment icon without a live connection", () => {
recordFaviconForProject(projectRef, favicon("http://[fd00::1]:3000/app", 5), "fd00::1");
const migrated = migratePersistedBrowserFaviconState({
byKey: useBrowserFaviconStore.getState().byKey,
}).byKey;
expect(lookupFavicon(migrated, projectRef, "http://[fd00::1]:3000/app", null)).toBe(PNG);
});
it("keeps exact host aliases attached to the newest canonical icon", () => {
const olderPng = "data:image/png;base64,QkJCQg==";
const newerPng = "data:image/png;base64,Q0NDQw==";
recordFaviconForProject(
projectRef,
favicon("http://192.168.64.2:3000/", 10, olderPng),
"192.168.64.2",
);
recordFaviconForProject(
projectRef,
favicon("http://192.168.64.3:3000/", 20, newerPng),
"192.168.64.3",
);
recordFaviconForProject(
projectRef,
favicon("http://192.168.64.4:3000/", 15, olderPng),
"192.168.64.4",
);
const byKey = useBrowserFaviconStore.getState().byKey;
for (const host of ["192.168.64.2", "192.168.64.3", "192.168.64.4"]) {
expect(lookupFavicon(byKey, projectRef, `http://${host}:3000/`, null)).toBe(newerPng);
}
expect(byKey["env-1:project-1 http://localhost:3000"]?.capturedAt).toBe(20);
});
it("evicts an icon and its exact host aliases atomically", () => {
recordFaviconForProject(projectRef, favicon("http://192.168.64.2:3000/", 100), "192.168.64.2");
for (let index = 1; index < BROWSER_FAVICON_MAX_ENTRIES; index += 1) {
recordFaviconForProject(
projectRef,
favicon(`https://example-${index}.com/`, 100 + index),
null,
);
}
expect(
lookupFavicon(
useBrowserFaviconStore.getState().byKey,
projectRef,
"http://192.168.64.2:3000/",
null,
),
).toBe(PNG);
recordFaviconForProject(projectRef, favicon("https://evicts-oldest.example/", 1_000), null);
expect(
lookupFavicon(
useBrowserFaviconStore.getState().byKey,
projectRef,
"http://192.168.64.2:3000/",
null,
),
).toBeNull();
});
it("retains multiple origins until project and connection metadata hydrate", () => {
expect(
recordFaviconForThread(threadRef, favicon("http://localhost:3000/", 1), null, undefined),
).toBe(false);
expect(
recordFaviconForThread(threadRef, favicon("http://localhost:5173/", 2), null, undefined),
).toBe(false);
expect(
Object.keys(Object.values(useBrowserFaviconStore.getState().pendingByThreadKey)[0] ?? {}),
).toHaveLength(2);
expect(flushPendingFaviconsForThread(threadRef, projectRef, "192.168.64.2")).toBe(true);
expect(Object.keys(useBrowserFaviconStore.getState().byKey).toSorted()).toEqual([
"env-1:project-1 http://localhost:3000",
"env-1:project-1 http://localhost:5173",
]);
expect(useBrowserFaviconStore.getState().pendingByThreadKey).toEqual({});
});
it("persists unambiguous loopback captures while the environment is offline", () => {
expect(
recordFaviconForThread(
threadRef,
favicon("http://localhost:3000/", 1),
projectRef,
undefined,
),
).toBe(true);
expect(useBrowserFaviconStore.getState().byKey).toEqual({
"env-1:project-1 http://localhost:3000": { dataUrl: PNG, capturedAt: 1 },
});
recordFaviconForThread(
threadRef,
favicon("http://192.168.64.2:5173/", 2),
projectRef,
undefined,
);
expect(flushPendingFaviconsForThread(threadRef, projectRef, undefined)).toBe(false);
expect(Object.values(useBrowserFaviconStore.getState().pendingByThreadKey)[0]).toBeDefined();
});
it("keeps pending captures in store-owned state independent of bridge lifetime", () => {
recordFaviconForThread(threadRef, favicon("http://localhost:3000/", 10), null, undefined);
const pendingAfterUnmount = useBrowserFaviconStore.getState().pendingByThreadKey;
useBrowserFaviconStore.setState({ pendingByThreadKey: pendingAfterUnmount });
flushPendingFaviconsForThread(threadRef, projectRef, "localhost");
expect(useBrowserFaviconStore.getState().byKey).toEqual({
"env-1:project-1 http://localhost:3000": { dataUrl: PNG, capturedAt: 10 },
});
});
it("flushes and resolves a pending draft-thread favicon after physical project registration", () => {
recordFaviconForThread(threadRef, favicon("http://localhost:8025/", 10), null, undefined);
registerFaviconProjectForThread(threadRef, projectRef);
const registered = useBrowserFaviconStore.getState().projectRefByThreadKey["env-1:thread-1"];
expect(registered).toEqual(projectRef);
expect(flushPendingFaviconsForThread(threadRef, registered!, undefined)).toBe(true);
expect(
lookupFavicon(
useBrowserFaviconStore.getState().byKey,
registered!,
"http://localhost:8025/",
null,
),
).toBe(PNG);
});
it("bounds pending memory by origin and thread", () => {
for (let thread = 0; thread < 22; thread += 1) {
for (let port = 3000; port < 3012; port += 1) {
recordFaviconForThread(
{ environmentId, threadId: ThreadId.make(`thread-${thread}`) },
favicon(`http://localhost:${port}/`, port),
null,
undefined,
);
}
}
const pending = useBrowserFaviconStore.getState().pendingByThreadKey;
expect(Object.keys(pending)).toHaveLength(20);
expect(Object.values(pending).every((byOrigin) => Object.keys(byOrigin).length === 10)).toBe(
true,
);
});
it("sanitizes hydrated state while preserving actions and transient pending data", () => {
recordFaviconForThread(threadRef, favicon("http://localhost:3000/", 1), null, undefined);
const current = useBrowserFaviconStore.getState();
const merged = mergeBrowserFaviconState(
{
byKey: {
"env-1:project-1 http://localhost:3000": { dataUrl: PNG, capturedAt: 2 },
"env-1:project-1 http://localhost:3001": { dataUrl: "bad", capturedAt: 3 },
"env-1:project-1 http://localhost:3002": { dataUrl: PNG, capturedAt: 1e308 },
["x".repeat(5_000)]: { dataUrl: PNG, capturedAt: 4 },
},
},
current,
);
expect(merged.byKey).toEqual({
"env-1:project-1 http://localhost:3000": { dataUrl: PNG, capturedAt: 2 },
});
expect(merged.pendingByThreadKey).toEqual(current.pendingByThreadKey);
expect(typeof merged.recordFavicon).toBe("function");
});
it("falls back to memory when localStorage access throws", () => {
vi.stubGlobal(
"window",
Object.defineProperty({}, "localStorage", {
get: () => {
throw new Error("storage blocked");
},
}),
);
const storage = resolveBrowserFaviconStorage();
storage.setItem("key", "value");
expect(storage.getItem("key")).toBe("value");
});
it("falls back to memory when localStorage operations throw", () => {
vi.stubGlobal("window", {
localStorage: {
getItem: vi.fn(() => {
throw new Error("read blocked");
}),
setItem: vi.fn(() => {
throw new Error("quota exceeded");
}),
removeItem: vi.fn(() => {
throw new Error("remove blocked");
}),
},
});
const storage = resolveBrowserFaviconStorage();
storage.setItem("key", "value");
expect(storage.getItem("key")).toBe("value");
storage.removeItem("key");
expect(storage.getItem("key")).toBeNull();
});
it("keeps the memory shadow authoritative after an asymmetric primary write failure", () => {
vi.stubGlobal("window", {
localStorage: {
getItem: vi.fn(() => "stale"),
setItem: vi.fn(() => {
throw new Error("quota exceeded");
}),
removeItem: vi.fn(() => {
throw new Error("remove blocked");
}),
},
});
const storage = resolveBrowserFaviconStorage();
storage.setItem("key", "fresh");
expect(storage.getItem("key")).toBe("fresh");
storage.removeItem("key");
expect(storage.getItem("key")).toBeNull();
});
});
+342
View File
@@ -0,0 +1,342 @@
import {
scopedProjectKey,
scopedThreadKey,
scopeProjectRef,
} from "@t3tools/client-runtime/environment";
import type { DesktopPreviewFavicon, ScopedProjectRef, ScopedThreadRef } from "@t3tools/contracts";
import * as Option from "effect/Option";
import { useMemo } from "react";
import { create } from "zustand";
import { createJSONStorage, persist } from "zustand/middleware";
import { normalizeHostname } from "~/browser/browserTargetResolver";
import { useThreadShell } from "~/state/entities";
import { usePreparedConnection } from "~/state/session";
import {
BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
type BrowserFaviconEntry,
canCanonicalizeFaviconWithoutEnvironment,
evictExcessFavicons,
faviconKey,
faviconStorageLocation,
isStorableFaviconDataUrl,
isValidFaviconCapturedAt,
migratePersistedBrowserFaviconState,
} from "./browserFaviconLogic";
import { createMemoryStorage, type StateStorage } from "./lib/storage";
const BROWSER_FAVICON_STORAGE_KEY = "t3code:browser-favicons:v1";
const MAX_PENDING_ORIGINS_PER_THREAD = 10;
const MAX_PENDING_THREADS = 20;
const MAX_REGISTERED_THREADS = 100;
type PendingFavicon = DesktopPreviewFavicon;
type PendingFaviconsByOrigin = Record<string, PendingFavicon>;
export interface BrowserFaviconStoreState {
byKey: Record<string, BrowserFaviconEntry>;
/** Capture buffering only. */
pendingByThreadKey: Record<string, PendingFaviconsByOrigin>;
/** Non-persisted fallback for draft/background threads without a hydrated shell. */
projectRefByThreadKey: Record<string, ScopedProjectRef>;
recordFavicon: (
key: string,
dataUrl: string,
capturedAt: number,
aliases?: ReadonlyArray<string>,
) => void;
}
function pendingOriginKey(pageUrl: string): string | null {
return faviconKey("pending", pageUrl, null)?.slice("pending ".length) ?? null;
}
function addPendingFavicon(
pendingByThreadKey: Record<string, PendingFaviconsByOrigin>,
threadKey: string,
favicon: PendingFavicon,
): Record<string, PendingFaviconsByOrigin> {
const originKey = pendingOriginKey(favicon.pageUrl);
if (!originKey) return pendingByThreadKey;
const current = pendingByThreadKey[threadKey] ?? {};
const existing = current[originKey];
if (existing && existing.capturedAt >= favicon.capturedAt) return pendingByThreadKey;
const nextForThread = {
...current,
[originKey]: favicon,
};
const boundedForThread = Object.fromEntries(
Object.entries(nextForThread)
.toSorted(([, left], [, right]) => right.capturedAt - left.capturedAt)
.slice(0, MAX_PENDING_ORIGINS_PER_THREAD),
);
const withoutThread = { ...pendingByThreadKey };
delete withoutThread[threadKey];
return Object.fromEntries(
[...Object.entries(withoutThread), [threadKey, boundedForThread]].slice(-MAX_PENDING_THREADS),
);
}
export function resolveBrowserFaviconStorage(): StateStorage {
const fallback = createMemoryStorage();
const shadowedNames = new Set<string>();
let primary: Storage;
try {
if (typeof window === "undefined") return fallback;
primary = window.localStorage;
} catch {
return fallback;
}
return {
getItem: (name) => {
if (shadowedNames.has(name)) return fallback.getItem(name);
try {
return primary.getItem(name);
} catch {
return fallback.getItem(name);
}
},
setItem: (name, value) => {
fallback.setItem(name, value);
try {
primary.setItem(name, value);
shadowedNames.delete(name);
} catch {
shadowedNames.add(name);
}
},
removeItem: (name) => {
fallback.removeItem(name);
try {
primary.removeItem(name);
shadowedNames.delete(name);
} catch {
shadowedNames.add(name);
}
},
};
}
export const useBrowserFaviconStore = create<BrowserFaviconStoreState>()(
persist(
(set) => ({
byKey: {},
pendingByThreadKey: {},
projectRefByThreadKey: {},
recordFavicon: (key, dataUrl, capturedAt, aliases = []) =>
set((state) => {
if (!isStorableFaviconDataUrl(dataUrl)) return state;
if (!isValidFaviconCapturedAt(capturedAt)) return state;
const existing = state.byKey[key];
const aliasCandidates =
capturedAt > (existing?.capturedAt ?? -1)
? [...aliases, ...(existing?.aliases ?? [])]
: [...(existing?.aliases ?? []), ...aliases];
const nextAliases = [...new Set(aliasCandidates)].slice(
0,
BROWSER_FAVICON_MAX_ALIASES_PER_ENTRY,
);
const aliasesUnchanged =
nextAliases.length === (existing?.aliases?.length ?? 0) &&
nextAliases.every((alias, index) => alias === existing?.aliases?.[index]);
if (existing && capturedAt <= existing.capturedAt && aliasesUnchanged) return state;
return {
byKey: evictExcessFavicons({
...state.byKey,
[key]: {
dataUrl: capturedAt > (existing?.capturedAt ?? -1) ? dataUrl : existing!.dataUrl,
capturedAt: Math.max(capturedAt, existing?.capturedAt ?? -1),
...(nextAliases.length > 0 ? { aliases: nextAliases } : {}),
},
}),
};
}),
}),
{
name: BROWSER_FAVICON_STORAGE_KEY,
version: 1,
storage: createJSONStorage(resolveBrowserFaviconStorage),
partialize: (state) => ({ byKey: state.byKey }),
migrate: migratePersistedBrowserFaviconState,
merge: mergeBrowserFaviconState,
},
),
);
export function mergeBrowserFaviconState(
persistedState: unknown,
currentState: BrowserFaviconStoreState,
): BrowserFaviconStoreState {
return {
...currentState,
...migratePersistedBrowserFaviconState(persistedState),
};
}
export function registerFaviconProjectForThread(
threadRef: ScopedThreadRef,
projectRef: ScopedProjectRef,
): void {
const threadKey = scopedThreadKey(threadRef);
const state = useBrowserFaviconStore.getState();
const current = state.projectRefByThreadKey[threadKey];
if (
current?.environmentId === projectRef.environmentId &&
current.projectId === projectRef.projectId
) {
return;
}
useBrowserFaviconStore.setState({
projectRefByThreadKey: Object.fromEntries(
[
...Object.entries(state.projectRefByThreadKey).filter(([key]) => key !== threadKey),
[threadKey, projectRef],
].slice(-MAX_REGISTERED_THREADS),
),
});
}
export function useFaviconProjectRefForThread(threadRef: ScopedThreadRef): ScopedProjectRef | null {
const shell = useThreadShell(threadRef);
const shellProjectId = shell?.projectId ?? null;
const shellProjectRef = useMemo(
() => (shellProjectId ? scopeProjectRef(threadRef.environmentId, shellProjectId) : null),
[shellProjectId, threadRef.environmentId],
);
const registered = useBrowserFaviconStore(
(state) => state.projectRefByThreadKey[scopedThreadKey(threadRef)] ?? null,
);
return shellProjectRef ?? registered;
}
export function recordFaviconForProject(
projectRef: ScopedProjectRef,
favicon: DesktopPreviewFavicon,
environmentHostname: string | null,
): boolean {
if (!isStorableFaviconDataUrl(favicon.dataUrl) || !isValidFaviconCapturedAt(favicon.capturedAt)) {
return false;
}
const location = faviconStorageLocation(
scopedProjectKey(projectRef),
favicon.pageUrl,
environmentHostname,
);
if (!location) return false;
const state = useBrowserFaviconStore.getState();
const existing = state.byKey[location.key];
if (
existing &&
existing.capturedAt >= favicon.capturedAt &&
location.aliases.every((alias) => existing.aliases?.includes(alias))
)
return true;
state.recordFavicon(location.key, favicon.dataUrl, favicon.capturedAt, location.aliases);
return true;
}
export function recordFaviconForThread(
threadRef: ScopedThreadRef,
favicon: DesktopPreviewFavicon,
projectRef: ScopedProjectRef | null,
environmentHostname: string | undefined,
): boolean {
if (
!isStorableFaviconDataUrl(favicon.dataUrl) ||
!isValidFaviconCapturedAt(favicon.capturedAt) ||
!pendingOriginKey(favicon.pageUrl)
)
return false;
const hostname =
environmentHostname !== undefined
? environmentHostname
: canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
? null
: undefined;
if (
projectRef &&
hostname !== undefined &&
recordFaviconForProject(projectRef, favicon, hostname)
) {
return true;
}
const threadKey = scopedThreadKey(threadRef);
const state = useBrowserFaviconStore.getState();
const pendingByThreadKey = addPendingFavicon(state.pendingByThreadKey, threadKey, favicon);
if (pendingByThreadKey !== state.pendingByThreadKey) {
useBrowserFaviconStore.setState({ pendingByThreadKey });
}
return false;
}
export function flushPendingFaviconsForThread(
threadRef: ScopedThreadRef,
projectRef: ScopedProjectRef,
environmentHostname: string | undefined,
): boolean {
const threadKey = scopedThreadKey(threadRef);
const pending = useBrowserFaviconStore.getState().pendingByThreadKey[threadKey];
if (!pending) return true;
const remaining = Object.fromEntries(
Object.entries(pending).filter(([, favicon]) => {
const hostname =
environmentHostname !== undefined
? environmentHostname
: canCanonicalizeFaviconWithoutEnvironment(favicon.pageUrl)
? null
: undefined;
return hostname === undefined || !recordFaviconForProject(projectRef, favicon, hostname);
}),
);
useBrowserFaviconStore.setState((state) => {
const pendingByThreadKey = { ...state.pendingByThreadKey };
if (Object.keys(remaining).length === 0) delete pendingByThreadKey[threadKey];
else pendingByThreadKey[threadKey] = remaining;
return { pendingByThreadKey };
});
return Object.keys(remaining).length === 0;
}
export function useFaviconForThreadUrl(threadRef: ScopedThreadRef, url: string): string | null {
const projectRef = useFaviconProjectRefForThread(threadRef);
const preparedConnection = usePreparedConnection(threadRef.environmentId);
const environmentHostname = Option.isSome(preparedConnection)
? new URL(preparedConnection.value.httpBaseUrl).hostname
: null;
return useBrowserFaviconStore((state) =>
lookupFavicon(state.byKey, projectRef, url, environmentHostname),
);
}
export function lookupFavicon(
byKey: Record<string, BrowserFaviconEntry>,
projectRef: ScopedProjectRef | null,
url: string,
environmentHostname: string | null,
): string | null {
const key = projectRef
? faviconKey(scopedProjectKey(projectRef), url, environmentHostname)
: null;
if (!key) return null;
const direct = byKey[key];
if (direct) return direct.dataUrl;
try {
const requestedHost = normalizeHostname(new URL(url).hostname);
const localKey = faviconKey(scopedProjectKey(projectRef!), url, requestedHost);
const localEntry = localKey ? byKey[localKey] : null;
return localEntry?.aliases?.includes(requestedHost) ? localEntry.dataUrl : null;
} catch {
return null;
}
}
export function resetBrowserFaviconsForTests(): void {
useBrowserFaviconStore.setState({
byKey: {},
pendingByThreadKey: {},
projectRefByThreadKey: {},
});
useBrowserFaviconStore.persist.clearStorage();
}
+12 -3
View File
@@ -179,6 +179,7 @@ import {
} from "~/projectScripts";
import { newDraftId, newMessageId, newThreadId } from "~/lib/utils";
import { useBrowserHistoryStore } from "~/browserHistoryStore";
import { registerFaviconProjectForThread } from "~/browserFaviconStore";
import { getProviderModelCapabilities, resolveSelectableProvider } from "../providerModels";
import { NO_PROVIDER_MODEL_SELECTION } from "../providerInstances";
import {
@@ -1704,9 +1705,11 @@ function ChatViewContent(props: ChatViewProps) {
});
}, [activeThreadKey, existingOpenTerminalThreadKeys, terminalUiState.terminalOpen]);
const latestTurnSettled = isLatestTurnSettled(activeLatestTurn, activeThread?.session ?? null);
const activeProjectRef = activeThread
? scopeProjectRef(activeThread.environmentId, activeThread.projectId)
: null;
const activeProjectRef = useMemo(
() =>
activeThread ? scopeProjectRef(activeThread.environmentId, activeThread.projectId) : null,
[activeThread?.environmentId, activeThread?.projectId],
);
const activeProject = useProject(activeProjectRef);
const handleNewThreadInActiveProject = useCallback(() => {
startNewThreadForProject(activeProjectRef, handleNewThread);
@@ -1758,6 +1761,10 @@ function ChatViewContent(props: ChatViewProps) {
// drive the environment picker in BranchToolbar.
const allProjects = useProjects();
const primaryEnvironmentId = primaryEnvironment?.environmentId ?? null;
useEffect(() => {
if (!activeThreadRef || !activeProjectRef) return;
registerFaviconProjectForThread(activeThreadRef, activeProjectRef);
}, [activeProjectRef, activeThreadRef]);
useEffect(() => {
if (!clientSettingsHydrated || !activeThreadRef || !activeProject) return;
// Reuse the sidebar's grouping so history follows the project rows the user
@@ -6546,6 +6553,7 @@ function ChatViewContent(props: ChatViewProps) {
activeSurfaceId={activeRightPanelSurface?.id ?? null}
pendingSurfaceIds={pendingFileSurfaceIds}
previewSessions={activePreviewState.sessions}
desktopByTabId={activePreviewState.desktopByTabId}
terminalLabelsById={activeTerminalLabelsById}
onActivate={activateRightPanelSurface}
onCloseSurface={closeRightPanelSurface}
@@ -6580,6 +6588,7 @@ function ChatViewContent(props: ChatViewProps) {
activeSurfaceId={activeRightPanelSurface?.id ?? null}
pendingSurfaceIds={pendingFileSurfaceIds}
previewSessions={activePreviewState.sessions}
desktopByTabId={activePreviewState.desktopByTabId}
terminalLabelsById={activeTerminalLabelsById}
onActivate={activateRightPanelSurface}
onCloseSurface={closeRightPanelSurface}
@@ -0,0 +1,115 @@
import type { DesktopPreviewFavicon, PreviewSessionSnapshot } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vite-plus/test";
import { RightPanelTabs } from "./RightPanelTabs";
const previewSurface = {
id: "browser:tab-1" as const,
kind: "preview" as const,
resourceId: "tab-1",
};
const secondSurface = {
id: "browser:tab-2" as const,
kind: "preview" as const,
resourceId: "tab-2",
};
const sessions: Readonly<Record<string, PreviewSessionSnapshot>> = {
"tab-1": {
threadId: "thread-1",
tabId: "tab-1",
navStatus: { _tag: "Success", url: "http://24x.xf.local/", title: "Local site" },
canGoBack: false,
canGoForward: false,
updatedAt: "2026-08-09T00:00:00.000Z",
},
"tab-2": {
threadId: "thread-1",
tabId: "tab-2",
navStatus: { _tag: "Success", url: "http://24x.xf.local/admin", title: "Admin" },
canGoBack: false,
canGoForward: false,
updatedAt: "2026-08-09T00:00:00.000Z",
},
};
const favicon = (dataUrl: string, pageUrl: string): DesktopPreviewFavicon => ({
dataUrl,
pageUrl,
capturedAt: 1,
});
function overlay(icon: DesktopPreviewFavicon | null) {
return {
hasWebContents: true,
canGoBack: false,
canGoForward: false,
loading: false,
zoomFactor: 1,
pictureInPicture: false,
colorScheme: "system" as const,
controller: "none" as const,
favicon: icon,
};
}
function renderTabs(first: DesktopPreviewFavicon | null, second?: DesktopPreviewFavicon) {
return renderToStaticMarkup(
<RightPanelTabs
mode="inline"
surfaces={second ? [previewSurface, secondSurface] : [previewSurface]}
activeSurfaceId={previewSurface.id}
pendingSurfaceIds={new Set()}
previewSessions={sessions}
desktopByTabId={{
"tab-1": overlay(first),
...(second ? { "tab-2": overlay(second) } : {}),
}}
terminalLabelsById={new Map()}
onActivate={() => undefined}
onCloseSurface={() => undefined}
onCloseOtherSurfaces={() => undefined}
onCloseSurfacesToRight={() => undefined}
onCloseAllSurfaces={() => undefined}
onCopyFilePath={() => undefined}
onAddBrowser={() => undefined}
onAddTerminal={() => undefined}
onAddPullRequest={() => undefined}
onAddDiff={() => undefined}
onAddFiles={() => undefined}
onAddAgents={() => undefined}
liveAgentCount={0}
browserAvailable
terminalAvailable={false}
diffAvailable={false}
filesAvailable={false}
pullRequestAvailable={false}
agentsAvailable={false}
>
<div>content</div>
</RightPanelTabs>,
);
}
describe("RightPanelTabs preview favicon", () => {
it("prefers a live capture and never asks Google about a private hostname", () => {
const captured = renderTabs(favicon("data:image/png;base64,AAAA", "http://24x.xf.local/"));
expect(captured).toContain("data:image/png;base64,AAAA");
expect(captured).not.toContain("s2/favicons");
expect(renderTabs(null)).not.toContain("s2/favicons");
});
it("keeps route-specific captures isolated between live tabs on one origin", () => {
const html = renderTabs(
favicon("data:image/png;base64,AAAA", "http://24x.xf.local/"),
favicon("data:image/png;base64,BBBB", "http://24x.xf.local/admin"),
);
expect(html).toContain("data:image/png;base64,AAAA");
expect(html).toContain("data:image/png;base64,BBBB");
});
it("hides a capture while the server session still describes another origin", () => {
const html = renderTabs(favicon("data:image/png;base64,AAAA", "https://example.com/"));
expect(html).not.toContain("data:image/png;base64,AAAA");
});
});
+24 -12
View File
@@ -22,6 +22,7 @@ import {
} from "react";
import { isElectron } from "~/env";
import type { DesktopPreviewOverlay } from "~/previewStateStore";
import type { RightPanelSurface } from "~/rightPanelStore";
import { cn } from "~/lib/utils";
import { readLocalApi } from "~/localApi";
@@ -34,6 +35,7 @@ import { useTheme } from "~/hooks/useTheme";
import { COLLAPSED_SIDEBAR_TITLEBAR_INSET_CLASS } from "~/workspaceTitlebar";
import { PreviewPanelShell, type PreviewPanelMode } from "./preview/PreviewPanelShell";
import { FaviconImage } from "./preview/PreviewFaviconIcon";
import { PierreEntryIcon } from "./chat/PierreEntryIcon";
interface RightPanelTabsProps {
@@ -48,6 +50,7 @@ interface RightPanelTabsProps {
activeSurfaceId: string | null;
pendingSurfaceIds: ReadonlySet<string>;
previewSessions: Readonly<Record<string, PreviewSessionSnapshot>>;
desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
terminalLabelsById: ReadonlyMap<string, string>;
onActivate: (surface: RightPanelSurface) => void;
onCloseSurface: (surface: RightPanelSurface) => void;
@@ -435,30 +438,35 @@ function surfaceTitle(
}
}
function PreviewFavicon({ url }: { url: string | null }) {
const faviconUrl = faviconUrlForOrigin(url, 32);
const [failedUrl, setFailedUrl] = useState<string | null>(null);
if (!faviconUrl || failedUrl === faviconUrl) return <Globe2 className="size-3 shrink-0" />;
function PreviewFavicon({ capturedUrl, url }: { capturedUrl: string | null; url: string | null }) {
const publicProviderUrl = faviconUrlForOrigin(url, 32);
return (
<img
src={faviconUrl}
alt=""
aria-hidden
draggable={false}
className="size-3 shrink-0 rounded-sm"
onError={() => setFailedUrl(faviconUrl)}
<FaviconImage
sources={[capturedUrl, publicProviderUrl]}
fallback={<Globe2 className="size-3 shrink-0" />}
className="size-3 shrink-0 rounded-sm object-contain"
/>
);
}
function sameOrigin(left: string, right: string): boolean {
try {
return new URL(left).origin === new URL(right).origin;
} catch {
return false;
}
}
function SurfaceIcon({
surface,
sessions,
desktopByTabId,
theme,
pullRequestStatuses,
}: {
surface: RightPanelSurface;
sessions: Readonly<Record<string, PreviewSessionSnapshot>>;
desktopByTabId: Readonly<Record<string, DesktopPreviewOverlay>>;
theme: "light" | "dark";
pullRequestStatuses: Readonly<Record<string, PullRequestTabStatus>> | undefined;
}) {
@@ -466,7 +474,10 @@ function SurfaceIcon({
case "preview": {
const snapshot = surface.resourceId ? sessions[surface.resourceId] : null;
const url = !snapshot || snapshot.navStatus._tag === "Idle" ? null : snapshot.navStatus.url;
return <PreviewFavicon url={url} />;
const favicon = snapshot ? (desktopByTabId[snapshot.tabId]?.favicon ?? null) : null;
const capturedUrl =
favicon && url && sameOrigin(favicon.pageUrl, url) ? favicon.dataUrl : null;
return <PreviewFavicon capturedUrl={capturedUrl} url={url} />;
}
case "diff":
return <FileDiff className="size-3 shrink-0" />;
@@ -636,6 +647,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) {
<SurfaceIcon
surface={surface}
sessions={props.previewSessions}
desktopByTabId={props.desktopByTabId}
theme={resolvedTheme}
pullRequestStatuses={props.pullRequestStatuses}
/>
@@ -1,4 +1,4 @@
import { EnvironmentId } from "@t3tools/contracts";
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
@@ -19,10 +19,14 @@ const mocks = vi.hoisted(() => ({
vi.mock("./useDiscoveredLocalServers", () => ({
useDiscoveredLocalServers: () => mocks.servers,
}));
vi.mock("./PreviewFaviconIcon", () => ({
PreviewFaviconIcon: () => <span data-favicon-icon />,
}));
import { PreviewEmptyState } from "./PreviewEmptyState";
const environmentId = EnvironmentId.make("env-1");
const threadRef = { environmentId, threadId: ThreadId.make("thread-1") };
function server(port: number) {
return {
@@ -41,6 +45,7 @@ function server(port: number) {
function render(recentEntries: Array<{ url: string; lastVisitedAt: number; title?: string }>) {
return renderToStaticMarkup(
<PreviewEmptyState
threadRef={threadRef}
environmentId={environmentId}
recentEntries={recentEntries}
onRemoveRecent={() => undefined}
@@ -1,4 +1,4 @@
import type { EnvironmentId } from "@t3tools/contracts";
import type { EnvironmentId, ScopedThreadRef } from "@t3tools/contracts";
import { Globe, History, RadioTower } from "lucide-react";
import type { BrowserHistoryEntry } from "~/browserHistoryStore";
@@ -9,6 +9,7 @@ import { PreviewRecentUrlCard } from "./PreviewRecentUrlCard";
import { useDiscoveredLocalServers } from "./useDiscoveredLocalServers";
interface Props {
threadRef: ScopedThreadRef;
environmentId: EnvironmentId;
configuredUrls?: ReadonlyArray<string> | undefined;
recentlySeenUrls?: ReadonlyArray<string> | undefined;
@@ -18,6 +19,7 @@ interface Props {
}
export function PreviewEmptyState({
threadRef,
environmentId,
configuredUrls,
recentlySeenUrls,
@@ -60,6 +62,7 @@ export function PreviewEmptyState({
{recents.map((entry) => (
<PreviewRecentUrlCard
key={entry.url}
threadRef={threadRef}
entry={entry}
onOpen={() => onOpenUrl(entry.url)}
onRemove={() => onRemoveRecent(entry.url)}
@@ -78,6 +81,7 @@ export function PreviewEmptyState({
{servers.map((server) => (
<PreviewLocalServerCard
key={`${server.host}:${server.port}`}
threadRef={threadRef}
server={server}
onOpen={() => onOpenUrl(server.requestedUrl)}
/>
@@ -0,0 +1,51 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it, vi } from "vite-plus/test";
const mocks = vi.hoisted(() => ({ favicon: null as string | null }));
vi.mock("~/browserFaviconStore", () => ({
useFaviconForThreadUrl: () => mocks.favicon,
}));
import { FaviconImage, PreviewFaviconIcon, selectFaviconSource } from "./PreviewFaviconIcon";
const threadRef = {
environmentId: EnvironmentId.make("env-1"),
threadId: ThreadId.make("thread-1"),
};
describe("preview favicon image", () => {
it("renders a captured source before later fallback sources", () => {
expect(
renderToStaticMarkup(
<FaviconImage
sources={["data:image/png;base64,AAAA", "https://public.example/icon"]}
fallback={<span>fallback</span>}
/>,
),
).toContain('src="data:image/png;base64,AAAA"');
const captured = "data:image/png;base64,AAAA";
const google = "https://public.example/icon";
expect(selectFaviconSource([captured, google], new Set())).toBe(captured);
expect(selectFaviconSource([captured, google], new Set([captured]))).toBe(google);
expect(selectFaviconSource([captured, google], new Set([captured, google]))).toBeNull();
expect(selectFaviconSource(["data:image/png;base64,BBBB", google], new Set([captured]))).toBe(
"data:image/png;base64,BBBB",
);
});
it("uses a stored project icon or falls back to the browser mockup", () => {
mocks.favicon = null;
const html = renderToStaticMarkup(
<PreviewFaviconIcon threadRef={threadRef} url="http://localhost:3000/" />,
);
expect(html).not.toContain("<img");
expect(html).toContain("rounded-[5px]");
mocks.favicon = "data:image/png;base64,AAAA";
const faviconHtml = renderToStaticMarkup(
<PreviewFaviconIcon threadRef={threadRef} url="http://localhost:3000/" />,
);
expect(faviconHtml).toContain('src="data:image/png;base64,AAAA"');
});
});
@@ -0,0 +1,66 @@
import type { ScopedThreadRef } from "@t3tools/contracts";
import { type ReactNode, useState } from "react";
import { useFaviconForThreadUrl } from "~/browserFaviconStore";
import { cn } from "~/lib/utils";
import { BrowserMockup } from "./BrowserMockup";
export function selectFaviconSource(
sources: ReadonlyArray<string>,
failed: ReadonlySet<string>,
): string | null {
return sources.find((candidate) => !failed.has(candidate)) ?? null;
}
export function FaviconImage(props: {
sources: ReadonlyArray<string | null | undefined>;
fallback: ReactNode;
className?: string | undefined;
}) {
const sources = props.sources.filter((source): source is string => Boolean(source));
return (
<FaviconImageAttempt
key={sources.join("\0")}
sources={sources}
fallback={props.fallback}
className={props.className}
/>
);
}
function FaviconImageAttempt(props: {
sources: ReadonlyArray<string>;
fallback: ReactNode;
className?: string | undefined;
}) {
const [failed, setFailed] = useState<ReadonlySet<string>>(() => new Set());
const source = selectFaviconSource(props.sources, failed);
if (!source) return props.fallback;
return (
<img
src={source}
alt=""
aria-hidden="true"
draggable={false}
className={props.className}
onError={() => setFailed((current) => new Set(current).add(source))}
/>
);
}
export function PreviewFaviconIcon(props: {
threadRef: ScopedThreadRef;
url: string;
className?: string | undefined;
}) {
const source = useFaviconForThreadUrl(props.threadRef, props.url);
const fallback = <BrowserMockup className={cn("size-7 shrink-0", props.className)} />;
return (
<FaviconImage
sources={[source]}
fallback={fallback}
className={cn("size-7 shrink-0 rounded object-contain", props.className)}
/>
);
}
@@ -1,12 +1,15 @@
import { BrowserMockup } from "./BrowserMockup";
import type { ScopedThreadRef } from "@t3tools/contracts";
import { PreviewFaviconIcon } from "./PreviewFaviconIcon";
import type { PreviewableServer } from "./useDiscoveredLocalServers";
interface Props {
threadRef: ScopedThreadRef;
server: PreviewableServer;
onOpen: () => void;
}
export function PreviewLocalServerCard({ server, onOpen }: Props) {
export function PreviewLocalServerCard({ threadRef, server, onOpen }: Props) {
const subtitle = describeServer(server);
return (
<button
@@ -14,7 +17,7 @@ export function PreviewLocalServerCard({ server, onOpen }: Props) {
onClick={onOpen}
className="group flex w-full items-center gap-3 px-3 py-3 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" />
<PreviewFaviconIcon threadRef={threadRef} url={server.requestedUrl} />
<div className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-sm font-medium text-foreground">{subtitle}</span>
<span className="truncate text-xs text-muted-foreground">
@@ -1,18 +1,20 @@
import type { ScopedThreadRef } from "@t3tools/contracts";
import { X } from "lucide-react";
import { isValidHistoryTimestamp, type BrowserHistoryEntry } from "~/browserHistoryStore";
import { useNowMinute } from "~/hooks/useNowMinute";
import { formatRelativeTimeLabel } from "~/timestampFormat";
import { BrowserMockup } from "./BrowserMockup";
import { PreviewFaviconIcon } from "./PreviewFaviconIcon";
interface Props {
threadRef: ScopedThreadRef;
entry: BrowserHistoryEntry;
onOpen: () => void;
onRemove: () => void;
}
export function PreviewRecentUrlCard({ entry, onOpen, onRemove }: Props) {
export function PreviewRecentUrlCard({ threadRef, 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}`;
@@ -27,7 +29,7 @@ export function PreviewRecentUrlCard({ entry, onOpen, onRemove }: Props) {
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" />
<PreviewFaviconIcon threadRef={threadRef} url={entry.url} />
<div className="flex min-w-0 flex-1 flex-col">
<span className="truncate text-sm font-medium text-foreground">
{entry.title ?? label}
@@ -710,6 +710,7 @@ export function PreviewView({
) : null}
{showEmptyState ? (
<PreviewEmptyState
threadRef={threadRef}
environmentId={threadRef.environmentId}
configuredUrls={configuredUrls}
recentlySeenUrls={previewState.recentlySeenUrls}
@@ -0,0 +1,48 @@
import type { DesktopPreviewTabState } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { projectDesktopState } from "./usePreviewBridge";
const favicon = {
dataUrl: "data:image/png;base64,AAAA",
pageUrl: "http://localhost:3000/app",
capturedAt: 1,
};
function state(navStatus: DesktopPreviewTabState["navStatus"]): DesktopPreviewTabState {
return {
tabId: "tab-1",
webContentsId: 1,
navStatus,
canGoBack: false,
canGoForward: false,
zoomFactor: 1,
pictureInPicture: false,
colorScheme: "system",
controller: "none",
favicon,
updatedAt: "2026-08-09T00:00:00.000Z",
};
}
describe("projectDesktopState", () => {
it("shows a retained icon only while the current document has the captured origin", () => {
expect(
projectDesktopState(
state({ kind: "Loading", url: "http://localhost:3000/reload", title: "" }),
).favicon,
).toEqual(favicon);
expect(
projectDesktopState(
state({
kind: "LoadFailed",
url: "https://example.com/",
title: "",
code: -105,
description: "failed",
}),
).favicon,
).toBeNull();
expect(projectDesktopState(state({ kind: "Idle" })).favicon).toBeNull();
});
});
@@ -6,15 +6,31 @@ import type {
ScopedThreadRef,
ThreadId,
} from "@t3tools/contracts";
import { useEffect, useRef } from "react";
import { parseScopedThreadKey, scopedThreadKey } from "@t3tools/client-runtime/environment";
import * as Option from "effect/Option";
import { useEffect, useEffectEvent, useMemo, useRef } from "react";
import {
flushPendingFaviconsForThread,
recordFaviconForThread,
useFaviconProjectRefForThread,
} from "~/browserFaviconStore";
import { useBrowserPointerStore } from "~/browser/browserPointerStore";
import { applyPreviewDesktopState, type DesktopPreviewOverlay } from "~/previewStateStore";
import { previewEnvironment } from "~/state/preview";
import { usePreparedConnection } from "~/state/session";
import { useAtomCommand } from "~/state/use-atom-command";
import { previewBridge } from "./previewBridge";
function originOf(url: string): string | null {
try {
return new URL(url).origin;
} catch {
return null;
}
}
/**
* Mirrors low-latency desktop state into the store and reflects navigation
* events back to the server. Webview lifetime is owned by ElectronBrowserHost.
@@ -28,26 +44,36 @@ export function usePreviewBridge(input: {
const clearBrowserPointer = useBrowserPointerStore((state) => state.clear);
const reportStatus = useAtomCommand(previewEnvironment.reportStatus, "preview status report");
const bridge = previewBridge;
const threadKey = scopedThreadKey(threadRef);
const stableThreadRef = useMemo(() => {
const parsed = parseScopedThreadKey(threadKey);
if (!parsed) throw new Error(`Invalid scoped thread key: ${threadKey}`);
return parsed;
}, [threadKey]);
const projectRef = useFaviconProjectRefForThread(stableThreadRef);
const preparedConnection = usePreparedConnection(stableThreadRef.environmentId);
const environmentHostname = Option.isSome(preparedConnection)
? new URL(preparedConnection.value.httpBaseUrl).hostname
: undefined;
// One bridge subscription does both jobs (mirror state + forward to
// server) so the desktop bridge keeps a single listener entry per tab.
const lastReportedUrl = useRef<string | null>(null);
const lastReportedKind = useRef<DesktopPreviewTabState["navStatus"]["kind"] | null>(null);
const lastDesktopNavStatus = useRef<DesktopPreviewTabState["navStatus"] | null>(null);
useEffect(() => {
if (!bridge || typeof window === "undefined") return;
lastReportedUrl.current = null;
lastReportedKind.current = null;
lastDesktopNavStatus.current = null;
const unsubscribe = bridge.onStateChange((changedTabId, state) => {
const handleStateChange = useEffectEvent(
(changedTabId: string, state: DesktopPreviewTabState): void => {
if (changedTabId !== runtimeTabId) return;
if (shouldClearBrowserPointer(lastDesktopNavStatus.current, state.navStatus)) {
clearBrowserPointer(runtimeTabId);
}
lastDesktopNavStatus.current = state.navStatus;
applyPreviewDesktopState(threadRef, tabId, projectDesktopState(state));
applyPreviewDesktopState(stableThreadRef, tabId, projectDesktopState(state));
if (state.favicon) {
recordFaviconForThread(stableThreadRef, state.favicon, projectRef, environmentHostname);
}
const reported = buildReportInput({
threadId: threadRef.threadId,
threadId: stableThreadRef.threadId,
tabId,
state,
lastReportedUrl: lastReportedUrl.current,
@@ -57,12 +83,22 @@ export function usePreviewBridge(input: {
lastReportedUrl.current = reported.lastReportedUrl;
lastReportedKind.current = reported.lastReportedKind;
void reportStatus({
environmentId: threadRef.environmentId,
environmentId: stableThreadRef.environmentId,
input: reported.input,
});
});
return unsubscribe;
}, [bridge, clearBrowserPointer, reportStatus, runtimeTabId, tabId, threadRef]);
},
);
useEffect(() => {
if (!bridge || typeof window === "undefined") return;
lastReportedUrl.current = null;
lastReportedKind.current = null;
lastDesktopNavStatus.current = null;
return bridge.onStateChange(handleStateChange);
}, [bridge, runtimeTabId, stableThreadRef, tabId]);
useEffect(() => {
if (!projectRef) return;
flushPendingFaviconsForThread(stableThreadRef, projectRef, environmentHostname);
}, [environmentHostname, projectRef, stableThreadRef]);
}
function shouldClearBrowserPointer(
@@ -75,7 +111,8 @@ function shouldClearBrowserPointer(
return current.url !== previous.url;
}
function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
export function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverlay {
const navOrigin = state.navStatus.kind === "Idle" ? null : originOf(state.navStatus.url);
return {
hasWebContents: state.webContentsId !== null,
canGoBack: state.canGoBack,
@@ -85,6 +122,7 @@ function projectDesktopState(state: DesktopPreviewTabState): DesktopPreviewOverl
pictureInPicture: state.pictureInPicture,
colorScheme: state.colorScheme,
controller: state.controller,
favicon: state.favicon && originOf(state.favicon.pageUrl) === navOrigin ? state.favicon : null,
};
}
+42
View File
@@ -0,0 +1,42 @@
import { describe, expect, it } from "vite-plus/test";
import { faviconUrlForOrigin } from "./favicon";
describe("faviconUrlForOrigin", () => {
it("never sends private origin hostnames to the public provider", () => {
for (const url of [
"http://localhost:3000/",
"http://127.0.0.1:3000/",
"http://0.0.0.0:3000/",
"http://devbox:3000/",
"https://24x.xf.local/",
"http://printer.home.arpa/",
"http://192.168.1.20:3000/",
"http://[::]/",
"http://[::ffff:192.168.1.20]/",
"http://100.65.180.100:3000/",
"https://devbox.example.ts.net/",
"http://192.0.2.1/",
"http://198.51.100.1/",
"http://203.0.113.1/",
"http://224.0.0.1/",
"http://240.0.0.1/",
"http://[2001:db8::1]/",
"http://[ff02::1]/",
"http://app.test../",
"https://24x.xf.local../",
"http://printer.home.arpa../",
"https://devbox.example.ts.net../",
"http://127.0.0.1../",
"http://127.1../",
"http://10.1../",
"http://172.16.1../",
"http://192.168.1../",
]) {
expect(faviconUrlForOrigin(url)).toBeNull();
}
expect(faviconUrlForOrigin("https://example.com/path", 32)).toBe(
"https://www.google.com/s2/favicons?domain=example.com&sz=32",
);
});
});
+3
View File
@@ -1,3 +1,5 @@
import { isPublicFaviconHost } from "~/browser/browserTargetResolver";
/**
* Favicon helpers for the preview tab strip.
*
@@ -13,6 +15,7 @@ export function faviconUrlForOrigin(rawUrl: string | null | undefined, size = 32
const url = new URL(rawUrl);
if (!url.host) return null;
if (url.protocol !== "http:" && url.protocol !== "https:") return null;
if (!isPublicFaviconHost(url.hostname)) return null;
return `${FAVICON_PROVIDER}?domain=${encodeURIComponent(url.host)}&sz=${size}`;
} catch {
return null;
+4
View File
@@ -322,6 +322,7 @@ describe("previewStateStore (single-tab)", () => {
pictureInPicture: false,
colorScheme: "system",
controller: "none",
favicon: null,
});
const state = readThreadPreviewState(ref);
expect(state.desktopOverlay?.canGoBack).toBe(true);
@@ -342,6 +343,7 @@ describe("previewStateStore (single-tab)", () => {
pictureInPicture: false,
colorScheme: "system",
controller: "none",
favicon: null,
});
setActivePreviewTab(ref, first.tabId);
@@ -390,6 +392,7 @@ describe("previewStateStore (single-tab)", () => {
pictureInPicture: false,
colorScheme: "system",
controller: "none",
favicon: null,
});
reconcilePreviewServerSessions(ref, { sessions: [active], serverEpoch, revision: 1 });
@@ -504,6 +507,7 @@ describe("previewStateStore (single-tab)", () => {
pictureInPicture: false,
colorScheme: "system",
controller: "none",
favicon: null,
});
const restarted = makeSnapshot({
navStatus: { _tag: "Success", url: "https://new.example", title: "New" },
+2
View File
@@ -9,6 +9,7 @@ import { useAtomValue } from "@effect/atom-react";
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import {
type DesktopPreviewColorScheme,
type DesktopPreviewFavicon,
type PreviewEvent,
type PreviewListResult,
type PreviewSessionSnapshot,
@@ -28,6 +29,7 @@ export interface DesktopPreviewOverlay {
pictureInPicture: boolean;
colorScheme: DesktopPreviewColorScheme;
controller: "human" | "agent" | "none";
favicon: DesktopPreviewFavicon | null;
}
export interface ThreadPreviewState {
@@ -175,6 +175,7 @@ const PULL_REQUESTS_PANEL_ENVIRONMENT_ID = "pull-requests-panel" as EnvironmentI
/** Stable so a read that is not wanted right now does not re-key on every render. */
const NO_LIST_TARGETS: ReadonlyArray<EnvironmentQueryTarget<PullRequestListInput>> = [];
const EMPTY_PREVIEW_SESSIONS = {};
const EMPTY_PREVIEW_DESKTOP_STATE = {};
const EMPTY_TERMINAL_LABELS = new Map<string, string>();
const EMPTY_PENDING_SURFACES = new Set<string>();
@@ -1540,6 +1541,7 @@ function PullRequestsRouteView() {
activeSurfaceId={activePullRequestSurface.id}
pendingSurfaceIds={EMPTY_PENDING_SURFACES}
previewSessions={EMPTY_PREVIEW_SESSIONS}
desktopByTabId={EMPTY_PREVIEW_DESKTOP_STATE}
terminalLabelsById={EMPTY_TERMINAL_LABELS}
onActivate={(surface) => {
if (surface.kind === "pull-request") activateSurface(surface);