diff --git a/README.md b/README.md index 83a1a44..80c86e9 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ Navigation: | --- | --- | | `j`/`k`, arrows | next / previous thread (scroll, in `attach`) | | `c` | new thread (see below) | +| `a` | attach a file to the next message (see below) | | `.` | thread actions (see below); a right-click on a thread opens them too | | `m` | model, options (reasoning, fast mode…) and access mode | | `T` | terminals: attach, new, close or clear | @@ -88,7 +89,7 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code - **Thread details:** a column beside the conversation with the workspace, model and mode, the branch with ahead/behind and its pull request, uncommitted changes per file, lineage (forks and subagents), background work and the goal. It opens by itself on terminals 160 columns or wider; on narrow ones `d` shows it in place of the conversation. - **Diffs:** pick `View diff` or a file under Changes to see uncommitted changes as unified diffs in place of the conversation. `D` (or `View changes from this turn`) reviews a turn's checkpoint; `View all changes in this thread` reviews the whole thread. `j`/`k` scroll, `[`/`]` choose a file, and `esc` closes. In uncommitted diffs, `x` or `enter` shows the whole file, including unchanged context; press it again to collapse. Historical checkpoint context is unavailable, as in the web app. - **Git:** the branch section offers the web app's quick action (`Commit & push`, `Push`, `Create PR`…) and its menu. Every action asks first, says when you are on the default branch, and takes an optional commit message (blank lets T3 write one). Progress shows on the bottom line. -- **Servers and automations:** local dev servers the thread started (stop one from the panel) and T3's scheduled tasks with their schedule and next run (run now, or turn on and off). +- **Servers and automations:** local dev servers the thread started (stop one from the panel) and T3's scheduled tasks with their schedule and next run (run now, or turn on and off). Automations are made and changed from the palette: `New automation` and `Edit automation: …` open the web form's fields in `$EDITOR` (title, schedule, project, workspace, model, mode, prompt); save and quit to save. `Delete automation: …` asks first. Webhook signatures and filters are kept as they are; change those in the app. - **Subagents:** subagent work in the conversation and the lineage rows in details are links; `enter` or a click opens the child thread, and `u` goes back. Idle subagents, which the thread list leaves out, are fetched from the server when you open one (on servers that serve them). A running subagent the web could stop gets a "Stop subagent" command in the palette. - **Command palette:** `ctrl+k`, as in the web app. It searches commands and threads with T3's own scoring, then lists full-text hits with snippets under `In messages`; start with `>` for commands only. Message search needs a word of at least three letters. - **Find in thread:** `f` or `Find in thread` in the palette or thread menu searches the whole conversation, counts matches, highlights matching text and loads earlier history to reveal the selected match. Matching Markdown is shown as highlighted plain text while finding. @@ -115,6 +116,10 @@ Submenus open as their own list, and typing finds their items from the top (`thr `c` (or `New thread` in the palette) opens a draft in the current thread's project, with the defaults T3 Code would use: the server's default model and mode for new threads, and the project folder or a new worktree as the project settings say. In the draft, `p` picks the project, `m` the model and mode, and `w` switches between the project folder and a new worktree off the default branch. Write the first message and send it: that starts the thread, which T3 then titles. `esc` cancels. +## Attachments + +`a` in navigation (or `Attach file…` in the palette) prompts for a path: `~` expands, and a relative path is taken from the thread's worktree or project folder. `Paste image from clipboard` in the palette takes a clipboard image instead (`wl-paste`, `xclip`, or `pngpaste` on macOS). Files upload at once, as in the web composer, and their names show above the message box until the next message sends them; `Remove attachment: …` in the palette takes one back and deletes the unsent upload. The web composer's limits apply: GIF, JPEG, PNG and WebP images up to 10 MB each and 80 MB in all, other files up to the server's limit (50 MB at most), 100 attachments per message. A message can be attachments alone. + ## Model, options and mode `m` (or a click on the model under the message box) opens a picker with the access mode, the model's options as the server describes them (reasoning effort, fast mode and whatever else the provider offers), and every model from the providers that are enabled and available. As in the web app: @@ -161,14 +166,14 @@ Open them from the command palette (`Settings`). `j`/`k` move, `enter` or a clic | `notificationMode` | `off`, `sound` (bell), `notifications` (desktop), `notifications-and-sound` | `sound` | | `inAppNotificationsEnabled` | `true`, `false` | `true` | -These use the web app's names, and its defaults except for the two alert settings, which the web app leaves off. The web app keeps them in each browser, so tui3 can't read yours and keeps its own. The same view shows the server's settings that matter here (model and mode for new threads, auto-settle, rate-limited threads), read-only: change those in the app. +These use the web app's names, and its defaults except for the two alert settings, which the web app leaves off. The web app keeps them in each browser, so tui3 can't read yours and keeps its own. The same view shows the server's settings that matter here (model and mode for new threads, auto-settle, rate-limited threads), read-only: change those in the app. Below them is usage: each provider's limit windows as room left, its banked reset credits, and the last 30 days' cost and tokens. When a window is 90% used or more, the top line says so. Spend a banked credit from the palette (`Use reset credit: …`); it asks first, as the app does. Long threads load as a bounded window of recent turns; press `o` for older ones. If the connection drops, tui3 reconnects with backoff and resubscribes. ## How it connects - It finds the local server from `~/.t3/userdata/server-runtime.json` (override with `TUI3_SERVER`). -- On first run it mints its own bearer session with `t3 auth session issue --label tui3`, scoped to `orchestration:read`, `orchestration:operate`, `filesystem:read` (diffs), `source-control:write` (git actions), `terminal:read` and `terminal:operate` (terminals, stopping servers), `diagnostics:read` (usage limits) and `providers:manage` (spending a usage reset credit), and stores it in `~/.config/tui3/credentials.json` (mode 600). Revoke it any time with `t3 auth session revoke`. A stored credential missing any of these scopes is replaced with a new one. For a remote server, pass a token in `TUI3_TOKEN`. +- On first run it mints its own bearer session with `t3 auth session issue --label tui3`, scoped to `orchestration:read`, `orchestration:operate` (attachments and automations ride on it), `filesystem:read` (diffs), `source-control:write` (git actions), `terminal:read` and `terminal:operate` (terminals, stopping servers), `diagnostics:read` (usage totals) and `providers:manage` (reset credits), and stores it in `~/.config/tui3/credentials.json` (mode 600). Revoke it any time with `t3 auth session revoke`. A stored credential missing any of these scopes is replaced with a new one. For a remote server, pass a token in `TUI3_TOKEN`. - It speaks T3 Code's own WebSocket RPC protocol, typed by upstream's `@t3tools/contracts`, and applies thread updates with upstream's own reducers. Both come from `vendor/t3code`, a submodule pinned to the server version this was built against (`v0.1.6-nightly.20261030.3917`). Set `TUI3_DEBUG=/path/to/log` to log thread subscriptions and snapshots. @@ -186,4 +191,4 @@ Type errors after a bump point at the protocol changes to adapt to. ## Not yet supported -Editing queued messages, `#` pull request mentions, plan follow-ups, attachments, forking threads, and reviewing or commenting on diffs. Use the T3 Code app for those. +Editing queued messages, `#` pull request mentions, plan follow-ups, forking threads, and reviewing or commenting on diffs. Use the T3 Code app for those. diff --git a/src/client/auth.ts b/src/client/auth.ts index d1c2172..38f4ab2 100644 --- a/src/client/auth.ts +++ b/src/client/auth.ts @@ -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; diff --git a/src/client/session.ts b/src/client/session.ts index 5dbef20..3622476 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -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 { + return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.scheduledTasksUpsert](input)); + } + + deleteAutomation(id: ScheduledTaskId): Promise { + 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 { + 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 { + 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 { + return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.serverGetUsageSummary](input)); + } + + consumeResetCredit(input: ProviderConsumeResetCreditInput): Promise { + return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.providerConsumeResetCredit](input)); + } + stopServer(server: Pick): Promise { 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 { + sendMessage(threadId: ThreadId, text: string, mode: ComposerDispatchMode = "auto", modelSelection?: ModelSelection, context?: OrchestrationMessageContext, attachments: readonly ChatAttachment[] = []): Promise { 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 & { readonly text: string; readonly context?: OrchestrationMessageContext | undefined }): Promise { - const { text, context, ...rest } = input; + async launchThread(input: Omit & { readonly text: string; readonly context?: OrchestrationMessageContext | undefined; readonly attachments?: readonly ChatAttachment[] }): Promise { + 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; } diff --git a/src/model/attachments.ts b/src/model/attachments.ts new file mode 100644 index 0000000..8ff9205 --- /dev/null +++ b/src/model/attachments.ts @@ -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> = { + 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 = { 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(", ")}` : ""; +} diff --git a/src/model/automations.ts b/src/model/automations.ts new file mode 100644 index 0000000..25abf37 --- /dev/null +++ b/src/model/automations.ts @@ -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(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(); + 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.` }; +} diff --git a/src/model/usage.ts b/src/model/usage.ts new file mode 100644 index 0000000..1f05f8f --- /dev/null +++ b/src/model/usage.ts @@ -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 = { + 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(); + 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; +} diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 475cffb..a85aebf 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -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 tui3 {` ${status}`} + {usageInfo.note ? {` ${usageInfo.note}`} : null} ctrl+k commands @@ -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 ? chooseMenuItem(menu.items[index])} /> : null} + {attach.line ? ( + + {attach.line} + + ) : null} {threadId || draft ? ( 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 ( @@ -40,6 +43,13 @@ export function SettingsView(props: { {line.value} ))} + {usage.length > 0 ? Usage : null} + {usage.map((line) => ( + + {` ${line.label.padEnd(labelWidth)}`} + {line.value} + + ))} ); } diff --git a/src/ui/useAttachments.ts b/src/ui/useAttachments.ts new file mode 100644 index 0000000..4fd89b0 --- /dev/null +++ b/src/ui/useAttachments.ts @@ -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>(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)); diff --git a/src/ui/useAutomations.ts b/src/ui/useAutomations.ts new file mode 100644 index 0000000..c9e9434 --- /dev/null +++ b/src/ui/useAutomations.ts @@ -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) => 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)), + }), + }; +} diff --git a/src/ui/useUsage.ts b/src/ui/useUsage.ts new file mode 100644 index 0000000..e02dd26 --- /dev/null +++ b/src/ui/useUsage.ts @@ -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; +} diff --git a/test/attachments.test.ts b/test/attachments.test.ts new file mode 100644 index 0000000..7d8f881 --- /dev/null +++ b/test/attachments.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, test } from "bun:test"; +import { AttachmentCreateUploadUrlInput, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; +import { homedir } from "node:os"; +import { join } from "node:path"; + +import { attachmentLine, checkAttachment, clipboardImageCommands, expandAttachmentPath } from "../src/model/attachments.ts"; + +const isUpload = Schema.is(AttachmentCreateUploadUrlInput); + +describe("expandAttachmentPath", () => { + test("expands ~ and resolves relative paths against the thread's folder", () => { + expect(expandAttachmentPath("~/shot.png", "/repo/app")).toBe(join(homedir(), "shot.png")); + expect(expandAttachmentPath("docs/report.pdf", "/repo/app")).toBe("/repo/app/docs/report.pdf"); + expect(expandAttachmentPath("/tmp/a.png", "/repo/app")).toBe("/tmp/a.png"); + }); +}); + +describe("checkAttachment", () => { + test("a supported image uploads as an image, whatever the OS reported", () => { + const result = checkAttachment({ name: "/tmp/Screen.PNG", sizeBytes: 2048, mimeType: "application/octet-stream", pending: [], maxFileBytes: null }); + expect(result.ok && result.upload).toEqual({ type: "image", name: "Screen.PNG", mimeType: "image/png", sizeBytes: 2048 }); + expect(result.ok && isUpload(result.upload)).toBe(true); + }); + + test("an image over the cap is refused, as an empty file is", () => { + const big = checkAttachment({ name: "big.jpg", sizeBytes: PROVIDER_SEND_TURN_MAX_IMAGE_BYTES + 1, pending: [], maxFileBytes: 100 }); + expect(big.ok).toBe(false); + expect(!big.ok && big.error).toContain("exceeds the 10 MB attachment limit"); + const empty = checkAttachment({ name: "a.txt", sizeBytes: 0, pending: [], maxFileBytes: 100 }); + expect(empty).toEqual({ ok: false, error: "'a.txt' is empty or could not be read." }); + }); + + test("files need the server's file support and fit its advertised limit", () => { + expect(checkAttachment({ name: "a.zip", sizeBytes: 10, pending: [], maxFileBytes: null })).toEqual({ ok: false, error: "This server does not support file attachments." }); + const over = checkAttachment({ name: "a.zip", sizeBytes: 2048, pending: [], maxFileBytes: 1024 }); + expect(over.ok).toBe(false); + const ok = checkAttachment({ name: "a.zip", sizeBytes: 512, mimeType: "application/zip", pending: [], maxFileBytes: 1024 }); + expect(ok.ok && ok.upload).toEqual({ type: "file", name: "a.zip", mimeType: "application/zip", sizeBytes: 512 }); + expect(ok.ok && isUpload(ok.upload)).toBe(true); + }); + + test("pending images count against the per-message total", () => { + const tenMb = PROVIDER_SEND_TURN_MAX_IMAGE_BYTES; + const pending = Array.from({ length: 8 }, (_, index) => ({ type: "image" as const, id: `a${index}`, name: `a${index}.png`, mimeType: "image/png", sizeBytes: tenMb })); + const result = checkAttachment({ name: "one-more.png", sizeBytes: 1, pending, maxFileBytes: null }); + expect(result.ok).toBe(false); + expect(!result.ok && result.error).toContain("80 MiB"); + }); +}); + +describe("clipboard", () => { + test("each platform's grabber comes first", () => { + expect(clipboardImageCommands("darwin")).toEqual([["pngpaste", "-"]]); + expect(clipboardImageCommands("linux")[0]).toEqual(["wl-paste", "--type", "image/png"]); + expect(attachmentLine([{ type: "file", id: "a", name: "a.txt", mimeType: "text/plain", sizeBytes: 1 }])).toBe("Attached: a.txt"); + }); +}); diff --git a/test/automations.test.ts b/test/automations.test.ts new file mode 100644 index 0000000..ad556d5 --- /dev/null +++ b/test/automations.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, test } from "bun:test"; +import { ScheduledTaskUpsertInput, type OrchestrationProjectShell, type ScheduledTask } from "@t3tools/contracts"; +import * as Schema from "effect/Schema"; + +import { automationTemplate, newAutomationTemplate, parseAutomation } from "../src/model/automations.ts"; + +const projects = [ + { id: "p1", title: "tasknotes", workspaceRoot: "/repo/tasknotes" }, + { id: "p2", title: "tui3", workspaceRoot: "/repo/tui3" }, +] as unknown as OrchestrationProjectShell[]; + +const task = (extra: Record = {}) => + ({ + id: "task-1", + title: "Nightly tidy", + prompt: "Tidy the notes.\nThen summarise.", + enabled: true, + schedule: { type: "fixed_time", timeOfDay: "09:00", weekdays: [1, 2, 3, 4, 5] }, + projectId: "p1", + threadId: "t1", + workspaceStrategy: { type: "worktree", baseRef: "main", startFromOrigin: true }, + modelSelection: { instanceId: "codex", model: "gpt-5", options: [{ id: "effort", value: "high" }] }, + runtimeMode: "full-access", + interactionMode: "default", + ...extra, + }) as unknown as ScheduledTask; + +const isUpsert = Schema.is(ScheduledTaskUpsertInput); + +describe("automation templates", () => { + test("an edited task round-trips, keeping its model options", () => { + const parsed = parseAutomation(automationTemplate(task(), projects), projects, task()); + expect(parsed.ok).toBe(true); + if (!parsed.ok) return; + expect(isUpsert(parsed.input)).toBe(true); + expect(parsed.input).toMatchObject({ + id: "task-1", + requireExisting: true, + title: "Nightly tidy", + prompt: "Tidy the notes.\nThen summarise.", + schedule: { type: "fixed_time", timeOfDay: "09:00", weekdays: [1, 2, 3, 4, 5] }, + projectId: "p1", + threadId: "t1", + workspaceStrategy: { type: "worktree", baseRef: "main", startFromOrigin: true }, + modelSelection: { instanceId: "codex", model: "gpt-5", options: [{ id: "effort", value: "high" }] }, + }); + }); + + test("a new task takes the edited title, interval and prompt", () => { + const text = newAutomationTemplate(projects, { projectId: "p2", threadId: "", modelSelection: { instanceId: "claude" as never, model: "opus" }, runtimeMode: "auto" }) + .replace("Title: ", "Title: Sweep") + .replace("Schedule: fixed 09:00 Mon,Tue,Wed,Thu,Fri", "Schedule: interval 2h") + .replace("Prompt:\n", "Prompt:\nSweep the inbox.\n"); + const parsed = parseAutomation(text, projects); + expect(parsed.ok).toBe(true); + if (!parsed.ok) return; + expect(isUpsert(parsed.input)).toBe(true); + expect(parsed.input).toMatchObject({ title: "Sweep", schedule: { type: "interval", everyMs: 7_200_000 }, projectId: "p2", threadId: null, runtimeMode: "auto" }); + expect(parsed.input).not.toHaveProperty("id"); + }); + + test("the web form's checks apply: complete, a minute or more, a checkout path", () => { + const blank = newAutomationTemplate(projects, { projectId: "p1", threadId: "", modelSelection: { instanceId: "codex" as never, model: "gpt-5" }, runtimeMode: "full-access" }); + expect(parseAutomation(blank, projects)).toEqual({ ok: false, error: "Scheduled task is incomplete: add a title, prompt, project, and model." }); + const filled = blank.replace("Title: ", "Title: X").replace("Prompt:\n", "Prompt:\nDo it.\n"); + expect(parseAutomation(filled.replace("Schedule: fixed 09:00 Mon,Tue,Wed,Thu,Fri", "Schedule: interval 0m"), projects).ok).toBe(false); + expect(parseAutomation(filled.replace("Workspace: worktree", "Workspace: existing_worktree"), projects)).toMatchObject({ ok: false, error: expect.stringContaining("Checkout path is required") }); + expect(parseAutomation(filled.replace("Project: tasknotes", "Project: nope"), projects).ok).toBe(false); + expect(parseAutomation(filled.replace("Schedule: fixed 09:00 Mon,Tue,Wed,Thu,Fri", "Schedule: whenever"), projects).ok).toBe(false); + }); + + test("editing a webhook task keeps its signature and dedupe, and leaves filters stored", () => { + const hook = task({ + schedule: { + type: "webhook", + signature: { header: "x-hub-signature-256", encoding: "hex", prefix: "sha256=" }, + maxDeliveryAgeMinutes: 60, + dedupe: { replayKey: "{{headers.x-id}}" }, + filters: [{ path: "body.action", op: "equals", value: "open" }], + }, + }); + const parsed = parseAutomation(automationTemplate(hook, projects), projects, hook); + expect(parsed.ok).toBe(true); + if (!parsed.ok) return; + expect(isUpsert(parsed.input)).toBe(true); + expect(parsed.input.schedule).toEqual({ + type: "webhook", + signature: { header: "x-hub-signature-256", encoding: "hex", prefix: "sha256=" }, + maxDeliveryAgeMinutes: 60, + dedupe: { replayKey: "{{headers.x-id}}" }, + }); + }); +}); diff --git a/test/commands.test.ts b/test/commands.test.ts index 7faa7db..2d7a071 100644 --- a/test/commands.test.ts +++ b/test/commands.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { NodeId, OrchestrationV2Command, OrchestrationV2ThreadLaunchInput, ProjectId, ProviderInstanceId, RunId, ThreadId, RuntimeRequestId, type OrchestrationV2Subagent } from "@t3tools/contracts"; +import { AttachmentCreateUploadUrlInput, AttachmentDeleteInput, NodeId, OrchestrationV2Command, OrchestrationV2ThreadLaunchInput, ProjectId, ProviderConsumeResetCreditInput, ProviderInstanceId, RunId, ScheduledTaskDeleteInput, ThreadId, RuntimeRequestId, UsageSummaryInput, type ChatAttachment, type OrchestrationV2Subagent } from "@t3tools/contracts"; import * as Effect from "effect/Effect"; import * as Schema from "effect/Schema"; @@ -94,6 +94,67 @@ describe("commands tui3 dispatches", () => { expect(Schema.is(OrchestrationV2ThreadLaunchInput)(payload)).toBe(true); expect(payload).toMatchObject({ initialMessage: { text: "Fix the flaky test", attachments: [] } }); }); + + test("attachments ride on a message and on a new thread's first message", async () => { + const attachment = { type: "image", id: "upload-1", name: "shot.png", mimeType: "image/png", sizeBytes: 12 } as ChatAttachment; + const { session, sent } = capturingSession(); + await session.sendMessage(threadId, "see this", "auto", undefined, undefined, [attachment]); + expect(isCommand(sent[0])).toBe(true); + expect(sent[0]).toMatchObject({ type: "message.dispatch", attachments: [attachment] }); + + const launching = new T3Session(); + let payload: unknown; + const rpc = { "orchestration.launchThread": (input: unknown) => ((payload = input), Effect.succeed({ threadId: ThreadId.make("new-2") })) }; + (launching as unknown as { connection: unknown }).connection = { rpc }; + await launching.launchThread({ + projectId: ProjectId.make("p1"), + title: "Attached image", + generateTitle: true, + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" }, + runtimeMode: "full-access", + interactionMode: "default", + workspaceStrategy: { type: "root" }, + text: "see this", + attachments: [attachment], + }); + expect(Schema.is(OrchestrationV2ThreadLaunchInput)(payload)).toBe(true); + expect(payload).toMatchObject({ initialMessage: { attachments: [attachment] } }); + }); + + test("upload mint, delete, usage, reset credit and automation delete payloads validate", async () => { + const session = new T3Session(); + const calls = new Map(); + const rpc = new Proxy( + {}, + { + get: (_target, method) => (input: unknown) => { + calls.set(String(method), input); + if (method === "attachments.createUploadUrl") return Effect.succeed({ attachmentId: "upload-9", relativeUrl: "/upload?sig=x", expiresAt: 1 }); + if (method === "server.getUsageSummary") return Effect.succeed({ buckets: [] }); + if (method === "provider.consumeResetCredit") return Effect.succeed({ outcome: "reset" }); + return Effect.succeed({}); + }, + }, + ); + (session as unknown as { connection: unknown }).connection = { rpc, target: { httpBaseUrl: "http://127.0.0.1:9" } }; + const originalFetch = globalThis.fetch; + globalThis.fetch = (async () => new Response(null, { status: 200 })) as unknown as typeof fetch; + try { + const uploaded = await session.uploadAttachment({ type: "image", name: "shot.png", mimeType: "image/png", sizeBytes: 3 }, new Uint8Array([1, 2, 3])); + expect(uploaded).toEqual({ type: "image", id: "upload-9", name: "shot.png", mimeType: "image/png", sizeBytes: 3 }); + } finally { + globalThis.fetch = originalFetch; + } + await session.deleteAttachment("upload-9"); + await session.usageSummary({ sinceDay: "2026-10-03" as never, untilDay: "2026-11-02" as never, timeZone: "UTC" }); + await session.consumeResetCredit({ instanceId: ProviderInstanceId.make("claude-1") }); + await session.deleteAutomation("task-1" as never); + expect(Schema.is(AttachmentCreateUploadUrlInput)(calls.get("attachments.createUploadUrl"))).toBe(true); + expect(Schema.is(AttachmentDeleteInput)(calls.get("attachments.delete"))).toBe(true); + expect(Schema.is(UsageSummaryInput)(calls.get("server.getUsageSummary"))).toBe(true); + expect(Schema.is(ProviderConsumeResetCreditInput)(calls.get("provider.consumeResetCredit"))).toBe(true); + expect(Schema.is(ScheduledTaskDeleteInput)(calls.get("scheduledTasks.delete"))).toBe(true); + }); }); describe("queue, resume and subagent commands", () => { diff --git a/test/usage.test.ts b/test/usage.test.ts new file mode 100644 index 0000000..eb65f32 --- /dev/null +++ b/test/usage.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, test } from "bun:test"; +import { ProviderInstanceId, type ServerConfig, type UsageSummary } from "@t3tools/contracts"; + +import { resetCreditOutcome, usageLimits, usageSummaryLines } from "../src/model/usage.ts"; + +const now = Date.parse("2026-11-02T12:00:00.000Z"); + +const provider = (usedPercent: number, extra: Record = {}) => ({ + instanceId: "claude-1", + driver: "claudeAgent", + displayName: "Claude", + enabled: true, + installed: true, + availability: "available", + auth: { status: "authenticated", email: "a@example.com", label: "Max" }, + models: [], + usageLimits: { + checkedAt: "2026-11-02T11:00:00.000Z", + windows: [{ id: "seven_day", kind: "weekly", label: "Weekly", usedPercent, resetsAt: "2026-11-04T12:00:00.000Z" }], + resetCredits: { availableCount: 2, nextExpiresAt: "2026-11-09T12:00:00.000Z" }, + }, + ...extra, +}); + +const config = (providers: unknown[]) => + ({ + environment: { environmentId: "env-1", label: "This Mac" }, + providers, + }) as unknown as ServerConfig; + +describe("usageLimits", () => { + test("lines read as room left, with banked credits the palette can spend", () => { + const info = usageLimits(config([provider(40)]), now); + expect(info.lines).toEqual([ + { label: "Claude · Max Weekly", value: "60% left · resets in 2d 0h" }, + { label: "Claude · Max reset credits", value: "2 reset credits banked · next expires in 7d 0h" }, + ]); + expect(info.note).toBeNull(); + expect(info.credits).toEqual([{ label: "Claude · Max", input: { instanceId: ProviderInstanceId.make("claude-1") }, credits: { availableCount: 2, nextExpiresAt: "2026-11-09T12:00:00.000Z" } }]); + }); + + test("a near or reached window becomes the status note", () => { + expect(usageLimits(config([provider(95)]), now).note).toBe("Claude Weekly: 5% left · resets in 2d 0h"); + expect(usageLimits(config([provider(100)]), now).note).toBe("Claude Weekly: limit reached · resets in 2d 0h"); + expect(usageLimits(null, now)).toEqual({ lines: [], note: null, credits: [] }); + }); +}); + +describe("usageSummaryLines", () => { + test("totals come first, then providers by cost", () => { + const summary = { + buckets: [ + { provider: "claude", costUsd: 3, totals: { uncachedInputTokens: 1000, cachedInputTokens: 0, cacheCreationTokens: 0, outputTokens: 500 } }, + { provider: "codex", costUsd: 7.5, totals: { uncachedInputTokens: 2000, cachedInputTokens: 1000, cacheCreationTokens: 0, outputTokens: 500 } }, + ], + sources: [{ distinctSessions: 4 }], + } as unknown as UsageSummary; + const lines = usageSummaryLines(summary); + expect(lines[0]!.label).toBe("Last 30 days"); + expect(lines[0]!.value).toContain("$10.50"); + expect(lines[0]!.value).toContain("4 sessions"); + expect(lines.slice(1).map((line) => line.label)).toEqual(["codex", "claude"]); + expect(resetCreditOutcome({ outcome: "reset" })).toBe("Reset applied. Your windows have cleared."); + expect(resetCreditOutcome({ outcome: "reset", warning: "Careful" })).toBe("Careful"); + }); +});