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

+58
View File
@@ -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");
});
});
+93
View File
@@ -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<string, unknown> = {}) =>
({
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}}" },
});
});
});
+62 -1
View File
@@ -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<string, unknown>();
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", () => {
+66
View File
@@ -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<string, unknown> = {}) => ({
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");
});
});