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

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