diff --git a/apps/server/src/admin.ts b/apps/server/src/admin.ts index 60859d7..c30496f 100644 --- a/apps/server/src/admin.ts +++ b/apps/server/src/admin.ts @@ -22,6 +22,7 @@ import { fetchGitHubAccount, fetchGitHubRepos, GitHubRejected } from "./github.t import type { Clients } from "./auth/clients.ts"; import { message, providerValues, type Fleet } from "./fleet.ts"; import type { Hub } from "./gateway/hub.ts"; +import { keptIconHeaders, projectIcon } from "./gateway/icons.ts"; import type { T3Gateway } from "./gateway/http.ts"; import { githubName } from "./gateway/repos.ts"; import { isWorking } from "./gateway/types.ts"; @@ -255,6 +256,12 @@ export class Admin { const { addresses } = await this.deps.network.info(request); return json(await Promise.all(addresses.map((address) => testAddress(address.url, settings.get("bridgeId"))))); } + if (section === "projects" && id && action === "icon" && method === "GET") { + const icon = hub.icons.get(id); + const file = icon && hub.icons.file(icon.revision); + if (!file) return json({ error: "This project has no logo." }, 404); + return new Response(file, { headers: keptIconHeaders(file.type) }); + } if (section === "network" && id && !action && method === "POST") { const changed = await this.deps.network.change(id, await body(request)); return changed ? json(changed) : json({ error: "Not found." }, 404); @@ -735,6 +742,7 @@ export class Admin { projects: projects.map((project) => ({ id: project.id, title: project.title, + icon: projectIcon(project.id, project.title, hub.pickedIcon(project.id), hub.icons.get(project.id)), url: project.url, branch: project.branch, vmIds: project.vms.map((entry) => entry.vmId), diff --git a/apps/server/src/db.ts b/apps/server/src/db.ts index 2449c23..b1af424 100644 --- a/apps/server/src/db.ts +++ b/apps/server/src/db.ts @@ -317,6 +317,18 @@ export const migrations = [ FOREIGN KEY (project_id, vm_id) REFERENCES project_vms(project_id, vm_id) ON DELETE CASCADE ); `, + // The logo T3 finds in each project's repository, kept from when a VM holding it was last awake (see gateway/icons.ts). + ` + CREATE TABLE project_icons ( + project_id TEXT PRIMARY KEY REFERENCES projects(id) ON DELETE CASCADE, + content_type TEXT NOT NULL, + data BLOB NOT NULL, + revision TEXT NOT NULL, + name TEXT NOT NULL, + fetched_at INTEGER NOT NULL + ); + CREATE INDEX project_icons_revision ON project_icons (revision); + `, ]; /** diff --git a/apps/server/src/gateway/http.ts b/apps/server/src/gateway/http.ts index 0c0d881..be1c74c 100644 --- a/apps/server/src/gateway/http.ts +++ b/apps/server/src/gateway/http.ts @@ -5,6 +5,7 @@ import type { Frame } from "../vm/backend.ts"; import type { WatchUpgrade } from "../watch/watch.ts"; import { assetPrefix, bridgeAssetUrl, heldOwner, relayedAsset, uploadPrefix } from "./attachments.ts"; import { bridgeAuth, bridgeScopes, type Hub } from "./hub.ts"; +import { iconOwner, keptIconHeaders } from "./icons.ts"; import { previewQuery, previewRelay, previewStreamPath } from "./preview.ts"; import type { Rpc, RpcClient } from "./rpc.ts"; import { historyPage, latestOrdinal } from "./saved.ts"; @@ -301,9 +302,15 @@ export class T3Gateway { /** * An asset, from the VM that signed its URL. A VM that is not awake is not woken for it, and the client shows the - * asset as missing. An upload VM Bridge still holds is served from here, as a download unless it is an image. + * asset as missing. An upload VM Bridge still holds is served from here, as a download unless it is an image, and + * so is a project logo it kept. */ private async asset(request: Request, owner: string, token: string, name: string) { + if (owner === iconOwner) { + const file = this.hub.icons.file(token); + if (!file) return notFound(); + return new Response(request.method === "HEAD" ? null : file, { headers: keptIconHeaders(file.type) }); + } if (owner === heldOwner) { const file = this.hub.attachments.file(token); if (!file) return notFound(); diff --git a/apps/server/src/gateway/hub.ts b/apps/server/src/gateway/hub.ts index 2503c56..abfdb60 100644 --- a/apps/server/src/gateway/hub.ts +++ b/apps/server/src/gateway/hub.ts @@ -16,6 +16,7 @@ import { defaultAgents, pendingAgent, presentAgent, type AgentReport } from "./a import { Attachments, maxUploadBytes } from "./attachments.ts"; import type { FileTrees, Worktree } from "./files.ts"; import { applyHeldCommand, nextTurnCommandTypes } from "./held.ts"; +import { ProjectIcons } from "./icons.ts"; import { isPathKey, projectForPath, projectRoot, translate, vmForPath, within, type Environments } from "./paths.ts"; import { repositoryIdentity } from "./repos.ts"; import { threadStamp } from "./saved.ts"; @@ -141,6 +142,8 @@ export class Hub extends EventEmitter { private sequence: number; /** Uploads waiting for the message that sends them. */ readonly attachments: Attachments; + /** Each project's logo, kept for while its VMs sleep. */ + readonly icons: ProjectIcons; constructor( readonly store: Store, @@ -155,6 +158,7 @@ export class Hub extends EventEmitter { super(); this.setMaxListeners(0); this.attachments = new Attachments(store.db); + this.icons = new ProjectIcons(store.db); this.reported = new Map([...store.snapshots("shell")].map(([vmId, shell]) => [vmId, this.owned(vmId, shell)])); for (const vmId of this.reported.keys()) this.overlay(vmId); this.configs = store.snapshots("config"); @@ -289,6 +293,10 @@ export class Hub extends EventEmitter { if (updated) this.refreshProjectionSoon(vmId, updated.id); const backend = this.fleet.backend(vmId); if (item.kind === "snapshot" && !enrichment && backend) void this.saveThreads(vmId, backend, reported, connectSaveMs); + if (backend && ((item.kind === "snapshot" && !enrichment) || item.kind === "project.updated")) { + const only = item.kind === "project.updated" ? item.project?.id : undefined; + this.refreshIcons(vmId, backend, only); + } const working = hasLiveWork(shell); if (working) this.fleet.touch(vmId); // Shown as soon as the VM reports it, rather than on the next idle sweep. @@ -297,6 +305,29 @@ export class Hub extends EventEmitter { this.emit("shell"); } + /** + * Asks a VM's T3 for the logos of the projects it is the primary VM of, or of one, to keep for while it sleeps. + * Only the primary asks, so a second VM still cloning a project does not report it without one. + */ + private refreshIcons(vmId: string, backend: Backend, only?: string) { + for (const project of this.reported.get(vmId)?.projects ?? []) { + const cwd = str(project.workspaceRoot); + if (!cwd || (only && project.id !== only)) continue; + const registered = this.store.project(project.id); + if (!registered || primaryVm(registered)?.vmId !== vmId) continue; + void this.icons.refresh(project.id, cwd, backend); + } + } + + /** The icon picked for a project in T3, from the shell a VM holding it last reported. */ + pickedIcon(projectId: string): unknown { + for (const shell of this.shells.values()) { + const project = shell.projects?.find((row) => row.id === projectId); + if (project?.projectIcon) return project.projectIcon; + } + return null; + } + /** Records a thread's latest run as a turn for analytics, once per run. Only IDs and names: never messages. */ private recordTurn(vmId: string, thread: Row) { const runId = str(thread.activeRunId) ?? str(thread.latestRunId); diff --git a/apps/server/src/gateway/icons.ts b/apps/server/src/gateway/icons.ts new file mode 100644 index 0000000..86d49d0 --- /dev/null +++ b/apps/server/src/gateway/icons.ts @@ -0,0 +1,133 @@ +import type { ProjectIcon, ProjectIconColor } from "@vmbridge/contracts"; +import type { Sql } from "../sql.ts"; +import type { Backend } from "../vm/backend.ts"; +import { assetPrefix } from "./attachments.ts"; + +/** Stands where a VM ID goes in an asset URL, for a project logo VM Bridge keeps (see `ProjectIcons`). */ +export const iconOwner = "icon"; +/** The file name T3 gives a project with no logo file. */ +const missingMarker = "project-favicon-missing"; +/** Larger files are not kept: T3 shows them from the VM while it is awake. */ +const maxIconBytes = 512 * 1024; +const t3AssetUrl = /^\/api\/assets\/[\w.-]+\/([^/\\?#\s]+)$/; + +export interface StoredIcon { + contentType: string; + /** Hex SHA-256 of the bytes. It names the file in URLs, so only someone who has the logo can make its link. */ + revision: string; + /** T3's file name for it, which carries T3's own revision. */ + name: string; +} + +/** + * The logo T3 finds in each project's repository, such as a favicon, kept from the last time a VM holding the + * project was awake. The dashboard shows it, and T3 clients get it while the VM sleeps, when T3 cannot serve it. + */ +export class ProjectIcons { + private readonly refreshing = new Set(); + + constructor(private readonly db: Sql) {} + + get(projectId: string): StoredIcon | undefined { + return this.db.one("SELECT content_type AS contentType, revision, name FROM project_icons WHERE project_id = ?", projectId); + } + + file(revision: string) { + const row = this.db.one<{ contentType: string; data: Uint8Array | ArrayBuffer }>( + "SELECT content_type AS contentType, data FROM project_icons WHERE revision = ?", + revision, + ); + return row && new Blob([row.data], { type: row.contentType }); + } + + /** + * Asks the VM's T3 for a project's logo, the way T3 clients do, and keeps a copy. Skips the download when T3's + * file name, which changes with the file, is the one kept. A failure keeps the last copy. + */ + async refresh(projectId: string, cwd: string, backend: Pick) { + if (this.refreshing.has(projectId)) return; + this.refreshing.add(projectId); + try { + const result = await backend.call<{ relativeUrl?: unknown }>("assets.createUrl", { resource: { _tag: "project-favicon", cwd } }, 30_000); + const relativeUrl = typeof result?.relativeUrl === "string" ? result.relativeUrl : ""; + const name = t3AssetUrl.exec(relativeUrl)?.[1]; + if (!name) return; + if (name === missingMarker) { + this.db.run("DELETE FROM project_icons WHERE project_id = ?", projectId); + return; + } + if (this.get(projectId)?.name === name) return; + const response = await backend.http(relativeUrl); + const contentType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() ?? ""; + if (!response.ok || !contentType.startsWith("image/")) return; + const bytes = new Uint8Array(await response.arrayBuffer()); + if (bytes.byteLength === 0 || bytes.byteLength > maxIconBytes) return; + const revision = [...new Uint8Array(await crypto.subtle.digest("SHA-256", bytes))].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + this.db.run( + `INSERT INTO project_icons (project_id, content_type, data, revision, name, fetched_at) VALUES (?, ?, ?, ?, ?, ?) + ON CONFLICT (project_id) DO UPDATE SET content_type = excluded.content_type, data = excluded.data, + revision = excluded.revision, name = excluded.name, fetched_at = excluded.fetched_at`, + projectId, contentType, bytes, revision, name, Date.now(), + ); + } catch { + // The VM went to sleep, or its T3 has no logo route. The last copy stays. + } finally { + this.refreshing.delete(projectId); + } + } +} + +/** The URL T3 clients load a kept logo from. */ +export function iconAssetUrl(icon: StoredIcon) { + return `${assetPrefix}${iconOwner}.${icon.revision}/${encodeURIComponent(icon.name)}`; +} + +/** + * Headers for a kept logo. Its URL names its bytes, so it never changes. An SVG can hold scripts and VM Bridge's + * origin also serves the dashboard, so one opened as a page is sandboxed. + */ +export function keptIconHeaders(contentType: string) { + return { + "content-type": contentType, + "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; sandbox", + "x-content-type-options": "nosniff", + "cache-control": "private, max-age=31536000, immutable", + }; +} + +/** T3's colors for project letters, in T3's order: the color a name gets is picked by its place here. */ +const colors: readonly ProjectIconColor[] = [ + "gray", "red", "orange", "amber", "yellow", "lime", "green", "emerald", "teal", + "cyan", "sky", "blue", "indigo", "violet", "purple", "fuchsia", "pink", "rose", +]; + +/** T3's letters and color for a project with no icon of its own, worked out from its name as T3 does. */ +export function nameIcon(title: string): { text: string; color: ProjectIconColor } { + const name = title.normalize("NFKC").trim(); + const words = name.match(/[\p{L}\p{N}]+/gu) ?? []; + let text = "PR"; + const firstWord = words[0]; + if (firstWord) { + const glyphs = Array.from(firstWord); + const first = glyphs[0]!; + const second = glyphs.slice(1).find((glyph) => /\p{N}/u.test(glyph)) ?? (words.length > 1 ? Array.from(words.at(-1)!)[0] : glyphs.at(-1)) ?? first; + text = Array.from(`${first}${second}`.toUpperCase()).slice(0, 2).join(""); + } + let index = 0; + for (const glyph of name.toLocaleLowerCase("en-US") || "project") index = (index * 31 + glyph.codePointAt(0)!) % colors.length; + return { text, color: colors[index]! }; +} + +/** + * The icon T3 shows for a project, in T3's order: the one picked in T3, then the logo in its repository, then + * letters from its name. A picked icon from T3's icon set is shown as letters in its color. + */ +export function projectIcon(projectId: string, title: string, picked: unknown, stored: StoredIcon | undefined): ProjectIcon { + const choice = (picked ?? {}) as { kind?: unknown; text?: unknown; emoji?: unknown; color?: unknown }; + const color = colors.find((entry) => entry === choice.color); + if (choice.kind === "monogram" && typeof choice.text === "string" && color) return { kind: "monogram", text: choice.text, color }; + if (choice.kind === "emoji" && typeof choice.emoji === "string") return { kind: "emoji", emoji: choice.emoji }; + if (choice.kind === "lucide" && color) return { kind: "monogram", text: nameIcon(title).text, color }; + if (stored) return { kind: "image", url: `/admin/api/projects/${encodeURIComponent(projectId)}/icon?v=${stored.revision}` }; + return { kind: "monogram", ...nameIcon(title) }; +} diff --git a/apps/server/src/gateway/rpc.ts b/apps/server/src/gateway/rpc.ts index 9add0af..ae9e8a9 100644 --- a/apps/server/src/gateway/rpc.ts +++ b/apps/server/src/gateway/rpc.ts @@ -7,6 +7,7 @@ import type { Clones } from "./clones.ts"; import type { FileTrees } from "./files.ts"; import { isHeldCommand } from "./held.ts"; import type { Hub } from "./hub.ts"; +import { iconAssetUrl } from "./icons.ts"; import { projectForPath, projectRoot } from "./paths.ts"; import { githubName, githubRepository, type RemoteBranches } from "./repos.ts"; import { str, type Row, type Wire } from "./types.ts"; @@ -695,7 +696,8 @@ export class Rpc { /** * An asset URL from the VM that has the asset, made to point at VM Bridge, which relays it. Like other reads, it does - * not wake a sleeping VM. An upload VM Bridge still holds is its own to answer for. + * not wake a sleeping VM. An upload VM Bridge still holds is its own to answer for, and so is a sleeping VM's project + * logo it kept. */ private async assetUrl(call: Call) { const resource = (call.payload.resource ?? {}) as Wire; @@ -706,7 +708,13 @@ export class Rpc { // The client tells this error apart: a pending upload it cannot find is one to upload again. if (!vmId) return call.client.send(tagged(call.id, { _tag: "AssetAttachmentNotFoundError", resource })); const backend = this.hub.fleet.backend(vmId); - if (!backend) throw new Error("This VM is asleep. Sending a message wakes it."); + if (!backend) { + const cwd = resource._tag === "project-favicon" ? str(resource.cwd) : undefined; + const project = cwd ? projectForPath(cwd, this.hub.projects()) : undefined; + const icon = project ? this.hub.icons.get(project.id) : undefined; + if (icon) return this.reply(call, { relativeUrl: iconAssetUrl(icon), expiresAt: Date.now() + 60 * 60_000 }); + throw new Error("This VM is asleep. Sending a message wakes it."); + } const exit = await new Promise((resolve, reject) => { try { backend.request(call.tag, this.hub.into(call.payload, vmId), (frame) => frame._tag === "Exit" && resolve(frame)); diff --git a/apps/server/test/icons.test.ts b/apps/server/test/icons.test.ts new file mode 100644 index 0000000..474f9ae --- /dev/null +++ b/apps/server/test/icons.test.ts @@ -0,0 +1,99 @@ +import { EventEmitter } from "node:events"; +import { expect, test } from "bun:test"; +import { Clients } from "../src/auth/clients.ts"; +import { openDatabase } from "../src/bun/sqlite.ts"; +import type { Fleet } from "../src/fleet.ts"; +import { T3Gateway } from "../src/gateway/http.ts"; +import { Hub } from "../src/gateway/hub.ts"; +import { nameIcon, projectIcon } from "../src/gateway/icons.ts"; +import { Rpc, type RpcClient } from "../src/gateway/rpc.ts"; +import type { Wire } from "../src/gateway/types.ts"; +import { Settings } from "../src/settings.ts"; +import { Store } from "../src/store.ts"; +import type { Traffic } from "../src/traffic.ts"; +import type { Backend } from "../src/vm/backend.ts"; +import { testEncryption } from "./key.ts"; + +const projectId = "p1"; +const png = new Uint8Array([137, 80, 78, 71, 1, 2, 3]); + +/** A VM's T3 that answers project logo requests with `name`, and serves `png` for it. */ +function fakeT3() { + const state = { name: "v1-favicon.png", downloads: 0 }; + const backend = { + call: async (tag: string, payload: Wire) => { + expect(tag).toBe("assets.createUrl"); + expect(payload).toEqual({ resource: { _tag: "project-favicon", cwd: "/workspace/fikrabot" } }); + return { relativeUrl: `/api/assets/signed.token/${state.name}`, expiresAt: 1 }; + }, + http: async () => { + state.downloads++; + return new Response(png, { headers: { "content-type": "image/png" } }); + }, + } as unknown as Backend; + return { backend, state }; +} + +/** VM Bridge with project p1 on VM vm1, which is asleep. */ +function setup() { + const store = new Store(openDatabase(":memory:"), testEncryption); + store.insertVm({ id: "vm1", provider: "kubi", name: "vm1", size: "medium", state: "sleeping", createdAt: 0 }); + store.insertProject({ id: projectId, url: "https://github.com/a/fikrabot", branch: null, title: "fikrabot", createdAt: 0 }); + store.addProjectVm(projectId, "vm1"); + const fleet = Object.assign(new EventEmitter(), { backend: () => undefined, connected: () => [] }) as unknown as Fleet; + const traffic = { record: () => {}, refused: () => {} } as unknown as Traffic; + const hub = new Hub(store, new Settings(store.db), fleet, traffic, { get: () => null, lastDisk: () => null }); + const rpc = new Rpc(hub, {} as never, {} as never, traffic, () => false); + const gateway = new T3Gateway(hub, rpc, new Clients(store.db)); + const sent: Wire[] = []; + const client: RpcClient = { clientId: "c1", cancels: new Map(), send: (frame) => sent.push(frame as Wire), open: () => true }; + const createUrl = async () => { + await rpc.handle(client, { _tag: "Request", id: 1, tag: "assets.createUrl", payload: { resource: { _tag: "project-favicon", cwd: `/projects/${projectId}` } } }); + for (let tries = 0; tries < 20 && !sent.length; tries++) await Bun.sleep(0); + return sent.pop()!.exit as { _tag: string; value?: { relativeUrl: string } }; + }; + const fetch = (path: string) => gateway.fetch(new Request(`http://bridge${path}`), () => null, () => null) as Promise; + return { hub, createUrl, fetch, close: () => (gateway.close(), hub.close()) }; +} + +test("a project's logo is kept while its VM is awake, and T3 clients get it while the VM sleeps", async () => { + const { hub, createUrl, fetch, close } = setup(); + expect((await createUrl())._tag).toBe("Failure"); + + const t3 = fakeT3(); + await hub.icons.refresh(projectId, "/workspace/fikrabot", t3.backend); + const minted = await createUrl(); + expect(minted._tag).toBe("Success"); + const url = minted.value!.relativeUrl; + // Named by the logo's hash, which only someone who has the logo can work out, and T3's own file name. + expect(url).toMatch(/^\/api\/assets\/icon\.[0-9a-f]{64}\/v1-favicon\.png$/); + const served = await fetch(url); + expect(new Uint8Array(await served.arrayBuffer())).toEqual(png); + expect(served.headers.get("content-type")).toBe("image/png"); + expect(served.headers.get("content-security-policy")).toContain("sandbox"); + expect((await fetch(url.replace(/icon\.[0-9a-f]+/, `icon.${"0".repeat(64)}`))).status).toBe(404); + + // The same file is not downloaded again. A project whose logo was removed loses the copy. + await hub.icons.refresh(projectId, "/workspace/fikrabot", t3.backend); + expect(t3.state.downloads).toBe(1); + t3.state.name = "project-favicon-missing"; + await hub.icons.refresh(projectId, "/workspace/fikrabot", t3.backend); + expect((await createUrl())._tag).toBe("Failure"); + expect((await fetch(url)).status).toBe(404); + close(); +}); + +test("the dashboard shows the icon T3 would: the one picked in T3, then the logo, then letters from the name", () => { + const stored = { contentType: "image/png", revision: "abc", name: "v1-favicon.png" }; + expect(projectIcon("p1", "fikrabot", { kind: "emoji", emoji: "๐Ÿš€" }, stored)).toEqual({ kind: "emoji", emoji: "๐Ÿš€" }); + expect(projectIcon("p1", "fikrabot", { kind: "monogram", text: "FB", color: "teal" }, stored)).toEqual({ kind: "monogram", text: "FB", color: "teal" }); + // T3's icon set is not in the dashboard: its color, with the name's letters. + expect(projectIcon("p1", "fikrabot", { kind: "lucide", name: "rocket", color: "rose" }, stored)).toEqual({ kind: "monogram", text: "FT", color: "rose" }); + expect(projectIcon("p1", "fikrabot", null, stored)).toEqual({ kind: "image", url: "/admin/api/projects/p1/icon?v=abc" }); + expect(projectIcon("p1", "fikrabot", null, undefined)).toEqual({ kind: "monogram", ...nameIcon("fikrabot") }); + + expect(nameIcon("fikrabot").text).toBe("FT"); + expect(nameIcon("vm bridge").text).toBe("VB"); + expect(nameIcon("app2-web").text).toBe("A2"); + expect(nameIcon("--").text).toBe("PR"); +}); diff --git a/apps/server/test/placement.test.ts b/apps/server/test/placement.test.ts index fbc076c..dd352df 100644 --- a/apps/server/test/placement.test.ts +++ b/apps/server/test/placement.test.ts @@ -91,7 +91,7 @@ describe("upgrading a database from one VM per project", () => { const path = join(dir, "main.db"); // Back to the schema before project_vms, tracked by user_version, with a project on a VM as that version stored it. const old = openDatabase(path); - old.exec("DROP TABLE vm_file_lists; DROP TABLE project_vms; DROP TABLE base_snapshots; DROP TABLE retired_snapshots; DROP TABLE errors; DROP TABLE vm_usage; DROP TABLE snapshot_usage; DROP TABLE vm_events; DROP TABLE turns; DROP TABLE agent_profiles; DROP TABLE instructions; DROP TABLE watch_links; DROP TABLE attachment_chunks; DROP TABLE attachment_uploads; DROP TABLE file_trees; ALTER TABLE clients DROP COLUMN last_connected_at; DROP TABLE projection_parts; ALTER TABLE projections DROP COLUMN stamp; DROP TABLE migrations; PRAGMA user_version = 5;"); + old.exec("DROP TABLE project_icons; DROP TABLE vm_file_lists; DROP TABLE project_vms; DROP TABLE base_snapshots; DROP TABLE retired_snapshots; DROP TABLE errors; DROP TABLE vm_usage; DROP TABLE snapshot_usage; DROP TABLE vm_events; DROP TABLE turns; DROP TABLE agent_profiles; DROP TABLE instructions; DROP TABLE watch_links; DROP TABLE attachment_chunks; DROP TABLE attachment_uploads; DROP TABLE file_trees; ALTER TABLE clients DROP COLUMN last_connected_at; DROP TABLE projection_parts; ALTER TABLE projections DROP COLUMN stamp; DROP TABLE migrations; PRAGMA user_version = 5;"); old.run("INSERT INTO vms (id, provider, name, size, state, created_at) VALUES ('vm1', 'boxd', 'vm1', 'medium', 'sleeping', 0)"); old.run("INSERT INTO projects (id, url, title, vm_id, checkout_path, created_at) VALUES ('p1', 'https://github.com/acme/app.git', 'app', 'vm1', '/workspace/app', 0)"); old.run("INSERT INTO projects (id, url, title, created_at) VALUES ('p2', 'https://github.com/acme/web.git', 'web', 1)"); diff --git a/apps/web/src/Canvas.tsx b/apps/web/src/Canvas.tsx index a38a7f9..4cd4edb 100644 --- a/apps/web/src/Canvas.tsx +++ b/apps/web/src/Canvas.tsx @@ -16,7 +16,7 @@ import { type NodeProps, } from "@xyflow/react"; import { HugeiconsIcon } from "@hugeicons/react"; -import { Add01Icon, Alert02Icon, Cancel01Icon, CenterFocusIcon, Delete02Icon, Folder01Icon, InformationCircleIcon, LaptopIcon, Message01Icon, Moon02Icon, PowerIcon, ZoomInIcon, ZoomOutIcon } from "@hugeicons/core-free-icons"; +import { Add01Icon, Alert02Icon, Cancel01Icon, CenterFocusIcon, Delete02Icon, InformationCircleIcon, LaptopIcon, Message01Icon, Moon02Icon, PowerIcon, ZoomInIcon, ZoomOutIcon } from "@hugeicons/core-free-icons"; import { vmSizes, type BridgeUpdate, type ClientInfo, type Overview, type ProjectInfo, type ProviderId, type TrafficEvent, type Usage, type VmInfo, type VmSize, type VmState, type VmStats } from "@vmbridge/contracts"; import { AlertDialog, @@ -54,7 +54,7 @@ import { useAction } from "@/hooks/use-action"; import { sinceText } from "@/lib/devices"; import { cn } from "@/lib/utils"; import { ago, api, useTick } from "./api.ts"; -import { Logo, ProviderLogo } from "./brand.tsx"; +import { Logo, ProjectIcon, ProviderLogo } from "./brand.tsx"; import { CopyButton } from "./CopyButton.tsx"; /** A connection animates while it carried a request this recently. */ @@ -254,7 +254,7 @@ function VmCard({ data }: NodeProps) {
{shown.map((project) => ( - + {project.title} {project.vmIds.length > 1 && ( @@ -816,8 +816,8 @@ function VmDetails({ vm, overview, now, onClose }: { vm: VmInfo; overview: Overv {projects.map((project) => ( - - + + {project.title} @@ -831,17 +831,25 @@ function VmDetails({ vm, overview, now, onClose }: { vm: VmInfo; overview: Overv

Sessions

{vm.sessions.length === 0 &&

No sessions.

} - {vm.sessions.map((session) => ( - - - - {session.title} - {session.status} - - {[session.provider, session.model].filter(Boolean).join(" ยท ") || "No model"} - - - ))} + {vm.sessions.map((session) => { + const project = overview.projects.find((entry) => entry.id === session.projectId); + return ( + + {project && ( + + + + )} + + + {session.title} + {session.status} + + {[session.provider, session.model].filter(Boolean).join(" ยท ") || "No model"} + + + ); + })}
diff --git a/apps/web/src/brand.tsx b/apps/web/src/brand.tsx index 20e9431..c5c2cbb 100644 --- a/apps/web/src/brand.tsx +++ b/apps/web/src/brand.tsx @@ -1,4 +1,4 @@ -import type { AgentKind, ProviderId } from "@vmbridge/contracts"; +import type { AgentKind, ProjectIcon as ProjectIconInfo, ProjectIconColor, ProviderId } from "@vmbridge/contracts"; import { cn } from "@/lib/utils"; import claude from "./assets/agents/claude.svg"; import codex from "./assets/agents/codex.svg"; @@ -65,3 +65,47 @@ export function AgentLogo({ agent, className }: { agent: AgentKind; className?: ); } + +// Whole class names, so Tailwind sees each one. The shades T3 uses on a dark background. +const projectColors: Record = { + gray: "text-gray-400", + red: "text-red-400", + orange: "text-orange-400", + amber: "text-amber-400", + yellow: "text-yellow-400", + lime: "text-lime-400", + green: "text-green-400", + emerald: "text-emerald-400", + teal: "text-teal-400", + cyan: "text-cyan-400", + sky: "text-sky-400", + blue: "text-blue-400", + indigo: "text-indigo-400", + violet: "text-violet-400", + purple: "text-purple-400", + fuchsia: "text-fuchsia-400", + pink: "text-pink-400", + rose: "text-rose-400", +}; + +/** A project's icon as T3 shows it: its repository's logo, an emoji, or letters on a tile of their color. */ +export function ProjectIcon({ icon, className }: { icon: ProjectIconInfo; className?: string }) { + const box = cn("inline-flex size-4 shrink-0 items-center justify-center", className); + if (icon.kind === "image") return ; + if (icon.kind === "emoji") { + return ( + + ); + } + return ( + + ); +} diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index e8addfa..cbd318e 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -330,9 +330,21 @@ export interface SkillSearchResult { installs: number; } +/** T3's colors for a project's letters. */ +export type ProjectIconColor = + | "gray" | "red" | "orange" | "amber" | "yellow" | "lime" | "green" | "emerald" | "teal" + | "cyan" | "sky" | "blue" | "indigo" | "violet" | "purple" | "fuchsia" | "pink" | "rose"; + +/** The icon T3 shows for a project: its repository's logo, or letters or an emoji. */ +export type ProjectIcon = + | { kind: "image"; url: string } + | { kind: "monogram"; text: string; color: ProjectIconColor } + | { kind: "emoji"; emoji: string }; + export interface ProjectInfo { id: string; title: string; + icon: ProjectIcon; url: string; branch: string | null; /** VMs holding the project, primary first. */