Merge attachments, usage limits and automation editing

# Conflicts:
#	README.md
#	src/ui/App.tsx
#	test/commands.test.ts
This commit is contained in:
Callum Alpass committed 2026-11-02 20:49:42 +11:00
commit fe9cbb6a9f
15 files changed
+1049 -23

No files matched your search

+3 -2
View File
@@ -3,8 +3,9 @@ import { homedir } from "node:os";
import { dirname, join } from "node:path";
/**
* Scopes tui3 asks for: read and operate threads, read diffs, run git actions
* (commit, push, open a PR), stop a thread's local servers, and use its terminals.
* Scopes tui3 asks for: read and operate threads (attachments and automations ride on
* operate), read diffs, run git actions (commit, push, open a PR), stop a thread's local
* servers, use its terminals, read usage totals, and spend reset credits.
*/
export const TUI3_SCOPES = ["orchestration:read", "orchestration:operate", "filesystem:read", "source-control:write", "terminal:read", "terminal:operate", "diagnostics:read", "providers:manage"] as const;
+47 -5
View File
@@ -26,10 +26,17 @@ import {
type GitActionProgressEvent,
type GitRunStackedActionResult,
type GitStackedAction,
type AttachmentCreateUploadUrlInput,
type ChatAttachment,
type ProjectId,
type ProviderConsumeResetCreditInput,
type ProviderConsumeResetCreditResult,
type ReviewDiffPreviewSource,
type ScheduledTask,
type ScheduledTaskId,
type ScheduledTaskUpsertInput,
type UsageSummary,
type UsageSummaryInput,
type ServerConfig,
type ModelSelection,
type OrchestrationMessageContext,
@@ -418,6 +425,41 @@ export class T3Session {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.scheduledTasksRunNow]({ id }));
}
upsertAutomation(input: ScheduledTaskUpsertInput): Promise<unknown> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.scheduledTasksUpsert](input));
}
deleteAutomation(id: ScheduledTaskId): Promise<unknown> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.scheduledTasksDelete]({ id }));
}
/**
* Uploads one attachment the way the web composer does: mint a signed upload URL,
* POST the bytes to it, and resolve with the ChatAttachment to send with the message.
*/
async uploadAttachment(upload: AttachmentCreateUploadUrlInput, bytes: Uint8Array): Promise<ChatAttachment> {
const { rpc, target } = this.requireConnection();
const minted = await Effect.runPromise(rpc[WS_METHODS.attachmentsCreateUploadUrl](upload));
const url = new URL(minted.relativeUrl, target.httpBaseUrl);
const response = await fetch(url, { method: "POST", headers: { "content-type": upload.mimeType }, body: bytes as BodyInit });
if (!response.ok) throw new Error(`Upload rejected (${response.status})`);
return { type: upload.type === "file" ? "file" : "image", id: minted.attachmentId, name: upload.name, mimeType: upload.mimeType, sizeBytes: upload.sizeBytes } as ChatAttachment;
}
/** Deletes an unsent upload, as removing it in the web composer does. */
deleteAttachment(attachmentId: string): Promise<unknown> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.attachmentsDelete]({ attachmentId }));
}
/** Token and cost totals for a window, as the web's usage page reads them. */
usageSummary(input: UsageSummaryInput): Promise<UsageSummary> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.serverGetUsageSummary](input));
}
consumeResetCredit(input: ProviderConsumeResetCreditInput): Promise<ProviderConsumeResetCreditResult> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.providerConsumeResetCredit](input));
}
stopServer(server: Pick<DiscoveredLocalServer, "pid" | "port">): Promise<unknown> {
if (server.pid === null) return Promise.reject(new Error("The server's process is unknown."));
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.previewStopLocalServer]({ pid: server.pid, port: server.port }));
@@ -457,7 +499,7 @@ export class T3Session {
*/
/** `modelSelection` switches the thread's model (and options) with this message, as the web composer does. */
/** `context` carries the records for thread mentions in the text. */
sendMessage(threadId: ThreadId, text: string, mode: ComposerDispatchMode = "auto", modelSelection?: ModelSelection, context?: OrchestrationMessageContext): Promise<void> {
sendMessage(threadId: ThreadId, text: string, mode: ComposerDispatchMode = "auto", modelSelection?: ModelSelection, context?: OrchestrationMessageContext, attachments: readonly ChatAttachment[] = []): Promise<void> {
const commandId = newCommandId();
return this.dispatch({
type: "message.dispatch",
@@ -465,7 +507,7 @@ export class T3Session {
threadId,
messageId: MessageId.make(commandId),
text,
attachments: [],
attachments: [...attachments],
...(context ? { context } : {}),
...(modelSelection ? { modelSelection } : {}),
...(mode === "queue" ? { dispatchMode: { type: "queue_after_active" } } : { dispatchMode: { type: "start_immediately" }, deliveryIntent: mode }),
@@ -651,11 +693,11 @@ export class T3Session {
* Creates a thread and sends its first message in one call, as the web app does when a
* draft is first sent. Resolves with the new thread's id.
*/
async launchThread(input: Omit<OrchestrationV2ThreadLaunchInput, "commandId" | "initialMessage"> & { readonly text: string; readonly context?: OrchestrationMessageContext | undefined }): Promise<ThreadId> {
const { text, context, ...rest } = input;
async launchThread(input: Omit<OrchestrationV2ThreadLaunchInput, "commandId" | "initialMessage"> & { readonly text: string; readonly context?: OrchestrationMessageContext | undefined; readonly attachments?: readonly ChatAttachment[] }): Promise<ThreadId> {
const { text, context, attachments, ...rest } = input;
const commandId = newCommandId();
const result = await Effect.runPromise(
this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.launchThread]({ ...rest, commandId, initialMessage: { messageId: MessageId.make(commandId), text, ...(context ? { context } : {}), attachments: [] } }),
this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.launchThread]({ ...rest, commandId, initialMessage: { messageId: MessageId.make(commandId), text, ...(context ? { context } : {}), attachments: [...(attachments ?? [])] } }),
);
return result.threadId;
}
+88
View File
@@ -0,0 +1,88 @@
import {
getProviderAttachmentLimitError,
isProviderSendTurnSupportedImageMimeType,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES,
type AttachmentCreateUploadUrlInput,
type ChatAttachment,
} from "@t3tools/contracts";
import { clampFileAttachmentUploadBytes, fileAttachmentTooLargeMessage } from "@t3tools/client-runtime/state/attachments";
import { homedir } from "node:os";
import { basename, isAbsolute, resolve } from "node:path";
const IMAGE_MIME_BY_EXTENSION: Readonly<Record<string, string>> = {
gif: "image/gif",
jpeg: "image/jpeg",
jpg: "image/jpeg",
png: "image/png",
webp: "image/webp",
};
/** The MIME type from the extension alone, for sources that report a generic one. */
export function imageMimeTypeForName(name: string): string | null {
const dot = name.lastIndexOf(".");
return dot > 0 ? (IMAGE_MIME_BY_EXTENSION[name.slice(dot + 1).toLowerCase()] ?? null) : null;
}
/** Expands `~` and resolves a relative path against `cwd`, as the attach prompt promises. */
export function expandAttachmentPath(input: string, cwd: string | null): string {
const path = input.trim();
const expanded = path === "~" ? homedir() : path.startsWith("~/") ? resolve(homedir(), path.slice(2)) : path;
return isAbsolute(expanded) ? expanded : resolve(cwd ?? process.cwd(), expanded);
}
/** The clipboard readers, in order: the platform's usual image grabber first. */
export function clipboardImageCommands(platform: string): readonly (readonly string[])[] {
return platform === "darwin"
? [["pngpaste", "-"]]
: [
["wl-paste", "--type", "image/png"],
["xclip", "-selection", "clipboard", "-t", "image/png", "-o"],
];
}
export type AttachmentCheck =
| { readonly ok: true; readonly upload: AttachmentCreateUploadUrlInput; readonly mimeType: string }
| { readonly ok: false; readonly error: string };
/**
* Checks one local file the way the web composer does: supported images go as images
* (GIF, JPEG, PNG, WebP, up to the image cap), everything else as a file up to the
* server's advertised limit, clamped to what a turn may reference.
*/
export function checkAttachment(input: {
readonly name: string;
readonly sizeBytes: number;
/** The OS-reported type, when it isn't empty or generic. */
readonly mimeType?: string;
readonly pending: readonly ChatAttachment[];
/** Null: the server advertises no file attachments. */
readonly maxFileBytes: number | null;
}): AttachmentCheck {
const name = basename(input.name) || "file";
if (input.pending.length >= PROVIDER_SEND_TURN_MAX_ATTACHMENTS) {
return { ok: false, error: `You can attach up to ${PROVIDER_SEND_TURN_MAX_ATTACHMENTS} files per message.` };
}
if (input.sizeBytes <= 0) return { ok: false, error: `'${name}' is empty or could not be read.` };
const reported = input.mimeType?.toLowerCase();
const imageMime = imageMimeTypeForName(name) ?? (reported && isProviderSendTurnSupportedImageMimeType(reported) ? reported : null);
if (imageMime) {
if (input.sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) return { ok: false, error: fileAttachmentTooLargeMessage(name, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) };
const candidate: Pick<ChatAttachment, "type" | "mimeType" | "sizeBytes"> = { type: "image", mimeType: imageMime, sizeBytes: input.sizeBytes };
const limit = getProviderAttachmentLimitError([...input.pending, candidate]);
if (limit) return { ok: false, error: limit };
const supported = PROVIDER_SEND_TURN_SUPPORTED_IMAGE_MIME_TYPES.find((candidate) => candidate === imageMime)!;
return { ok: true, upload: { type: "image", name, mimeType: supported, sizeBytes: input.sizeBytes }, mimeType: imageMime };
}
if (input.maxFileBytes === null) return { ok: false, error: "This server does not support file attachments." };
const limit = clampFileAttachmentUploadBytes(input.maxFileBytes);
if (input.sizeBytes > limit) return { ok: false, error: fileAttachmentTooLargeMessage(name, limit) };
const mimeType = reported && reported !== "" ? reported : "application/octet-stream";
return { ok: true, upload: { type: "file", name, mimeType, sizeBytes: input.sizeBytes }, mimeType };
}
/** The pending attachments as the one line shown above the composer. */
export function attachmentLine(pending: readonly ChatAttachment[]): string {
return pending.length > 0 ? `Attached: ${pending.map((attachment) => attachment.name).join(", ")}` : "";
}
+242
View File
@@ -0,0 +1,242 @@
import {
MIN_SCHEDULED_TASK_INTERVAL_MS,
ProjectId,
ProviderInstanceId,
ThreadId,
type ModelSelection,
type OrchestrationProjectShell,
type RuntimeMode,
type ScheduledTask,
type ScheduledTaskUpsertInput,
type ScheduledTaskUpsertSchedule,
} from "@t3tools/contracts";
const RUNTIME_MODES: readonly RuntimeMode[] = ["approval-required", "auto-accept-edits", "auto", "full-access"];
const WEEKDAY_NAMES = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"] as const;
const WEEKDAY_BY_NAME = new Map<string, number>(WEEKDAY_NAMES.map((name, index) => [name.toLowerCase(), index]));
export interface AutomationDefaults {
readonly projectId: string;
readonly threadId: string;
readonly modelSelection: ModelSelection;
readonly runtimeMode: RuntimeMode;
}
/**
* The $EDITOR template for a new automation: the web form's fields and defaults
* (weekdays at 09:00, a new worktree off main from origin), one per line.
*/
export function newAutomationTemplate(projects: readonly OrchestrationProjectShell[], defaults: AutomationDefaults): string {
const project = projects.find((candidate) => candidate.id === defaults.projectId) ?? projects[0];
return template({
title: "",
enabled: true,
schedule: "fixed 09:00 Mon,Tue,Wed,Thu,Fri",
project: project?.title ?? "",
thread: defaults.threadId,
workspace: "worktree",
baseRef: "main",
startFromOrigin: true,
checkoutPath: "",
model: `${defaults.modelSelection.instanceId}:${defaults.modelSelection.model}`,
mode: defaults.runtimeMode,
prompt: "",
});
}
/** The $EDITOR template for an existing automation, its fields filled in. */
export function automationTemplate(task: ScheduledTask, projects: readonly OrchestrationProjectShell[]): string {
const project = projects.find((candidate) => candidate.id === task.projectId);
return template({
title: task.title,
enabled: task.enabled,
schedule: scheduleText(task),
project: project?.title ?? task.projectId,
thread: task.threadId ?? "",
workspace: task.workspaceStrategy.type,
baseRef: task.workspaceStrategy.type === "worktree" ? task.workspaceStrategy.baseRef : "main",
startFromOrigin: task.workspaceStrategy.type === "worktree" ? (task.workspaceStrategy.startFromOrigin ?? false) : true,
checkoutPath: task.workspaceStrategy.type === "existing_worktree" ? task.workspaceStrategy.worktreePath : "",
model: `${task.modelSelection.instanceId}:${task.modelSelection.model}`,
mode: task.runtimeMode,
prompt: task.prompt,
});
}
interface TemplateFields {
readonly title: string;
readonly enabled: boolean;
readonly schedule: string;
readonly project: string;
readonly thread: string;
readonly workspace: string;
readonly baseRef: string;
readonly startFromOrigin: boolean;
readonly checkoutPath: string;
readonly model: string;
readonly mode: string;
readonly prompt: string;
}
function template(fields: TemplateFields): string {
return [
"# Automation. Lines starting with # are ignored. Save and quit to save the automation.",
"# Schedule: `fixed HH:MM Mon,Tue,...` (days optional), `interval 15m` / `interval 2h`, or `webhook`.",
"# Webhook signatures and filters are kept as they are; change those in T3 Code.",
"# Workspace: `worktree` (a new one off Base ref), `root` (the project folder), or `existing_worktree` (Checkout path).",
"# Thread: the thread each run continues in; blank starts a fresh thread each run.",
`Title: ${fields.title}`,
`Enabled: ${fields.enabled ? "true" : "false"}`,
`Schedule: ${fields.schedule}`,
`Project: ${fields.project}`,
`Thread: ${fields.thread}`,
`Workspace: ${fields.workspace}`,
`Base ref: ${fields.baseRef}`,
`Start from origin: ${fields.startFromOrigin ? "true" : "false"}`,
`Checkout path: ${fields.checkoutPath}`,
`Model: ${fields.model}`,
`Mode: ${fields.mode}`,
"Prompt:",
fields.prompt,
"",
].join("\n");
}
function scheduleText(task: ScheduledTask): string {
const schedule = task.schedule;
switch (schedule.type) {
case "interval": {
const minutes = schedule.everyMs / 60_000;
return Number.isInteger(minutes) && minutes % 60 === 0 ? `interval ${minutes / 60}h` : `interval ${Math.max(1, Math.round(minutes))}m`;
}
case "fixed_time": {
const days = schedule.weekdays && schedule.weekdays.length > 0 && schedule.weekdays.length < 7 ? ` ${schedule.weekdays.map((day) => WEEKDAY_NAMES[day]).join(",")}` : "";
return `fixed ${schedule.timeOfDay}${days}`;
}
case "webhook":
return "webhook";
}
}
export type AutomationParse = { readonly ok: true; readonly input: ScheduledTaskUpsertInput } | { readonly ok: false; readonly error: string };
/**
* Parses an edited template back into an upsert, with the web form's checks:
* a title, a prompt, a project and a model, an interval of at least a minute,
* and a checkout path for an existing worktree. Editing a webhook task keeps
* its signature, dedupe and filters, as the template says.
*/
export function parseAutomation(text: string, projects: readonly OrchestrationProjectShell[], existing?: ScheduledTask): AutomationParse {
const fields = new Map<string, string>();
const promptLines: string[] = [];
let inPrompt = false;
for (const line of text.split("\n")) {
if (inPrompt) {
promptLines.push(line);
continue;
}
if (line.startsWith("#")) continue;
const match = /^([^:]+):\s*(.*)$/.exec(line);
if (!match) continue;
const key = match[1]!.trim().toLowerCase();
if (key === "prompt") {
inPrompt = true;
if (match[2]) promptLines.push(match[2]);
continue;
}
fields.set(key, match[2]!.trim());
}
const get = (key: string) => fields.get(key) ?? "";
const title = get("title");
const prompt = promptLines.join("\n").trim();
const projectText = get("project");
const project = projects.find((candidate) => candidate.title === projectText) ?? projects.find((candidate) => candidate.id === projectText);
const model = parseModel(get("model"), existing?.modelSelection);
if (!title || !prompt || !project || !model) return { ok: false, error: "Scheduled task is incomplete: add a title, prompt, project, and model." };
const schedule = parseSchedule(get("schedule"), existing);
if (!schedule.ok) return schedule;
const workspace = get("workspace") || "worktree";
const checkoutPath = get("checkout path");
if (workspace === "existing_worktree" && !checkoutPath) return { ok: false, error: "Checkout path is required: enter the path of the checkout to run in." };
if (workspace !== "root" && workspace !== "worktree" && workspace !== "existing_worktree") return { ok: false, error: `Workspace must be worktree, root, or existing_worktree, not "${workspace}".` };
const mode = get("mode");
if (!(RUNTIME_MODES as readonly string[]).includes(mode)) return { ok: false, error: `Mode must be one of ${RUNTIME_MODES.join(", ")}, not "${mode}".` };
const threadId = get("thread");
return {
ok: true,
input: {
...(existing ? { id: existing.id, requireExisting: true } : {}),
title,
prompt,
enabled: get("enabled").toLowerCase() !== "false",
schedule: schedule.schedule,
projectId: ProjectId.make(project.id),
threadId: threadId ? ThreadId.make(threadId) : null,
workspaceStrategy:
workspace === "root"
? { type: "root" }
: workspace === "existing_worktree"
? { type: "existing_worktree", worktreePath: checkoutPath }
: { type: "worktree", baseRef: get("base ref") || "main", startFromOrigin: get("start from origin").toLowerCase() !== "false" },
modelSelection: model,
runtimeMode: mode as RuntimeMode,
interactionMode: existing?.interactionMode ?? "default",
creationSource: "web",
},
};
}
function parseModel(text: string, base?: ModelSelection): ModelSelection | null {
const colon = text.indexOf(":");
if (colon <= 0 || colon === text.length - 1) return null;
const instanceId = text.slice(0, colon).trim();
const model = text.slice(colon + 1).trim();
if (!instanceId || !model) return null;
// An unchanged model keeps its provider options, as the web form keeps them.
if (base && base.instanceId === instanceId && base.model === model) return base;
return { instanceId: ProviderInstanceId.make(instanceId), model };
}
type ScheduleParse = { readonly ok: true; readonly schedule: ScheduledTaskUpsertSchedule } | { readonly ok: false; readonly error: string };
function parseSchedule(text: string, existing?: ScheduledTask): ScheduleParse {
const [kind = "", ...rest] = text.trim().split(/\s+/);
if (kind === "interval") {
const match = /^(\d+)\s*(m|h)?$/.exec(rest.join(" "));
const everyMs = match ? Number(match[1]) * (match[2] === "h" ? 3_600_000 : 60_000) : Number.NaN;
if (!Number.isSafeInteger(everyMs) || everyMs < MIN_SCHEDULED_TASK_INTERVAL_MS) return { ok: false, error: "Invalid interval: enter an interval of at least one minute." };
return { ok: true, schedule: { type: "interval", everyMs } };
}
if (kind === "fixed") {
const timeOfDay = rest[0] ?? "";
if (!/^([01]?\d|2[0-3]):([0-5]\d)$/.test(timeOfDay)) return { ok: false, error: `Invalid schedule: "${text}" — use fixed HH:MM, interval 15m, or webhook.` };
const days = rest.slice(1).join(" ").split(/[,\s]+/).filter(Boolean);
const weekdays: number[] = [];
for (const day of days) {
const index = WEEKDAY_BY_NAME.get(day.toLowerCase());
if (index === undefined) return { ok: false, error: `Unknown weekday "${day}": use ${WEEKDAY_NAMES.join(", ")}.` };
weekdays.push(index);
}
const everyDay = weekdays.length === 0 || new Set(weekdays).size === 7;
return { ok: true, schedule: { type: "fixed_time", timeOfDay, ...(everyDay ? {} : { weekdays: [...new Set(weekdays)].sort((a, b) => a - b) }) } };
}
if (kind === "webhook") {
const current = existing?.schedule.type === "webhook" ? existing.schedule : null;
if (!current) return { ok: true, schedule: { type: "webhook", signature: null, dedupe: {} } };
// Filters stay stored when left out; a signature without a secret keeps the stored one.
return {
ok: true,
schedule: {
type: "webhook",
signature: current.signature ? { header: current.signature.header, encoding: current.signature.encoding, prefix: current.signature.prefix } : null,
...(current.maxDeliveryAgeMinutes !== undefined ? { maxDeliveryAgeMinutes: current.maxDeliveryAgeMinutes } : {}),
dedupe: current.dedupe ?? {},
},
};
}
return { ok: false, error: `Invalid schedule: "${text}" — use fixed HH:MM, interval 15m, or webhook.` };
}
+87
View File
@@ -0,0 +1,87 @@
import type { ProviderConsumeResetCreditInput, ServerConfig, ServerProviderResetCredits, UsageSummary } from "@t3tools/contracts";
import { collectLimitAccounts, collectLimitNotices, formatDuration, remainingPercent, type LimitPresentations } from "@t3tools/shared/usageLimits";
import { formatTokens, formatUsd } from "@t3tools/shared/usageFormat";
/** At or above this much of a window used, the status line calls the limit near. */
export const NEAR_LIMIT_USED_PERCENT = 90;
export interface UsageLimitInfo {
/** One line per account and window, for the settings view. */
readonly lines: readonly { label: string; value: string }[];
/** The worst near-or-reached window, for the status line; null when every window has room. */
readonly note: string | null;
/** Accounts with a banked reset credit the palette can spend. */
readonly credits: readonly { label: string; input: ProviderConsumeResetCreditInput; credits: ServerProviderResetCredits }[];
}
/** Provider limits from the server config, collected the way the web's usage page collects them. */
export function usageLimits(config: ServerConfig | null, now = Date.now()): UsageLimitInfo {
if (!config) return { lines: [], note: null, credits: [] };
const presentations: LimitPresentations = new Map([
[config.environment.environmentId, { entry: { target: { label: config.environment.label } }, serverConfig: config }],
]);
const lines: { label: string; value: string }[] = [];
const credits: UsageLimitInfo["credits"][number][] = [];
let note: { used: number; text: string } | null = null;
for (const account of collectLimitAccounts(presentations)) {
const label = account.displayName ?? account.email ?? account.driver;
const heading = [label, account.plan, account.sourceLabel].filter(Boolean).join(" · ");
for (const window of account.limits.windows) {
const left = remainingPercent(window);
const resets = window.resetsAt && Date.parse(window.resetsAt) > now ? ` · resets in ${formatDuration(Date.parse(window.resetsAt) - now)}` : "";
lines.push({ label: `${heading} ${window.label}`, value: `${left}% left${resets}` });
if (window.usedPercent >= NEAR_LIMIT_USED_PERCENT && (!note || window.usedPercent > note.used)) {
note = { used: window.usedPercent, text: `${label} ${window.label}: ${left === 0 ? "limit reached" : `${left}% left`}${resets}` };
}
}
const banked = account.limits.resetCredits;
if (banked && banked.availableCount > 0) {
lines.push({ label: `${heading} reset credits`, value: resetCreditsSummary(banked, now) });
if (account.redeem) credits.push({ label: heading, input: account.redeem.input, credits: banked });
}
}
for (const notice of collectLimitNotices(presentations)) lines.push({ label: "Limits", value: notice });
return { lines, note: note?.text ?? null, credits };
}
/** The web's banked-credits wording: a count and when the next one expires. */
export function resetCreditsSummary(credits: ServerProviderResetCredits, now = Date.now()): string {
if (credits.availableCount === 0) return "No reset credits banked";
const expires = credits.nextExpiresAt ? ` · next expires in ${formatDuration(Date.parse(credits.nextExpiresAt) - now)}` : "";
return `${credits.availableCount} ${credits.availableCount === 1 ? "reset credit" : "reset credits"} banked${expires}`;
}
const RESET_CREDIT_OUTCOMES: Record<string, string> = {
reset: "Reset applied. Your windows have cleared.",
nothingToReset: "Nothing to reset right now.",
noCredit: "No reset credit left.",
alreadyRedeemed: "That credit was already redeemed.",
};
/** What spending a reset credit says afterwards, as the web reports it. */
export function resetCreditOutcome(result: { readonly outcome: string; readonly warning?: string | undefined }): string {
return result.warning ?? RESET_CREDIT_OUTCOMES[result.outcome] ?? result.outcome;
}
/** The usage summary's totals for the settings view: cost and tokens, then the priciest providers. */
export function usageSummaryLines(summary: UsageSummary | null): { label: string; value: string }[] {
if (!summary) return [];
const byProvider = new Map<string, { cost: number; tokens: number }>();
let cost = 0;
let tokens = 0;
for (const bucket of summary.buckets) {
const total = bucket.totals.uncachedInputTokens + bucket.totals.cachedInputTokens + bucket.totals.cacheCreationTokens + bucket.totals.outputTokens;
cost += bucket.costUsd;
tokens += total;
const entry = byProvider.get(bucket.provider) ?? { cost: 0, tokens: 0 };
entry.cost += bucket.costUsd;
entry.tokens += total;
byProvider.set(bucket.provider, entry);
}
const sessions = summary.sources.reduce((sum, source) => sum + source.distinctSessions, 0);
const lines = [{ label: "Last 30 days", value: `${formatUsd(cost)} · ${formatTokens(tokens)} tokens · ${sessions} sessions` }];
for (const [provider, entry] of [...byProvider].sort((a, b) => b[1].cost - a[1].cost)) {
lines.push({ label: provider, value: `${formatUsd(entry.cost)} · ${formatTokens(entry.tokens)} tokens` });
}
return lines;
}
+68 -10
View File
@@ -9,8 +9,9 @@ import {
type PendingUserInputDraftAnswer,
} from "@t3tools/client-runtime/state/pending-user-input";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
import { type ContextMenuItem, type DiscoveredLocalServer, type ModelSelection, type OrchestrationV2ThreadShell, type ProviderApprovalDecision, type ScheduledTask, type ThreadId } from "@t3tools/contracts";
import { type ChatAttachment, type ContextMenuItem, type DiscoveredLocalServer, type ModelSelection, type OrchestrationV2ThreadShell, type ProviderApprovalDecision, type ScheduledTask, type ThreadId } from "@t3tools/contracts";
import { homedir } from "node:os";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
@@ -24,6 +25,7 @@ import { configPath, cycleConfig, saveConfig, type Tui3Config } from "../config.
import { detailsActions, detailsCwd, RUNTIME_MODE_LABELS, threadDetails, type DetailsAction, type GitAction } from "../model/details.ts";
import { paletteEntries, paletteGroups, pickerGroups, type PaletteCommand, type Picker, type PickerItem } from "../model/palette.ts";
import { serverSettingLines, settingRows } from "../model/settings.ts";
import { resetCreditOutcome, usageLimits, usageSummaryLines } from "../model/usage.ts";
import { buildTimeline, type Timeline } from "../model/timeline.ts";
import type { Section } from "../model/threads.ts";
import { ComposerMenu } from "./ComposerMenu.tsx";
@@ -51,6 +53,9 @@ import { usePaletteSearch } from "./usePaletteSearch.ts";
import { useThreadFind } from "./useThreadFind.ts";
import { ThreadFindBar } from "./ThreadFindBar.tsx";
import { mergeThreadShells, messageMatchGroups } from "../model/search.ts";
import { useAttachments } from "./useAttachments.ts";
import { useAutomations } from "./useAutomations.ts";
import { useUsageSummary } from "./useUsage.ts";
/**
* "input": typing goes to the composer. "nav": single keys move, scroll, approve.
@@ -382,6 +387,37 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
setMode(returnMode.current);
};
// Attachments, usage and automation editing: each hook owns its slice; App wires it in below.
const attachCwd = draft ? (shell.snapshot?.projects.find((candidate) => candidate.id === draft.projectId)?.workspaceRoot ?? null) : (threadShell?.worktreePath ?? project?.workspaceRoot ?? null);
const attach = useAttachments({
session,
composerKey,
cwd: attachCwd,
maxFileBytes: serverConfig?.config ? (serverConfig.config.environment.capabilities.fileAttachments?.maxUploadBytes ?? null) : undefined,
confirm,
say,
});
const usage = useUsageSummary(session, settingsIndex !== null && live);
const usageInfo = useMemo(() => usageLimits(serverConfig?.config ?? null, now), [serverConfig, now]);
const useResetCredit = (credit: (typeof usageInfo.credits)[number]) =>
confirm({
title: "Use a reset credit?",
detail: "This redeems one credit on your account and clears the current rate-limit windows. It cannot be undone.",
confirmLabel: "use credit",
run: () =>
session.consumeResetCredit(credit.input).then(
(result) => say(resetCreditOutcome(result)),
(error) => say(`Could not use the reset credit: ${messageOf(error)}`, true),
),
});
const automationDefaults = (() => {
const projects = shell.snapshot?.projects ?? [];
const projectId = threadShell?.projectId ?? draft?.projectId ?? projects[0]?.id;
const modelSelection = threadShell?.modelSelection ?? draft?.modelSelection ?? serverConfig?.config?.settings.defaultModelSelection ?? undefined;
return projectId && modelSelection ? { projectId, threadId: threadShell?.id ?? "", modelSelection, runtimeMode: threadShell?.runtimeMode ?? draft?.runtimeMode ?? ("full-access" as const) } : null;
})();
const automationEditing = useAutomations({ session, renderer, projects: shell.snapshot?.projects ?? [], defaults: automationDefaults, confirm, run, say });
const openDiff = (path: string | null) => {
if (!vcsCwd) return;
const cwd = vcsCwd;
@@ -755,7 +791,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const { existingWorktree: _, ...rest } = draft;
setDraft({ ...rest, envMode: draft.existingWorktree ? "local" : draft.envMode === "local" ? "worktree" : "local" });
};
const launchDraft = (text: string, context?: OrchestrationMessageContext) => {
const launchDraft = (text: string, context?: OrchestrationMessageContext, attachments: readonly ChatAttachment[] = []) => {
if (!draft || !draftProject) return;
const launching = draft;
const project = draftProject;
@@ -770,7 +806,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
}
return session.launchThread({
projectId: launching.projectId,
title: deriveThreadTitleSeed({ text, attachments: [] }),
title: deriveThreadTitleSeed({ text, attachments: [...attachments] }),
generateTitle: true,
modelSelection: launching.modelSelection,
runtimeMode: launching.runtimeMode,
@@ -778,6 +814,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
workspaceStrategy,
text,
context,
attachments,
});
})().then(
(id) => {
@@ -870,27 +907,33 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return;
}
const text = raw.trim();
const attachedFiles = attach.pending;
const context = messageContext(text, mentions.current.get(composerKey) ?? new Map());
if (draft) {
if (!text) return;
if (!text && attachedFiles.length === 0) return;
const taken = attach.take();
clearComposer();
return launchDraft(text, context);
return launchDraft(text || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, context, taken);
}
if (!threadId) return;
if (pendingInput && questionDraft) {
if (attachedFiles.length > 0) return say("Attachments can't go with a question answer here; remove them first from the palette.", true);
const question = pendingInput.questions[questionDraft.index];
if (!question) return;
const answer = text ? setPendingUserInputCustomAnswer(question, questionDraft.answers[question.id], text) : questionDraft.answers[question.id];
clearComposer();
return advanceQuestion({ ...questionDraft, answers: { ...questionDraft.answers, ...(answer ? { [question.id]: answer } : {}) } });
}
if (queue.submit(text)) return;
if (!text) return;
if ((queue.editing || attachedFiles.length === 0) && queue.submit(text)) return;
if (!text && attachedFiles.length === 0) return;
if (pendingApproval && attachedFiles.length > 0) return say("Send approval feedback without attachments or added context.", true);
clearComposer();
const taken = attach.take();
const sendText = text || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT;
if (pendingApproval) {
// As in the web composer: the message declines the request and redirects the agent.
if (pendingApproval.supportsFeedback) return run("Declined with feedback", () => session.respond(threadId, pendingApproval.requestId, "decline", text));
return run("Declined and redirected", () => session.sendMessage(threadId, text, "steer", undefined, context));
return run("Declined and redirected", () => session.sendMessage(threadId, sendText, "steer", undefined, context, taken));
}
const dispatchMode = resolveComposerDispatchMode({ running: working, alternateModifier: alternate, activeTurnDefault: config.followUpBehavior });
const pendingModel = pendingModels.get(threadId);
@@ -901,7 +944,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return next;
});
}
run(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", () => session.sendMessage(threadId, text, dispatchMode, pendingModel, context));
run(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", () => session.sendMessage(threadId, sendText, dispatchMode, pendingModel, context, taken));
};
const loadEarlier = () => {
@@ -950,6 +993,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
if (action.kind === "automation") {
command(action.id, `Run automation: ${action.task.title}`, () => runAutomation(action.task), { keywords: ["scheduled", "task"] });
command(`${action.id}:toggle`, `${action.task.enabled ? "Turn off" : "Turn on"} automation: ${action.task.title}`, () => toggleAutomation(action.task), { keywords: ["scheduled", "task", "enable", "disable"] });
command(`${action.id}:edit`, `Edit automation: ${action.task.title}`, () => automationEditing.editAutomation(action.task), { keywords: ["scheduled", "task", "editor"] });
command(`${action.id}:delete`, `Delete automation: ${action.task.title}`, () => automationEditing.deleteAutomation(action.task), { keywords: ["scheduled", "task", "remove"] });
}
}
if (parent) command("parent", `Go to parent: ${parent.title}`, () => openThread(parent.threadId), { shortcut: "u" });
@@ -971,6 +1016,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
if (currentModel) command("model", "Change model, options or mode", openModelPicker, { shortcut: "m", keywords: ["provider", "thinking", "reasoning", "effort", "speed", "fast", "access", "approval"] });
commands.push(...workspace.commands);
if (threadId || draft) command("editor", "Write the message in $EDITOR", openEditor, { shortcut: "ctrl+g", keywords: ["vim", "editor", "compose"] });
if (threadId || draft) commands.push(...attach.commands);
command("new-automation", "New automation", automationEditing.newAutomation, { keywords: ["scheduled", "task", "create", "editor"] });
usageInfo.credits.forEach((credit, index) => command(`reset-credit:${index}`, `Use reset credit: ${credit.label}`, () => useResetCredit(credit), { keywords: ["usage", "limit", "reset", "credit"] }));
command("settings", "Settings", openSettings, { keywords: ["preferences", "config", "options", "notifications", "alerts"] });
command("quit", "Quit tui3", quit, { shortcut: "q", keywords: ["exit"] });
@@ -1217,6 +1265,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return;
case "c":
return startDraft();
case "a":
if (threadId || draft) attach.attachFile();
return;
case "m":
return openModelPicker();
case ".":
@@ -1342,6 +1393,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
<strong>tui3</strong>
</text>
<text fg={shell.status.type === "live" ? colors.faint : colors.warn}>{` ${status}`}</text>
{usageInfo.note ? <text fg={colors.warn} wrapMode="none">{` ${usageInfo.note}`}</text> : null}
<box flexGrow={1} />
<text fg={colors.faint}>ctrl+k commands</text>
</box>
@@ -1379,6 +1431,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
rows={settingsRows}
server={serverSettingLines(serverConfig?.config ?? null)}
serverStatus={serverConfig?.status ?? "loading"}
usage={[...usageInfo.lines, ...usageSummaryLines(usage.summary), ...(usage.failed && !usage.summary ? [{ label: "Last 30 days", value: "could not read usage" }] : [])]}
selected={settingsIndex}
path={configPath().replace(homedir(), "~")}
onCycle={(index) => {
@@ -1437,6 +1490,11 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
/>
) : null}
{menu ? <ComposerMenu items={menu.items} selected={menuSelected} empty={menu.empty} width={width - listWidth - (detailsColumn ? DETAILS_WIDTH : 0) - 2} onPick={(index) => chooseMenuItem(menu.items[index])} /> : null}
{attach.line ? (
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={2}>
<text fg={colors.muted} wrapMode="none">{attach.line}</text>
</box>
) : null}
{threadId || draft ? (
<box
border
@@ -1568,7 +1626,7 @@ function hints(
if (state.diff) return "j/k scroll · esc close diff · l details";
if (state.draft) return "i write the first message · p project · m model & mode · w worktree · esc cancel";
const parts = state.attached ? ["j/k scroll"] : ["j/k threads", "/ filter"];
parts.push("i type", "c new", ". actions", "m model", "ctrl+j terminal", "l details");
parts.push("i type", "c new", "a attach", ". actions", "m model", "ctrl+j terminal", "l details");
if (state.parent) parts.push("u parent");
parts.push("ctrl+k commands", "q quit");
if (state.queue === "queued") parts.unshift("Q queue");
+11 -1
View File
@@ -6,11 +6,14 @@ export function SettingsView(props: {
readonly rows: readonly SettingRow[];
readonly server: readonly { label: string; value: string }[];
readonly serverStatus: "loading" | "live" | "error";
/** Usage limits and the last 30 days' totals, read-only; left out until known. */
readonly usage?: readonly { label: string; value: string }[];
readonly selected: number;
readonly path: string;
readonly onCycle: (index: number) => void;
}) {
const labelWidth = Math.max(...props.rows.map((row) => row.label.length), ...props.server.map((line) => line.label.length)) + 2;
const usage = props.usage ?? [];
const labelWidth = Math.max(...props.rows.map((row) => row.label.length), ...props.server.map((line) => line.label.length), ...usage.map((line) => line.label.length)) + 2;
return (
<box flexGrow={1} minHeight={0} flexDirection="column" paddingLeft={2} paddingRight={1}>
<box flexDirection="row" flexShrink={0} height={1}>
@@ -40,6 +43,13 @@ export function SettingsView(props: {
<text fg={colors.text}>{line.value}</text>
</box>
))}
{usage.length > 0 ? <text fg={colors.faint} marginTop={1}>Usage</text> : null}
{usage.map((line) => (
<box key={`${line.label}:${line.value}`} flexDirection="row" height={1}>
<text fg={colors.muted} flexShrink={0}>{` ${line.label.padEnd(labelWidth)}`}</text>
<text fg={colors.text}>{line.value}</text>
</box>
))}
</box>
);
}
+124
View File
@@ -0,0 +1,124 @@
import type { ChatAttachment } from "@t3tools/contracts";
import { spawnSync } from "node:child_process";
import { readFile, stat } from "node:fs/promises";
import { useState } from "react";
import type { T3Session } from "../client/session.ts";
import { attachmentLine, checkAttachment, clipboardImageCommands, expandAttachmentPath } from "../model/attachments.ts";
import type { PaletteCommand } from "../model/palette.ts";
import type { Confirmation } from "./ConfirmBar.tsx";
export interface Attachments {
/** Uploaded and waiting to ride on this composer's next message. */
readonly pending: readonly ChatAttachment[];
/** The one line shown above the composer, or "" when nothing is attached. */
readonly line: string;
readonly commands: readonly (PaletteCommand & { readonly run: () => void })[];
/** Prompts for a path and uploads it; the `a` key and the palette both call this. */
readonly attachFile: () => void;
/** Hands the pending attachments to a send and clears them. */
readonly take: () => readonly ChatAttachment[];
}
/**
* Pending attachments per composer (a thread, or the new-thread draft), uploaded
* as they're picked the way the web composer uploads them, ready to send.
*/
export function useAttachments(deps: {
readonly session: T3Session;
/** The composer they belong to; switching threads keeps each one's list. */
readonly composerKey: string;
/** Relative paths resolve here: the thread's worktree or project folder. */
readonly cwd: string | null;
/** The server's advertised file cap; null refuses files, undefined while it loads. */
readonly maxFileBytes: number | null | undefined;
readonly confirm: (confirmation: Confirmation) => void;
readonly say: (text: string, bad?: boolean) => void;
}): Attachments {
const { session, composerKey, cwd, maxFileBytes, confirm, say } = deps;
const [byComposer, setByComposer] = useState<ReadonlyMap<string, readonly ChatAttachment[]>>(new Map());
const pending = byComposer.get(composerKey) ?? [];
const add = (attachment: ChatAttachment) =>
setByComposer((previous) => new Map(previous).set(composerKey, [...(previous.get(composerKey) ?? []), attachment]));
const upload = (name: string, bytes: Uint8Array, mimeType?: string) => {
if (maxFileBytes === undefined) return say("Still loading the server's attachment limits.", true);
const checked = checkAttachment({ name, sizeBytes: bytes.length, ...(mimeType ? { mimeType } : {}), pending: byComposer.get(composerKey) ?? [], maxFileBytes });
if (!checked.ok) return say(checked.error, true);
say(`Uploading ${checked.upload.name}…`);
session.uploadAttachment(checked.upload, bytes).then(
(attachment) => {
add(attachment);
say(`Attached ${attachment.name}`);
},
(error) => say(`Could not attach ${checked.upload.name}: ${messageOf(error)}`, true),
);
};
const attachFile = () =>
confirm({
title: "Attach file",
...(cwd ? { detail: `Relative to ${cwd}` } : {}),
message: { placeholder: "~/screenshot.png or ./report.pdf" },
confirmLabel: "attach",
run: (text) => {
const path = text.trim();
if (!path) return;
const resolved = expandAttachmentPath(path, cwd);
void (async () => {
const info = await stat(resolved);
if (!info.isFile()) throw new Error("not a file");
return readFile(resolved);
})().then(
(bytes) => upload(resolved, bytes, Bun.file(resolved).type || undefined),
() => say(`Could not read ${resolved}.`, true),
);
},
});
const pasteImage = () => {
let missing = true;
for (const [command, ...args] of clipboardImageCommands(process.platform)) {
const result = spawnSync(command!, args, { maxBuffer: 64 * 1024 * 1024 });
if (result.error && (result.error as NodeJS.ErrnoException).code === "ENOENT") continue;
missing = false;
if (result.status === 0 && result.stdout.length > 0) return upload("pasted-image.png", result.stdout, "image/png");
break;
}
say(missing ? "No clipboard image tool found (wl-paste, xclip, or pngpaste)." : "No image on the clipboard.", true);
};
const remove = (attachment: ChatAttachment) => {
setByComposer((previous) => new Map(previous).set(composerKey, (previous.get(composerKey) ?? []).filter((candidate) => candidate.id !== attachment.id)));
session.deleteAttachment(attachment.id).then(
() => say(`Removed ${attachment.name}`),
(error) => say(`Removed ${attachment.name}; deleting the upload failed: ${messageOf(error)}`, true),
);
};
const commands: Attachments["commands"][number][] = [
{ id: "attach-file", title: "Attach file…", shortcut: "a", keywords: ["attachment", "image", "upload", "file"], run: attachFile },
{ id: "attach-paste-image", title: "Paste image from clipboard", keywords: ["attachment", "image", "screenshot", "clipboard"], run: pasteImage },
...pending.map((attachment) => ({
id: `attach-remove:${attachment.id}`,
title: `Remove attachment: ${attachment.name}`,
keywords: ["attachment", "delete", "detach"],
run: () => remove(attachment),
})),
];
return {
pending,
line: attachmentLine(pending),
commands,
attachFile,
take: () => {
const taken = byComposer.get(composerKey) ?? [];
if (taken.length > 0) setByComposer((previous) => new Map(previous).set(composerKey, []));
return taken;
},
};
}
const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
+50
View File
@@ -0,0 +1,50 @@
import type { CliRenderer } from "@opentui/core";
import type { OrchestrationProjectShell, ScheduledTask } from "@t3tools/contracts";
import type { T3Session } from "../client/session.ts";
import { automationTemplate, newAutomationTemplate, parseAutomation, type AutomationDefaults } from "../model/automations.ts";
import type { Confirmation } from "./ConfirmBar.tsx";
import { editInEditor } from "./editor.ts";
export interface Automations {
readonly newAutomation: () => void;
readonly editAutomation: (task: ScheduledTask) => void;
readonly deleteAutomation: (task: ScheduledTask) => void;
}
/** Creates, edits (in $EDITOR) and deletes automations, as the web's scheduled-task form does. */
export function useAutomations(deps: {
readonly session: T3Session;
readonly renderer: CliRenderer;
readonly projects: readonly OrchestrationProjectShell[];
/** Form defaults for a new task, from the open thread; null when there's nothing to base one on. */
readonly defaults: AutomationDefaults | null;
readonly confirm: (confirmation: Confirmation) => void;
readonly run: (label: string, action: () => Promise<unknown>) => void;
readonly say: (text: string, bad?: boolean) => void;
}): Automations {
const { session, renderer, projects, defaults, confirm, run, say } = deps;
const edit = (template: string, existing?: ScheduledTask) => {
const edited = editInEditor(renderer, template);
if (edited === null) return say("The editor exited with an error; the automation is unchanged.", true);
const parsed = parseAutomation(edited, projects, existing);
if (!parsed.ok) return say(parsed.error, true);
run(existing ? "Automation saved" : "Automation created", () => session.upsertAutomation(parsed.input));
};
return {
newAutomation: () => {
if (!defaults) return say("Open a thread first, so the automation has a project and model.", true);
edit(newAutomationTemplate(projects, defaults));
},
editAutomation: (task) => edit(automationTemplate(task, projects), task),
deleteAutomation: (task) =>
confirm({
title: `Delete automation "${task.title}"?`,
detail: "It stops running and is gone for good.",
confirmLabel: "delete",
run: () => run("Automation deleted", () => session.deleteAutomation(task.id)),
}),
};
}
+41
View File
@@ -0,0 +1,41 @@
import type { UsageSummary } from "@t3tools/contracts";
import { makeWindow } from "@t3tools/shared/usageFormat";
import { useEffect, useRef, useState } from "react";
import type { T3Session } from "../client/session.ts";
/** As the web usage query's stale time: a scan is slow, so keep a fresh-enough answer. */
const STALE_MS = 60_000;
/**
* The last 30 days' usage summary (the web page's default window), fetched while
* `active` — settings open — and refetched once it goes stale.
*/
export function useUsageSummary(session: T3Session, active: boolean): { readonly summary: UsageSummary | null; readonly failed: boolean } {
const [state, setState] = useState<{ summary: UsageSummary | null; failed: boolean }>({ summary: null, failed: false });
const fetchedAt = useRef(0);
useEffect(() => {
if (!active) return;
let cancelled = false;
const fetchOnce = () => {
if (Date.now() - fetchedAt.current < STALE_MS) return;
fetchedAt.current = Date.now();
session.usageSummary(makeWindow(30)).then(
(summary) => {
if (!cancelled) setState({ summary, failed: false });
},
() => {
fetchedAt.current = 0;
if (!cancelled) setState((previous) => ({ summary: previous.summary, failed: true }));
},
);
};
fetchOnce();
const timer = setInterval(fetchOnce, STALE_MS);
return () => {
cancelled = true;
clearInterval(timer);
};
}, [session, active]);
return state;
}