Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions apps/server/src/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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),
Expand Down
12 changes: 12 additions & 0 deletions apps/server/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
`,
];

/**
Expand Down
9 changes: 8 additions & 1 deletion apps/server/src/gateway/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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();
Expand Down
31 changes: 31 additions & 0 deletions apps/server/src/gateway/hub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -141,6 +142,8 @@ export class Hub extends EventEmitter<HubEvents> {
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,
Expand All @@ -155,6 +158,7 @@ export class Hub extends EventEmitter<HubEvents> {
super();
this.setMaxListeners(0);
this.attachments = new Attachments(store.db);
this.icons = new ProjectIcons(store.db);
this.reported = new Map([...store.snapshots<Shell>("shell")].map(([vmId, shell]) => [vmId, this.owned(vmId, shell)]));
for (const vmId of this.reported.keys()) this.overlay(vmId);
this.configs = store.snapshots<ServerConfig>("config");
Expand Down Expand Up @@ -289,6 +293,10 @@ export class Hub extends EventEmitter<HubEvents> {
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.
Expand All @@ -297,6 +305,29 @@ export class Hub extends EventEmitter<HubEvents> {
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);
Expand Down
133 changes: 133 additions & 0 deletions apps/server/src/gateway/icons.ts
Original file line number Diff line number Diff line change
@@ -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<string>();

constructor(private readonly db: Sql) {}

get(projectId: string): StoredIcon | undefined {
return this.db.one<StoredIcon>("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> | 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<Backend, "call" | "http">) {
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) };
}
12 changes: 10 additions & 2 deletions apps/server/src/gateway/rpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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;
Expand All @@ -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<Frame>((resolve, reject) => {
try {
backend.request(call.tag, this.hub.into(call.payload, vmId), (frame) => frame._tag === "Exit" && resolve(frame));
Expand Down
Loading