From 49a49d68cefcf85cba0b3777156512a7306a8fca Mon Sep 17 00:00:00 2001 From: James Babcock Date: Sun, 4 Oct 2026 03:07:38 -0700 Subject: [PATCH] Add glanceboard widget for T3code --- app/apps/glanceboard/configuration.ts | 21 ++- app/apps/glanceboard/glanceboard-settings.ts | 3 +- app/apps/glanceboard/widget.ts | 2 +- app/apps/glanceboard/widgets/index.ts | 2 + app/apps/glanceboard/widgets/t3code-widget.ts | 122 ++++++++++++++++++ app/apps/t3code/background.ts | 11 ++ app/apps/t3code/index.ts | 27 +++- app/apps/t3code/t3-glance.ts | 103 +++++++++++++++ app/apps/t3code/t3-model.ts | 21 +++ app/apps/t3code/t3code-app.worker.ts | 101 +++++++++++---- tests/t3code-glance.test.cjs | 71 ++++++++++ tests/tsconfig.json | 3 +- 12 files changed, 453 insertions(+), 34 deletions(-) create mode 100644 app/apps/glanceboard/widgets/t3code-widget.ts create mode 100644 app/apps/t3code/background.ts create mode 100644 app/apps/t3code/t3-glance.ts create mode 100644 tests/t3code-glance.test.cjs diff --git a/app/apps/glanceboard/configuration.ts b/app/apps/glanceboard/configuration.ts index a783df47..36c40f5a 100644 --- a/app/apps/glanceboard/configuration.ts +++ b/app/apps/glanceboard/configuration.ts @@ -1,11 +1,24 @@ -import { getStringSetting } from "../../native/settings-store"; +import { getBooleanSetting, getStringSetting } from "../../native/settings-store"; import { QUADRANT_LAYOUT, SIX_SLOT_LAYOUT } from "./layout"; -/** Configuration-only query usable by workers without loading widget/UI modules. */ -export function isTerminalWidgetConfigured(): boolean { +/** Whether the current layout has `widgetId` in any slot (configuration only, enabled or not). */ +function isGlanceWidgetConfigured(widgetId: string): boolean { const layout = getStringSetting("glanceboard.layout", "2x2") === "2x3" ? SIX_SLOT_LAYOUT : QUADRANT_LAYOUT; // Both layouts store their slots under the original quadrants key. None // of the default slots needs a worker, so absent keys cannot retain one. return layout.slots.some((_, index) => - getStringSetting(`glanceboard.${QUADRANT_LAYOUT.id}.slot.${index}`, "none") === "terminal"); + getStringSetting(`glanceboard.${QUADRANT_LAYOUT.id}.slot.${index}`, "none") === widgetId); +} + +/** Configuration-only query usable by workers without loading widget/UI modules. */ +export function isTerminalWidgetConfigured(): boolean { + return isGlanceWidgetConfigured("terminal"); +} + +/** + * Whether the T3 Code widget can show: it is in a slot and the Glanceboard is + * enabled (the T3 worker holds its server connections open only then). + */ +export function isT3CodeWidgetInUse(): boolean { + return getBooleanSetting("glanceboard.enabled", false) && isGlanceWidgetConfigured("t3code"); } diff --git a/app/apps/glanceboard/glanceboard-settings.ts b/app/apps/glanceboard/glanceboard-settings.ts index 9478e695..0aa587f2 100644 --- a/app/apps/glanceboard/glanceboard-settings.ts +++ b/app/apps/glanceboard/glanceboard-settings.ts @@ -5,13 +5,14 @@ import { glanceWidgetSpans } from "./widgets"; export type GlanceSlotChoice = GlanceWidgetId | "none"; -const SLOT_CHOICES: readonly GlanceSlotChoice[] = ["none", "system-card", "calendar", "terminal", "nightscout", "compass", "music"]; +const SLOT_CHOICES: readonly GlanceSlotChoice[] = ["none", "system-card", "calendar", "terminal", "t3code", "nightscout", "compass", "music"]; const SLOT_CHOICE_LABELS: Record = { none: "Empty", "system-card": "System card", calendar: "Calendar", terminal: "Terminal", + t3code: "T3 Code", nightscout: "Nightscout", compass: "Compass", music: "Music", diff --git a/app/apps/glanceboard/widget.ts b/app/apps/glanceboard/widget.ts index 0f5c2d78..ba390647 100644 --- a/app/apps/glanceboard/widget.ts +++ b/app/apps/glanceboard/widget.ts @@ -27,7 +27,7 @@ export interface GlanceWidget { paint(image: GrayImage): void; } -export type GlanceWidgetId = "system-card" | "nightscout" | "compass" | "music" | "calendar" | "terminal"; +export type GlanceWidgetId = "system-card" | "nightscout" | "compass" | "music" | "calendar" | "terminal" | "t3code"; export type GlanceWidgetDefinition = { id: GlanceWidgetId; diff --git a/app/apps/glanceboard/widgets/index.ts b/app/apps/glanceboard/widgets/index.ts index fa15a5ec..aeee473f 100644 --- a/app/apps/glanceboard/widgets/index.ts +++ b/app/apps/glanceboard/widgets/index.ts @@ -4,6 +4,7 @@ import { CompassWidget } from "./compass-widget"; import { MusicWidget } from "./music-widget"; import { NightscoutWidget } from "./nightscout-widget"; import { SystemCardWidget } from "./system-card"; +import { T3CodeWidget } from "./t3code-widget"; import { TerminalWidget } from "./terminal-widget"; /** Every widget a board slot can hold. */ @@ -11,6 +12,7 @@ export const GLANCE_WIDGETS: readonly GlanceWidgetDefinition[] = [ { id: "system-card", label: "System card", create: () => new SystemCardWidget() }, { id: "calendar", label: "Calendar", tall: true, create: () => new CalendarWidget() }, { id: "terminal", label: "Terminal", tall: true, create: () => new TerminalWidget() }, + { id: "t3code", label: "T3 Code", tall: true, create: () => new T3CodeWidget() }, { id: "nightscout", label: "Nightscout", create: () => new NightscoutWidget() }, { id: "compass", label: "Compass", create: () => new CompassWidget() }, { id: "music", label: "Music", create: () => new MusicWidget() }, diff --git a/app/apps/glanceboard/widgets/t3code-widget.ts b/app/apps/glanceboard/widgets/t3code-widget.ts new file mode 100644 index 00000000..19ea3797 --- /dev/null +++ b/app/apps/glanceboard/widgets/t3code-widget.ts @@ -0,0 +1,122 @@ +import { type GrayImage, type UiFont } from "../../../graphics/image"; +import { truncateText } from "../../../graphics/textwrap"; +import { lineStep } from "../../../ui/metrics"; +import { onWorkerStateChanged, readWorkerState } from "../../../ui/shell/worker-state"; +import { loadEnvironments } from "../../t3code/t3-environments"; +import { glanceSummary, T3_GLANCE_STATE_KEY, type T3GlanceRow, type T3GlanceSnapshot } from "../../t3code/t3-glance"; +import { formatAge, threadMarker } from "../../t3code/t3-model"; +import { glanceFont } from "../glance-font"; +import { type GlanceWidget } from "../widget"; + +const PAD = 8; +/** A row fits while its glyph line clears this margin above the bottom edge. */ +const BOTTOM_MARGIN = 2; +const MINUTE_MS = 60_000; + +/** + * T3 Code's agent threads at a glance: how many need you and how many are + * working, then the threads themselves in the app's order (needs-you, then + * working, then recent) with the app's status marks. Approvals and questions + * say so at the right edge; other rows show how long ago they were active. + * Painted from the snapshot the T3 worker publishes; the app's boot hook + * keeps that worker connected while this widget is on an enabled board. + */ +export class T3CodeWidget implements GlanceWidget { + private snapshot = readWorkerState(T3_GLANCE_STATE_KEY) as T3GlanceSnapshot | undefined; + private unsubscribe: (() => void) | null = null; + private tick: ReturnType | null = null; + + start(requestRender: () => void): void { + this.stop(); + this.snapshot = readWorkerState(T3_GLANCE_STATE_KEY) as T3GlanceSnapshot | undefined; + this.unsubscribe = onWorkerStateChanged(T3_GLANCE_STATE_KEY, (snapshot) => { + this.snapshot = snapshot as T3GlanceSnapshot | undefined; + requestRender(); + }); + // Keeps the ages honest while the board stays up. + this.tick = setInterval(requestRender, MINUTE_MS); + } + + stop(): void { + this.unsubscribe?.(); + this.unsubscribe = null; + if (this.tick !== null) clearInterval(this.tick); + this.tick = null; + } + + paint(image: GrayImage): void { + const font = glanceFont.small(); + const step = lineStep(font); + const textWidth = image.width - 2 * PAD; + const snapshot = this.snapshot; + let y = PAD; + + const title = "T3 Code"; + image.drawText(font, PAD, y, title, 150); + const summary = snapshot ? glanceSummary(snapshot) : ""; + if (summary) { + const text = truncateText(font, summary, textWidth - font.measureText(title) - 12); + image.drawText(font, image.width - PAD - font.measureText(text), y, text, snapshot!.needsYou ? 230 : 140); + } + y += step; + + const message = !snapshot + ? noWorkerMessage() + : !snapshot.configured + ? "Pair a computer in the T3 Code app" + : snapshot.status || (!snapshot.rows.length ? "No active threads" : ""); + if (message) { + image.drawText(font, PAD, y, truncateText(font, message, textWidth), 120); + return; + } + + const rows = snapshot!.rows; + // Rows are placed a line step apart but only need their line height to fit. + const capacity = Math.max(0, Math.floor((image.height - BOTTOM_MARGIN - y - font.lineHeight) / step) + 1); + const hidden = rows.length + snapshot!.more - capacity; + const shown = hidden > 0 ? rows.slice(0, Math.max(0, capacity - 1)) : rows; + const nowMs = Date.now(); + const markerWidth = font.measureText("W") + 7; + for (const row of shown) { + paintRow(image, font, row, PAD, y, textWidth, markerWidth, nowMs); + y += step; + } + if (hidden > 0) { + image.drawText(font, PAD + markerWidth, y, `+${rows.length + snapshot!.more - shown.length} more`, 110); + } + } +} + +/** Before the T3 worker publishes anything (or after it stopped for lack of anything to connect to). */ +function noWorkerMessage(): string { + const environments = loadEnvironments(); + if (!environments.length) return "Pair a computer in the T3 Code app"; + if (!environments.some((environment) => environment.enabled)) return "Disconnected in the T3 Code app"; + return "Connecting…"; +} + +function rowRightText(row: T3GlanceRow, nowMs: number): string { + if (row.status === "approval") return row.requestKind === "file-change" ? "approve edit" : "approve"; + if (row.status === "input") return "question"; + return formatAge(row.activityMs, nowMs); +} + +function paintRow( + image: GrayImage, + font: UiFont, + row: T3GlanceRow, + x: number, + y: number, + width: number, + markerWidth: number, + nowMs: number, +): void { + const { marker, value: markerValue } = threadMarker(row.status, { unread: row.unread }); + if (marker) image.drawText(font, x, y, marker, markerValue); + const needsYou = row.status === "approval" || row.status === "input"; + const right = rowRightText(row, nowMs); + const rightWidth = right ? font.measureText(right) + 8 : 0; + if (right) image.drawText(font, x + width - font.measureText(right), y, right, needsYou ? 230 : 110); + const value = needsYou ? 255 : row.status === "working" || row.unread ? 215 : 165; + image.drawText(font, x + markerWidth, y, truncateText(font, row.title, Math.max(10, width - markerWidth - rightWidth)), value); +} diff --git a/app/apps/t3code/background.ts b/app/apps/t3code/background.ts new file mode 100644 index 00000000..f72712e2 --- /dev/null +++ b/app/apps/t3code/background.ts @@ -0,0 +1,11 @@ +import { isT3CodeWidgetInUse } from "../glanceboard/configuration"; +import { loadEnvironments } from "./t3-environments"; + +/** + * Keep the T3 worker (and its server connections) running with no window + * open, for the Glanceboard widget. The app's boot hook spawns the worker + * whenever this turns true; the worker reports idle once it turns false. + */ +export function hasT3BackgroundWork(): boolean { + return isT3CodeWidgetInUse() && loadEnvironments().some((environment) => environment.enabled); +} diff --git a/app/apps/t3code/index.ts b/app/apps/t3code/index.ts index 886b4e81..3c7fa43d 100644 --- a/app/apps/t3code/index.ts +++ b/app/apps/t3code/index.ts @@ -1,4 +1,13 @@ import { launchWorkerAppWindow, type AppDefinition } from "../app-definition"; +import { onSettingsStoreChanged } from "../../native/settings-store"; +import { hasT3BackgroundWork } from "./background"; +import { T3_ENVIRONMENTS_KEY } from "./t3-environments"; + +/** The one place the worker is constructed (string-literal path for the webpack worker loader). */ +const createWorker = () => new Worker("./t3code-app.worker"); + +/** The boot hook's settings listener; replaced if a controller boots again. */ +let stopWatchingSettings: (() => void) | null = null; const t3codeApp: AppDefinition = { appId: "t3code", @@ -6,12 +15,28 @@ const t3codeApp: AppDefinition = { icon: "t3code", launch: (ctx) => launchWorkerAppWindow(ctx, { - createWorker: () => new Worker("./t3code-app.worker"), + createWorker, windowId: "t3code:main", title: "T3 Code", iconLetter: "T3", icon: "t3code", }), + /** + * The Glanceboard's T3 Code widget shows what this app's worker knows, so + * start the worker (windowless) whenever the widget is in use: at startup, + * and when the widget, the board, or the paired environments change. The + * worker reports idle by itself once nothing needs it. + */ + boot: (ctx) => { + const ensureWorker = () => { + if (hasT3BackgroundWork()) ctx.ensureWorkerHost(createWorker); + }; + ensureWorker(); + stopWatchingSettings?.(); + stopWatchingSettings = onSettingsStoreChanged((key) => { + if (key.startsWith("glanceboard.") || key === T3_ENVIRONMENTS_KEY) ensureWorker(); + }); + }, }; export default t3codeApp; diff --git a/app/apps/t3code/t3-glance.ts b/app/apps/t3code/t3-glance.ts new file mode 100644 index 00000000..05ba312e --- /dev/null +++ b/app/apps/t3code/t3-glance.ts @@ -0,0 +1,103 @@ +/** + * The T3 Code thread list as the Glanceboard shows it: the T3 worker builds + * this snapshot from its live connections and publishes it through the + * host's worker-state channel; the T3 Code widget paints it on the main + * thread. Plain JSON (it crosses postMessage) with timestamps rather than + * formatted ages, so the widget's "5m" is right whenever it paints. + * + * No NativeScript imports: this module is bundled into the worker as well. + */ +import { + isThreadUnread, + sectionThreads, + threadActivityMs, + threadStatus, + type T3ThreadShell, + type T3ThreadStatus, +} from "./t3-model"; + +/** Worker-state key the T3 worker publishes its snapshot under. */ +export const T3_GLANCE_STATE_KEY = "t3code:threads"; + +/** More than a double-height slot can show; the widget says how many it left out. */ +const MAX_ROWS = 24; + +export type T3GlanceRow = { + /** Environment id + thread id. */ + key: string; + title: string; + status: T3ThreadStatus; + /** A run finished since the thread was last visited (on any T3 client). */ + unread: boolean; + /** For approvals: what kind ("command", "file-change", ...). */ + requestKind: string | null; + /** Last activity, epoch ms (server clock). */ + activityMs: number; +}; + +export type T3GlanceSnapshot = { + /** Any environment is paired. */ + configured: boolean; + /** Why there is nothing to show when no environment is connected ("Connecting…", ...); "" otherwise. */ + status: string; + needsYou: number; + working: number; + /** Needs-you first, then working, then recent; settled and snoozed threads left out. */ + rows: T3GlanceRow[]; + /** Listed threads beyond `rows`. */ + more: number; +}; + +export type T3GlanceEnvironment = { + id: string; + ready: boolean; + /** "connecting", "retrying", "auth-failed", ... (T3EnvironmentClient phase). */ + phase: string; + enabled: boolean; + threads: Iterable; +}; + +export function buildGlanceSnapshot(environments: readonly T3GlanceEnvironment[], nowMs: number): T3GlanceSnapshot { + const owner = new Map(); + for (const environment of environments) { + if (!environment.ready) continue; + for (const thread of environment.threads) owner.set(thread, environment.id); + } + const sections = sectionThreads(owner.keys(), nowMs); + const listed = [...sections.attention, ...sections.working, ...sections.recent]; + const rows = listed.slice(0, MAX_ROWS).map((thread): T3GlanceRow => { + const status = threadStatus(thread); + return { + key: `${owner.get(thread)}:${thread.id}`, + title: thread.title || "Untitled", + status, + unread: isThreadUnread(thread), + requestKind: status === "approval" ? (thread.pendingRuntimeRequest?.kind ?? null) : null, + activityMs: threadActivityMs(thread), + }; + }); + return { + configured: environments.length > 0, + status: environments.some((environment) => environment.ready) ? "" : environmentsStatus(environments), + needsYou: sections.attention.length, + working: sections.working.filter((thread) => threadStatus(thread) === "working").length, + rows, + more: listed.length - rows.length, + }; +} + +function environmentsStatus(environments: readonly T3GlanceEnvironment[]): string { + if (!environments.length) return ""; + if (environments.every((environment) => !environment.enabled)) return "Disconnected"; + if (environments.some((environment) => environment.phase === "connecting" || environment.phase === "connected")) return "Connecting…"; + if (environments.every((environment) => !environment.enabled || environment.phase === "auth-failed")) return "Pair again in the T3 Code app"; + return "Can't reach T3 Code"; +} + +/** "1 needs you · 2 working" (or "" when neither). */ +export function glanceSummary(snapshot: Pick): string { + return [ + snapshot.needsYou ? `${snapshot.needsYou} need${snapshot.needsYou === 1 ? "s" : ""} you` : "", + snapshot.working ? `${snapshot.working} working` : "", + ].filter(Boolean).join(" · "); +} diff --git a/app/apps/t3code/t3-model.ts b/app/apps/t3code/t3-model.ts index 86d2a9f4..63ecab1e 100644 --- a/app/apps/t3code/t3-model.ts +++ b/app/apps/t3code/t3-model.ts @@ -261,6 +261,27 @@ export function threadStatusLabel(status: T3ThreadStatus): string { } } +const STATUS_MARKERS: Record = { + approval: { marker: "!", value: 255 }, + input: { marker: "?", value: 255 }, + working: { marker: "…", value: 210 }, + waiting: { marker: "…", value: 130 }, + failed: { marker: "x", value: 200 }, + limited: { marker: "x", value: 160 }, + ready: { marker: "", value: 0 }, +}; + +/** + * The one-glyph status mark drawn left of a thread title (in the app's list + * and on the Glanceboard), with its gray level: ! approval, ? question, + * … working, x failed, ● finished since last visited, ✓ settled. + */ +export function threadMarker(status: T3ThreadStatus, flags: { settled?: boolean; unread?: boolean } = {}): { marker: string; value: number } { + if (status === "ready" && flags.settled) return { marker: "✓", value: 110 }; + if (status === "ready" && flags.unread) return { marker: "●", value: 220 }; + return STATUS_MARKERS[status]; +} + function timeMs(value: string | null | undefined): number { if (!value) return 0; const parsed = Date.parse(value); diff --git a/app/apps/t3code/t3code-app.worker.ts b/app/apps/t3code/t3code-app.worker.ts index c4eb33b8..b4db75f4 100644 --- a/app/apps/t3code/t3code-app.worker.ts +++ b/app/apps/t3code/t3code-app.worker.ts @@ -19,8 +19,11 @@ * Double-click backs out a level, and from the list yields focus. * * Connections (one T3EnvironmentClient per paired environment) live while the - * window is open. Frames are painted here and submitted straight to the - * compositor from this worker's thread. + * window is open, and also with no window while the Glanceboard shows the + * T3 Code widget (the app's boot hook spawns this worker for it). Either way + * the worker publishes a thread-list snapshot for that widget. Frames are + * painted here and submitted straight to the compositor from this worker's + * thread. */ import "@nativescript/core/globals"; import { finishWorkerShutdown } from "../../ui/shell/worker-lifecycle"; @@ -49,6 +52,8 @@ import { import { exchangePairingCredential, fetchEnvironmentDescriptor, T3_ORCHESTRATION_PROTOCOL, type T3Fetch } from "./t3-auth"; import { errorMessage, T3EnvironmentClient, type StoredEnvironment, type ThreadHandle } from "./t3-client"; import { loadEnvironments, removeEnvironment, T3_ENVIRONMENTS_KEY, upsertEnvironment } from "./t3-environments"; +import { hasT3BackgroundWork } from "./background"; +import { buildGlanceSnapshot, glanceSummary, T3_GLANCE_STATE_KEY } from "./t3-glance"; import { approvalOptions, approvalResponseCommand, @@ -67,6 +72,7 @@ import { sectionThreads, settleCommand, threadActivityMs, + threadMarker, threadStatus, threadStatusLabel, timelineEntries, @@ -296,7 +302,7 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { const message = event.data; switch (message.type) { case "check-idle": - if (!window) post({ type: "worker-idle" }); + reportIdle(); break; case "shutdown": stopAllClients(); @@ -334,7 +340,8 @@ global.onmessage = (event: { data: WorkerAppMessage }) => { window = null; closeThreadView(); screen = { kind: "list" }; - stopAllClients(); + // The Glanceboard widget may still want the connections. + if (!hasT3BackgroundWork()) stopAllClients(); updateListRefreshTimer(); break; case "input": @@ -392,8 +399,20 @@ function inferForeground(focused: boolean): void { } onSettingsStoreChanged((key) => { + if (key.startsWith("glanceboard.")) { + // The widget was added or removed, or the board switched on or off. + if (!window) { + if (hasT3BackgroundWork()) syncClients(); + else { + stopAllClients(); + reportIdle(); + } + } + return; + } if (key === T3_ENVIRONMENTS_KEY) { - if (window) syncClients(); + if (window || hasT3BackgroundWork()) syncClients(); + else reportIdle(); render(); } else if (key === PAIRING_DRAFT_KEY) { // Live keystrokes from the phone editor. @@ -435,13 +454,54 @@ function syncClients(): void { client.updateConfig(environment); } persistedLabels.set(environment.id, environment.label); - if (environment.enabled && window) client.start(); + if (environment.enabled && (window || hasT3BackgroundWork())) client.start(); else if (!environment.enabled) client.stop(); } + schedulePublish(); } function stopAllClients(): void { for (const client of clients.values()) client.stop(); + schedulePublish(); +} + +/** Let the host shut this worker down once neither a window nor the widget needs it. */ +function reportIdle(): void { + if (!window && !hasT3BackgroundWork()) post({ type: "worker-idle" }); +} + +// --------------------------------------------------------------------------- +// Glanceboard snapshot + +const PUBLISH_COALESCE_MS = 300; +let publishTimer: ReturnType | null = null; +let lastPublishedSnapshot = ""; + +/** Publish soon; agents can change the thread list many times a second. */ +function schedulePublish(): void { + if (publishTimer) return; + publishTimer = setTimeout(() => { + publishTimer = null; + publishGlanceSnapshot(); + }, PUBLISH_COALESCE_MS); +} + +/** The thread list for the Glanceboard widget, posted only when its JSON changed. */ +function publishGlanceSnapshot(): void { + const snapshot = buildGlanceSnapshot( + [...clients.values()].map((client) => ({ + id: client.config.id, + ready: client.ready, + phase: client.phase, + enabled: client.config.enabled, + threads: client.shell.threads.values(), + })), + Date.now(), + ); + const encoded = JSON.stringify(snapshot); + if (encoded === lastPublishedSnapshot) return; + lastPublishedSnapshot = encoded; + post({ type: "publish-state", key: T3_GLANCE_STATE_KEY, state: snapshot }); } function onClientChanged(client: T3EnvironmentClient): void { @@ -453,6 +513,7 @@ function onClientChanged(client: T3EnvironmentClient): void { } noteAttention(client); if (screen.kind === "thread" && threadView && threadView.envId === client.config.id) maybeVisitThread(false); + schedulePublish(); scheduleRender(); } @@ -1152,26 +1213,8 @@ function selectionIndex(items: readonly ListItem[]): number | undefined { return index >= 0 ? index : undefined; } -const STATUS_MARKERS: Record = { - approval: { marker: "!", value: 255 }, - input: { marker: "?", value: 255 }, - working: { marker: "…", value: 210 }, - waiting: { marker: "…", value: 130 }, - failed: { marker: "x", value: 200 }, - limited: { marker: "x", value: 160 }, - ready: { marker: "", value: 0 }, -}; - function threadItem(client: T3EnvironmentClient, thread: T3ThreadShell, multiEnv: boolean, nowMs: number): ListItem { - const status = threadStatus(thread); - let { marker, value } = STATUS_MARKERS[status]; - if (status === "ready" && isThreadSettled(thread)) { - marker = "✓"; - value = 110; - } else if (status === "ready" && isThreadUnread(thread)) { - marker = "●"; - value = 220; - } + const { marker, value } = threadMarker(threadStatus(thread), { settled: isThreadSettled(thread), unread: isThreadUnread(thread) }); const project = client.shell.projects.get(thread.projectId)?.title ?? ""; const where = multiEnv ? [project, environmentName(client)].filter(Boolean).join(" · ") : project; const age = formatAge(threadActivityMs(thread), nowMs); @@ -1370,7 +1413,7 @@ function listStatusLine(): string { if (all.every((client) => !client.ready)) { return all.some((client) => client.phase === "connecting") ? "Connecting…" : "Not connected"; } - return [needs ? `${needs} need${needs === 1 ? "s" : ""} you` : "", working ? `${working} working` : ""].filter(Boolean).join(" · "); + return glanceSummary({ needsYou: needs, working }); } function paintList(win: AppWindow, mode: "list" | "environments"): GrayImage { @@ -1733,3 +1776,9 @@ async function readThreadText({ client, thread }: ThreadMatch): Promise handle.close(); } } + +// --------------------------------------------------------------------------- +// Startup (last, so every module-level binding above is initialized) + +// Spawned without a window (by the app's boot hook) for the Glanceboard widget. +if (hasT3BackgroundWork()) syncClients(); diff --git a/tests/t3code-glance.test.cjs b/tests/t3code-glance.test.cjs new file mode 100644 index 00000000..3d2bf6f3 --- /dev/null +++ b/tests/t3code-glance.test.cjs @@ -0,0 +1,71 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { buildGlanceSnapshot, glanceSummary } = require('../.test-build/app/apps/t3code/t3-glance.js'); +const { threadMarker } = require('../.test-build/app/apps/t3code/t3-model.js'); + +const NOW = Date.parse('2026-10-04T12:00:00.000Z'); +const iso = (offsetMs) => new Date(NOW + offsetMs).toISOString(); + +function thread(id, extra = {}) { + return { + id, projectId: 'p1', title: `Thread ${id}`, status: 'completed', latestRunId: 'r', activeProviderThreadId: 'x', + pendingBackgroundTasks: [], latestUserMessageAt: iso(-60_000), updatedAt: iso(-60_000), createdAt: iso(-86_400_000), + lineage: {}, ...extra, + }; +} + +const env = (id, threads, extra = {}) => ({ id, ready: true, phase: 'connected', enabled: true, threads, ...extra }); + +test('rows: needs-you, then working, then recent, across environments; settled and snoozed left out', () => { + const snapshot = buildGlanceSnapshot([ + env('a', [ + thread('recent', { latestUserMessageAt: iso(-120_000) }), + thread('approve', { status: 'running', pendingRuntimeRequest: { id: 'q1', kind: 'file-change', createdAt: iso(-1000) } }), + thread('done', { settledOverride: 'settled', settledAt: iso(-1000) }), + ]), + env('b', [ + thread('busy', { status: 'running', latestUserAuthoredMessageAt: iso(-30_000) }), + thread('nap', { snoozedUntil: iso(3_600_000), snoozedAt: iso(-1000) }), + thread('new', { latestRunCompletedAt: iso(-5000), lastVisitedAt: iso(-50_000), latestUserMessageAt: iso(-10_000) }), + ]), + ], NOW); + assert.deepEqual(snapshot.rows.map((row) => row.key), ['a:approve', 'b:busy', 'b:new', 'a:recent']); + assert.deepEqual(snapshot.rows.map((row) => row.status), ['approval', 'working', 'ready', 'ready']); + assert.equal(snapshot.rows[0].requestKind, 'file-change'); + assert.equal(snapshot.rows[2].unread, true); + assert.equal(snapshot.needsYou, 1); + assert.equal(snapshot.working, 1); + assert.equal(snapshot.more, 0); + assert.equal(snapshot.status, ''); + assert.equal(glanceSummary(snapshot), '1 needs you · 1 working'); + // It crosses postMessage: plain JSON only. + assert.deepEqual(JSON.parse(JSON.stringify(snapshot)), snapshot); +}); + +test('caps rows and counts the rest', () => { + const threads = Array.from({ length: 30 }, (_, index) => thread(`t${index}`, { latestUserMessageAt: iso(-index * 1000) })); + const snapshot = buildGlanceSnapshot([env('a', threads)], NOW); + assert.equal(snapshot.rows.length, 24); + assert.equal(snapshot.more, 6); +}); + +test('status when nothing is connected', () => { + assert.deepEqual(buildGlanceSnapshot([], NOW), { configured: false, status: '', needsYou: 0, working: 0, rows: [], more: 0 }); + const status = (environments) => buildGlanceSnapshot(environments, NOW).status; + assert.equal(status([env('a', [], { ready: false, phase: 'connecting' })]), 'Connecting…'); + assert.equal(status([env('a', [], { ready: false, phase: 'retrying' })]), "Can't reach T3 Code"); + assert.equal(status([env('a', [], { ready: false, phase: 'auth-failed' })]), 'Pair again in the T3 Code app'); + assert.equal(status([env('a', [], { ready: false, phase: 'idle', enabled: false })]), 'Disconnected'); + // One connected environment is enough to show threads. + assert.equal(status([env('a', [], { ready: false, phase: 'retrying' }), env('b', [])]), ''); +}); + +test('status marks', () => { + assert.deepEqual(threadMarker('approval'), { marker: '!', value: 255 }); + assert.deepEqual(threadMarker('input'), { marker: '?', value: 255 }); + assert.equal(threadMarker('working').marker, '…'); + assert.equal(threadMarker('ready', { unread: true }).marker, '●'); + assert.equal(threadMarker('ready', { settled: true, unread: true }).marker, '✓'); + assert.equal(threadMarker('ready').marker, ''); + assert.equal(threadMarker('failed', { unread: true }).marker, 'x'); +}); diff --git a/tests/tsconfig.json b/tests/tsconfig.json index 331cfe00..73bcf527 100644 --- a/tests/tsconfig.json +++ b/tests/tsconfig.json @@ -56,6 +56,7 @@ "../app/apps/t3code/t3-model.ts", "../app/apps/t3code/t3-auth.ts", "../app/apps/t3code/t3-client.ts", - "../app/apps/t3code/t3-transcript.ts" + "../app/apps/t3code/t3-transcript.ts", + "../app/apps/t3code/t3-glance.ts" ] }