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

+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;
}