Add glanceboard widget for T3code

This commit is contained in:
James Babcock committed 2026-10-04 03:07:38 -07:00
1 parent 043e5e74ce
commit 49a49d68ce
12 files changed
+453 -34

No files matched your search

+11
View File
@@ -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);
}
+26 -1
View File
@@ -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;
+103
View File
@@ -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<T3ThreadShell>;
};
export function buildGlanceSnapshot(environments: readonly T3GlanceEnvironment[], nowMs: number): T3GlanceSnapshot {
const owner = new Map<T3ThreadShell, string>();
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<T3GlanceSnapshot, "needsYou" | "working">): string {
return [
snapshot.needsYou ? `${snapshot.needsYou} need${snapshot.needsYou === 1 ? "s" : ""} you` : "",
snapshot.working ? `${snapshot.working} working` : "",
].filter(Boolean).join(" · ");
}
+21
View File
@@ -261,6 +261,27 @@ export function threadStatusLabel(status: T3ThreadStatus): string {
}
}
const STATUS_MARKERS: Record<T3ThreadStatus, { marker: string; value: number }> = {
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);
+75 -26
View File
@@ -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<typeof setTimeout> | 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<T3ThreadStatus, { marker: string; value: number }> = {
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<string>
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();