SLOPSHOPPER

uploads.sh

Host screenshots, GIFs, recordings, and files on uploads.sh and embed them in GitHub PRs and issues.

panebandguardcommandtoastprocess
★ 19v0.4.6Apache-2.0updated 2026-10-26buildinternet/uploads/plugins/claude/uploads
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · uploads
│ ┃ Staged attachments ✕ › fix the failing auth test and add an audit log call │ ┃ Nothing staged for this branch. │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /uploads-staged │ ⎿ uploads: Opened the staged attachments pane. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Staged attachments
Nothing staged for this branch.
README

uploads.sh plugin

Get screenshots, GIFs, screen recordings, and other files into GitHub pull requests and issues from inside your coding agent. The plugin hosts each file on uploads.sh and gives your agent a stable public URL to embed, so a PR can show a before/after or a recording of the bug instead of describing it in prose.

The plugin is one folder (plugins/claude/uploads) in the common agent-plugin layout. .claude-plugin/plugin.json is the manifest, .mcp.json declares the hosted MCP server, skills/ holds the three skills, and hooks/ holds the pre-PR reminder. The same folder serves every listing below.

What it bundles

ComponentInvocationPurpose
github-screenshots skill/uploads:github-screenshotsCapture, host, and embed a visual in a PR or issue
annotate-screenshots skill/uploads:annotate-screenshotsAdd boxes, arrows, labels, and redactions to a capture
uploads-cli skill/uploads:uploads-cliFull reference for the optional uploads CLI
uploads MCP server(tools)Hosted server at https://agents.uploads.sh/mcp
PR screenshot reminder hook(automatic)Advisory nudge before gh pr create on a UI branch with no screenshots
Staged media mod/uploads-stagedClaude Code: staged attachments above the prompt, attached on PR open

The slash names in the table are how Claude Code invokes the skills. Other agents discover the same skills/ directory by layout.

The staged media mod (hooks/register.tsx) is Claude Code only. It needs Claude Code 2.1.287 or later. Older versions load the rest of the plugin and skip the mod. It draws in the terminal and the Desktop app's Code tab. Elsewhere, such as the VS Code extension's chat panel or claude -p, it still attaches files and tells Claude, but shows nothing.

On the Desktop app, the band shows thumbnails of the staged attachments. View or /uploads-staged opens a pane where you can see each one, copy its markdown, remove it, or copy the PR's feed link. The footnote links to your workspace on uploads.sh. Hide hides the band until the staged set changes.

Install

Pick your agent. The same folder serves both listings.

Claude Code

/plugin marketplace add buildinternet/uploads
/plugin install uploads@uploads

uploads is also listed in the Claude directory, where you can add it on claude.ai and in Cowork.

Grok Build

This plugin is submitted to the xAI plugin marketplace as uploads. Once listed, run /plugin in Grok Build, search for uploads.sh, and install it. The marketplace pins a commit of this repo, so updates arrive when the catalog entry is bumped.

Sign in

On first use, the MCP server opens the uploads.sh sign-in and consent screen in your browser. The token it issues can read and write files in the workspace you pick. See <https://uploads.sh/auth.md>.

Hooks

The pre-PR reminder is a PreToolUse hook with matcher Bash. A matcher can only key the tool name, so the hook starts before Bash commands. The script acts only on gh pr create. That filter lives in the uploads CLI, not in the matcher.

The hook command names the script directly:

"${CLAUDE_PLUGIN_ROOT}"/hooks/pre-pr-screenshot.sh

That path is the whole program. It uses ${CLAUDE_PLUGIN_ROOT} and no other variable. Claude Code sets CLAUDE_PLUGIN_ROOT to the installed plugin directory. Grok Build sets GROK_PLUGIN_ROOT to that same directory and also sets CLAUDE_PLUGIN_ROOT. Codex sets PLUGIN_ROOT and also sets CLAUDE_PLUGIN_ROOT. Codex reads the command string and ignores an args array, so the path stays in command.

The script runs the locally installed uploads CLI (uploads hook pre-pr-screenshot). If the CLI is not installed or not signed in, the hook does nothing. Set UPLOADS_HOOK_DISABLE=1 to turn it off.

hooks/register.tsx is a separate Claude Code mod. It draws staged attachments above the prompt. It is not part of the portable hooks contract. It needs Claude Code 2.1.287 or later.

License

Apache-2.0, the same license as this repository (license in .claude-plugin/plugin.json).

Data and network access

The plugin reaches these uploads.sh services:

  • agents.uploads.sh: the hosted MCP server behind the upload, list, metadata, and comment tools. It receives the files you ask your agent to upload, their file names, and metadata such as the repository, branch, and PR number. Uploaded files are served from a public URL on uploads.sh, so anyone with the link can view them.
  • api.uploads.sh: the REST API used by the optional uploads CLI. The skills only send requests here if you install the CLI and your agent runs it.
  • GitHub: when you attach files to a PR or issue, one comment that embeds them is posted or updated. The uploads.sh GitHub App posts it in repositories where you install the app; otherwise the CLI posts it through your local gh login.

When the reminder hook runs (see Hooks), it reads the branch name and changed files from local git and asks the uploads.sh API whether any files are staged for that branch. It uses the CLI's own sign-in. It prints a reminder. It sends nothing if the CLI is missing or not signed in.

The staged media mod also runs the local uploads CLI, plus gh pr view, with their own sign-ins. It reads what is staged for the current branch (with uploads staged) when a session starts and after shell commands that run uploads, switch branches, or open a PR. After gh pr create opens a PR, it looks up the PR's head branch:

  • If the repository is linked to your workspace, the GitHub App attaches the staged files, and the mod only reports it.
  • Otherwise, the mod runs uploads attach --promote for that PR. Turn off the Attach staged files on gh pr create option in /plugin to have it only report what is waiting.

On the Desktop app, the pane also runs uploads delete when you remove an attachment, uploads approve when you approve a held file, uploads feed create when you copy the feed link, and gh pr view to find the branch's open PR. Thumbnails are fetched with curl from storage.uploads.sh, resized by Cloudflare's image transform, and kept in the mod's session state.

Every program the mod starts goes through one helper, run in hooks/register.tsx. That helper calls $.process.run with an argument list, so a scan of that line cannot see the program. The helper runs only the commands in this table, each written here as fixed text.

ProgramWhy it runsWhat it sends, and where
uploads staged --format jsonSession start, after a matching shell command, and when the session is idleBranch and repository name to the uploads.sh API at api.uploads.sh, using the CLI's saved sign-in
uploads staged --format json --branch <branch> --repo <owner/repo>After gh pr create, to read files staged on the PR's head branchThat branch and repository to the uploads.sh API
uploads attach --promote --pr <n> --repo <owner/repo> --from-branch <branch> --jsonAfter gh pr create, when this workspace should attach the filesPR number, repository, and branch to the uploads.sh API, which posts the PR comment
uploads feed create --repo <owner/repo> --pr <n>You press Copy link in the paneRepository and PR number to the uploads.sh API. The CLI prints the feed URL back to the mod
uploads delete <key>You press Remove in the paneThe file's key to the uploads.sh API
uploads approve <key...>You press Approve on a held file in the paneThe held files' keys to the uploads.sh API, which releases them
gh pr view --json number,url,stateWith the staged read, to find the open PR for the current branchThe current branch, through your local gh login, to the GitHub API
gh pr view <n> --repo <owner/repo> --json headRefName -q .headRefNameAfter gh pr create, to learn the PR's head branchThe PR number and repository to the GitHub API
`sh -c 'curl -sfL --max-time 15 "$1" \base64' sh <url>`Drawing a thumbnail or a large preview on the Desktop appAn HTTPS GET to storage.uploads.sh. For an image on that host, <url> is Cloudflare's image transform (/cdn-cgi/image/...). The JPEG stays in the mod's session

<branch>, <owner/repo>, <n>, <key>, and <url> are the only parts that change. The words of each command stay as written.

Local data the mod reads is the staged-file list from uploads staged, the open PR from gh pr view, and those thumbnail bytes. It keeps them in the mod's session state.

What the mod reads from the conversation: the text of shell commands Claude runs, so it can spot uploads, a branch switch, or gh pr create, and the output of gh pr create, so it can read the new PR's URL. That text stays on the machine. The values that leave are the ones in the table, and each one leaves through the program in its row.

If the CLI is not installed or not signed in, the mod does nothing.

See the privacy policy and terms.

Updating

Third-party marketplaces don't update automatically by default. To pick up a new version in Claude Code:

/plugin marketplace update uploads
/plugin update uploads@uploads

Grok Build updates when the xAI catalog entry's pinned commit is bumped.

Source 2 files
hooks/register.tsx 1251 lines
1import { atom, read, update } from "claude-code";
2import type { EngineInterface, Register } from "claude-code";
3
4import type { Attached, BandRow, Binding, FileRef, Staged } from "../types";
5
6const staged = atom({ plugin: "uploads", key: "staged" } as const, null);
7const attached = atom({ plugin: "uploads", key: "attached" } as const, null);
8const isExpanded = atom({ plugin: "uploads", key: "isExpanded" } as const, false);
9// Desktop: JPEG data URIs of the staged images (storage URL -> URI; "" = failed).
10const thumbs = atom({ plugin: "uploads", key: "thumbs" } as const, {});
11const large = atom({ plugin: "uploads", key: "large" } as const, {});
12// The row the pane's detail view shows; null shows the grid.
13const preview = atom({ plugin: "uploads", key: "preview" } as const, null);
14// The open PR for the session branch, for the pane's feed link.
15const openPr = atom({ plugin: "uploads", key: "openPr" } as const, null);
16const feedUrl = atom({ plugin: "uploads", key: "feedUrl" } as const, null);
17// The staged set the desktop band is hidden for; a change shows it again.
18const dismissed = atom({ plugin: "uploads", key: "dismissed" } as const, null);
19
20const PANE = "uploads-staged";
21const PANE_TITLE = "Staged attachments";
22
23// Bash commands that can change what is staged for the branch, or which branch it is.
24const REFRESH_AFTER =
25  /\buploads\s+(attach|put|screenshot|shot|delete|unstage)\b|\bgit\s+(checkout|switch|branch\s+-m)\b|\bgh\s+pr\s+create\b/;
26const PR_CREATE = /\bgh\s+pr\s+create\b/;
27const PR_URL = /https:\/\/github\.com\/([\w.-]+\/[\w.-]+)\/pull\/(\d+)/g;
28const IDLE_REFRESH_MS = 2 * 60 * 1000;
29const STALE_STAGED_MS = 30 * 24 * 60 * 60 * 1000;
30// Long enough for the GitHub App's webhook to promote the files after a PR opens.
31const AFTER_PR_REFRESH_MS = 15_000;
32
33const BINDINGS: readonly Binding[] = ["self", "none", "other", "unknown"];
34
35// Before/after pairing, mirroring the attachments comment (comment-render's
36// pairAttachments): images only; same `path` metadata with one `state=before`
37// and one `state=after`, else filename stems that differ only by the token.
38// The band shows each pair as one row, so a missing half shows as a gap.
39const IMAGE_EXT = /\.(png|jpe?g|gif|webp|avif)$/i;
40const STEM_TOKEN = /(^|[-_.])(before|after)($|[-_.])/i;
41
42type RawFile = {
43  key?: unknown;
44  filename: string;
45  state?: unknown;
46  path?: unknown;
47  url?: unknown;
48  size?: unknown;
49  stagedAt?: unknown;
50  /** `gh.branch`, when the CLI includes it. Older CLIs omit the field. */
51  branch?: unknown;
52  /** True while the file is held for review. Older CLIs omit the field. */
53  held?: unknown;
54};
55type Role = "before" | "after";
56
57/** The uploads.sh file page (preview and details) for a storage URL; else the URL itself. */
58const filePage = (url: string): string => {
59  const match = /^https:\/\/storage\.uploads\.sh\/(.+)$/.exec(url);
60  return match ? `https://uploads.sh/f/${match[1]}` : url;
61};
62
63const fileRef = (file: RawFile): FileRef => ({
64  key: typeof file.key === "string" ? file.key : file.filename,
65  name: file.filename,
66  url: typeof file.url === "string" ? filePage(file.url) : null,
67  src: typeof file.url === "string" ? file.url : null,
68  size: typeof file.size === "number" ? file.size : null,
69  stagedAt: typeof file.stagedAt === "string" ? file.stagedAt : null,
70  held: file.held === true,
71});
72
73/** A file's before/after role and the key its other half shares, or null for neither. */
74const roleOf = (file: RawFile): { role: Role; key: string; label: string } | null => {
75  if (!IMAGE_EXT.test(file.filename)) {
76    return null;
77  }
78  const dot = file.filename.lastIndexOf(".");
79  const stem = file.filename.slice(0, dot);
80  const meta = typeof file.state === "string" ? file.state.trim().toLowerCase() : "";
81  const path = typeof file.path === "string" ? file.path.trim() : "";
82  const token = STEM_TOKEN.exec(stem);
83  const role: Role | null =
84    meta === "before" || meta === "after" ? meta : token ? (token[2]!.toLowerCase() as Role) : null;
85  if (role === null) {
86    return null;
87  }
88  // Only a file with nothing to pair on stands alone under its own name.
89  const solo = { role, key: `solo:${file.filename}`, label: stem };
90  if (path && path !== "/") {
91    return meta === role ? { role, key: `path:${path}`, label: path } : solo;
92  }
93  if (!token) {
94    return solo;
95  }
96  const end = token.index + token[1]!.length + token[2]!.length;
97  const base =
98    token[1]!.length > 0
99      ? stem.slice(0, token.index) + stem.slice(end)
100      : stem.slice(end + token[3]!.length);
101  return {
102    role,
103    key: `stem:${base.toLowerCase()}${file.filename.slice(dot).toLowerCase()}`,
104    label: base,
105  };
106};
107
108/** The band's rows in staged order: a pair (either half may be missing), or a plain file. */
109const toRows = (files: readonly RawFile[]): BandRow[] => {
110  const order: (string | RawFile)[] = [];
111  const groups = new Map<string, { label: string; before: RawFile[]; after: RawFile[] }>();
112  for (const file of files) {
113    const found = roleOf(file);
114    if (found === null) {
115      order.push(file);
116      continue;
117    }
118    let group = groups.get(found.key);
119    if (!group) {
120      group = { label: found.label, before: [], after: [] };
121      groups.set(found.key, group);
122      order.push(found.key);
123    }
124    group[found.role].push(file);
125  }
126  return order.flatMap((entry): BandRow[] => {
127    if (typeof entry !== "string") {
128      return [{ kind: "file", file: fileRef(entry) }];
129    }
130    const { label, before, after } = groups.get(entry)!;
131    // More than one of a side is ambiguous, as in the comment: no pairing, one row each.
132    if (before.length > 1 || after.length > 1) {
133      return [
134        ...before.map((f): BandRow => ({ kind: "pair", label, before: fileRef(f), after: null })),
135        ...after.map((f): BandRow => ({ kind: "pair", label, before: null, after: fileRef(f) })),
136      ];
137    }
138    return [
139      {
140        kind: "pair",
141        label,
142        before: before[0] ? fileRef(before[0]) : null,
143        after: after[0] ? fileRef(after[0]) : null,
144      },
145    ];
146  });
147};
148
149/** True when every kept file was staged more than 30 days before `now`. */
150const viewIsStale = (view: Staged, now: number): boolean => {
151  const times: (string | null)[] = [];
152  for (const row of view.rows) {
153    if (row.kind === "file") times.push(row.file.stagedAt);
154    else {
155      if (row.before) times.push(row.before.stagedAt);
156      if (row.after) times.push(row.after.stagedAt);
157    }
158  }
159  if (times.length === 0) return false;
160  return times.every((at) => {
161    if (!at) return false;
162    const parsed = Date.parse(at);
163    return Number.isFinite(parsed) && now - parsed > STALE_STAGED_MS;
164  });
165};
166
167/** How many staged files a row stands for. */
168const filesIn = (row: BandRow): number =>
169  row.kind === "file" ? 1 : (row.before ? 1 : 0) + (row.after ? 1 : 0);
170
171// The terminal's expanded band lists at most this many rows.
172const MAX_ROWS = 8;
173
174const formatSize = (bytes: number | null): string =>
175  bytes === null ? "" : bytes < 1024 ? `${bytes} B` : `${Math.round(bytes / 1024)} KB`;
176
177const parseStaged = (stdout: string): Staged | null => {
178  try {
179    const doc = JSON.parse(stdout);
180    if (
181      typeof doc?.repo !== "string" ||
182      typeof doc?.branch !== "string" ||
183      !Array.isArray(doc?.files)
184    ) {
185      return null;
186    }
187    const state = doc.binding?.state;
188    const wanted = doc.branch.toLowerCase();
189    // A file that names a different branch is not staged for this one. Files
190    // with no `branch` (an older CLI) stay: the count is already what that
191    // CLI returned. Count the files we keep, not `doc.files.length`, so a
192    // mismatched row cannot make the band or the PR-create hook claim work.
193    const foreignBranches: string[] = [];
194    const files: RawFile[] = [];
195    for (const raw of doc.files as RawFile[]) {
196      if (typeof raw?.filename !== "string") continue;
197      const fileBranch = typeof raw.branch === "string" ? raw.branch : undefined;
198      if (fileBranch && fileBranch.toLowerCase() !== wanted) {
199        if (!foreignBranches.some((name) => name.toLowerCase() === fileBranch.toLowerCase())) {
200          foreignBranches.push(fileBranch);
201        }
202        continue;
203      }
204      files.push(raw);
205    }
206    return {
207      repo: doc.repo,
208      branch: doc.branch,
209      count: files.length,
210      rows: toRows(files),
211      binding: BINDINGS.includes(state) ? state : "unknown",
212      autoAttach: doc.binding?.autoAttach === true,
213      foreignBranches,
214    };
215  } catch {
216    return null;
217  }
218};
219
220/**
221 * What `uploads attach --promote --json` promoted and skipped, or null when it
222 * printed nothing usable (the server call failed, or the output isn't JSON).
223 */
224const parsePromotion = (
225  stdout: string | null,
226): { promoted: number; skipped: number; held: number } | null => {
227  try {
228    const doc = JSON.parse(stdout ?? "");
229    const promotion = doc?.promotion;
230    if (!Array.isArray(promotion?.promoted) || !Array.isArray(promotion?.skipped)) {
231      return null;
232    }
233    // The synced comment counts the PR's files held for review.
234    const held = typeof doc.comment?.held === "number" ? doc.comment.held : 0;
235    return { promoted: promotion.promoted.length, skipped: promotion.skipped.length, held };
236  } catch {
237    return null;
238  }
239};
240
241/** The last PR URL in `gh pr create` output, which prints it on success. */
242const parsePrUrl = (text: string | undefined): { repo: string; pr: number } | null => {
243  const matches = [...(text ?? "").matchAll(PR_URL)];
244  const [, repo, pr] = matches.at(-1) ?? [];
245  return repo && pr ? { repo, pr: Number(pr) } : null;
246};
247
248// The uploads.sh accent (#c27eff) mixed half and half with the site's muted
249// text (#b3b3ad): a faded purple that marks the row without shouting.
250const BRAND = "#bb98d6";
251// An unpaired before or after: a missing half the reader should notice.
252const WARN = "#e5b567";
253
254const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
255const toBase64 = (bytes: Uint8Array): string => {
256  let out = "";
257  for (let i = 0; i < bytes.length; i += 3) {
258    const n = ((bytes[i] ?? 0) << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);
259    out += BASE64[(n >> 18) & 63]! + BASE64[(n >> 12) & 63]!;
260    out += i + 1 < bytes.length ? BASE64[(n >> 6) & 63]! : "=";
261    out += i + 2 < bytes.length ? BASE64[n & 63]! : "=";
262  }
263  return out;
264};
265
266// The favicon's mark: three stacked pixel chevrons fading downward, drawn as
267// 16×16 RGBA from favicon.svg's 32-unit grid (one pixel per two units).
268const MARK = (() => {
269  const size = 16;
270  const pixels = new Uint8Array(size * size * 4);
271  const blocks = [
272    [7, 2],
273    [5, 3],
274    [9, 3],
275    [3, 4],
276    [11, 4],
277  ] as const;
278  const rows = [
279    [0, 255],
280    [4, 140],
281    [8, 71],
282  ] as const;
283  for (const [dy, alpha] of rows) {
284    for (const [x, y] of blocks) {
285      for (const [i, j] of [
286        [0, 0],
287        [1, 0],
288        [0, 1],
289        [1, 1],
290      ] as const) {
291        pixels.set([0xbb, 0x98, 0xd6, alpha], ((y + dy + j) * size + x + i) * 4);
292      }
293    }
294  }
295  return { rgba: toBase64(pixels), width: size, height: size };
296})();
297
298const attachments = (n: number) => (n === 1 ? "1 attachment" : `${n} attachments`);
299
300/** How many staged files are held for review. */
301const heldIn = (rows: readonly BandRow[] | undefined): number =>
302  (Array.isArray(rows) ? rows : []).flatMap(filesOf).filter((f) => f.held).length;
303
304type Line = { text: string; warn: boolean };
305
306/** What the staged attachments are waiting for, by the repo's link to a workspace. */
307const headline = (view: Staged): Line => {
308  const line = waitingFor(view);
309  const held = heldIn(view.rows);
310  return held > 0 ? { text: `${line.text} · ${held} held for review`, warn: true } : line;
311};
312
313const waitingFor = (view: Staged): Line => {
314  const n = attachments(view.count);
315  if (view.binding === "other") {
316    return { text: `${n} won't attach: repo linked to another workspace`, warn: true };
317  }
318  if (view.binding === "none") {
319    return { text: `${n} waiting for a PR · link the repo to auto-attach`, warn: false };
320  }
321  return { text: `${n} waiting for a PR`, warn: false };
322};
323
324/** The band's one line for the session branch, or null to show nothing. */
325const bandLine = (view: Staged, done: Attached | null): Line | null => {
326  if (view.count > 0) {
327    return headline(view);
328  }
329  if (done?.branch !== view.branch || done.repo !== view.repo) {
330    return null;
331  }
332  const n = attachments(done.count);
333  return {
334    text:
335      done.via === "app"
336        ? `${n} sent to PR #${done.pr} via the uploads-sh bot`
337        : `${n} added to PR #${done.pr}`,
338    warn: false,
339  };
340};
341
342// ---- desktop thumbnails and the pane ------------------------------------------
343
344const STORAGE = "https://storage.uploads.sh/";
345
346/** The workspace page for the staged files, read off their storage URLs; null off uploads.sh storage. */
347const workspacePage = (rows: readonly BandRow[]): string | null => {
348  for (const row of rows) {
349    for (const f of filesOf(row)) {
350      const ws = f.src?.startsWith(STORAGE) ? f.src.slice(STORAGE.length).split("/")[0] : "";
351      if (ws) return `https://uploads.sh/account/workspaces/${encodeURIComponent(ws)}`;
352    }
353  }
354  return null;
355};
356
357/** The files in a row, before first. */
358const filesOf = (row: BandRow): FileRef[] =>
359  row.kind === "file" ? [row.file] : [row.before, row.after].filter((f): f is FileRef => !!f);
360
361/** Identifies a staged set: the desktop band hides for it and returns when it changes. */
362const setKey = (view: Staged): string =>
363  `${view.repo}#${view.branch}#${(Array.isArray(view.rows) ? view.rows : [])
364    .flatMap((row) => filesOf(row).map((f) => f.key))
365    .join(",")}`;
366
367// A resized JPEG of a storage image, through Cloudflare's image transform.
368const transformed = (src: string, width: number, quality: number): string =>
369  src.startsWith(STORAGE) && !src.toLowerCase().endsWith(".svg")
370    ? `${STORAGE}cdn-cgi/image/width=${width},fit=scale-down,format=jpeg,quality=${quality}/${src.slice(STORAGE.length)}`
371    : src;
372
373const embedUrl = (src: string): string =>
374  src.startsWith(STORAGE) ? `https://embed.uploads.sh/${src.slice(STORAGE.length)}` : src;
375
376// A JPEG of `src` as a data URI: the desktop draws Svg as an isolated image, so
377// it can't load a remote URL. Null when the fetch fails or the result is too big.
378async function fetchUri(
379  $: EngineInterface,
380  src: string,
381  width: number,
382  quality: number,
383): Promise<string | null> {
384  const b64 = await run(
385    $,
386    ["sh", "-c", 'curl -sfL --max-time 15 "$1" | base64', "sh", transformed(src, width, quality)],
387    20_000,
388  );
389  const body = b64?.replace(/\s+/g, "") ?? "";
390  return body && body.length <= 120_000 ? `data:image/jpeg;base64,${body}` : null;
391}
392
393// A held file's bytes are private, so there is no thumbnail to fetch.
394const imageFiles = (rows: readonly BandRow[]): FileRef[] =>
395  rows.flatMap(filesOf).filter((f) => !!f.src && !f.held && IMAGE_EXT.test(f.name));
396
397// Fetches thumbnails not yet cached; a failure is remembered as "" (drawn as a file card).
398async function loadThumbs($: EngineInterface, rows: readonly BandRow[]): Promise<void> {
399  for (const file of imageFiles(rows)) {
400    if (file.src! in (await read($, thumbs))) {
401      continue;
402    }
403    const uri = await fetchUri($, file.src!, 360, 70);
404    await update($, thumbs, (t) => ({ ...t, [file.src!]: uri ?? "" }));
405  }
406}
407
408async function loadLarge($: EngineInterface, row: BandRow): Promise<void> {
409  for (const file of imageFiles([row])) {
410    if (file.src! in (await read($, large))) {
411      continue;
412    }
413    const uri = (await fetchUri($, file.src!, 1100, 72)) ?? (await fetchUri($, file.src!, 760, 60));
414    if (uri) {
415      await update($, large, (t) => ({ ...t, [file.src!]: uri }));
416    }
417  }
418}
419
420const esc = (s: string): string =>
421  s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
422
423// The mark as vector art, for the desktop band: the same chevrons as MARK.
424const MARK_SVG = (() => {
425  const blocks = [
426    [7, 2],
427    [5, 3],
428    [9, 3],
429    [3, 4],
430    [11, 4],
431  ] as const;
432  const rows = [
433    [0, 1],
434    [4, 0.55],
435    [8, 0.28],
436  ] as const;
437  const rects = rows
438    .flatMap(([dy, a]) =>
439      blocks.map(
440        ([x, y]) =>
441          `<rect x="${x}" y="${y + dy}" width="2" height="2" fill="${BRAND}" fill-opacity="${a}"/>`,
442      ),
443    )
444    .join("");
445  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16">${rects}</svg>`;
446})();
447
448// `uri`: a data URI to draw; null while loading; "" when there is no inline
449// preview (not an image, or the thumbnail failed), drawn as a file card.
450// `held` draws the held card in place of any preview.
451type Slot = { uri: string | null; chip: string | null; ext: string; held?: boolean };
452
453const extOf = (name: string): string => {
454  const dot = name.lastIndexOf(".");
455  return dot > 0
456    ? name
457        .slice(dot + 1)
458        .toUpperCase()
459        .slice(0, 5)
460    : "FILE";
461};
462
463// A file card: a page glyph with a folded corner and the extension under it.
464const fileCard = (x: number, w: number, height: number, ext: string, path: string): string => {
465  const g = Math.min(height * 0.34, w * 0.3);
466  const gx = x + w / 2 - g * 0.4;
467  const gy = height / 2 - g * 0.75;
468  const f = g * 0.28;
469  const small = height < 40;
470  const glyph = small
471    ? ""
472    : `<path d="M${gx},${gy} h${g * 0.8 - f} l${f},${f} v${g - f} h${-g * 0.8} Z M${gx + g * 0.8 - f},${gy} v${f} h${f}" fill="none" stroke="#8889" stroke-width="1.5" stroke-linejoin="round"/>`;
473  const label = `<text x="${x + w / 2}" y="${small ? height / 2 + 3.5 : gy + g + 18}" text-anchor="middle" font-size="${small ? 9 : 12}" font-weight="600" letter-spacing="0.5" font-family="system-ui,-apple-system,sans-serif" fill="#888">${esc(ext)}</text>`;
474  return `<path d="${path}" fill="#8881"/>${glyph}${label}`;
475};
476
477// A held file: a padlock in the warning colour, with HELD under it.
478const heldCard = (x: number, w: number, height: number, path: string): string => {
479  const small = height < 40;
480  const s = small ? height * 0.42 : Math.min(height * 0.3, w * 0.25);
481  const cx = x + w / 2;
482  const top = small ? height / 2 - s / 2 : height / 2 - s * 0.9;
483  const bodyY = top + s * 0.42;
484  const lock =
485    `<path d="M${cx - s * 0.26},${bodyY} v${-s * 0.14} a${s * 0.26},${s * 0.26} 0 0 1 ${s * 0.52},0 v${s * 0.14}" fill="none" stroke="${WARN}" stroke-width="${small ? 1.2 : 1.8}"/>` +
486    `<rect x="${cx - s * 0.4}" y="${bodyY}" width="${s * 0.8}" height="${s * 0.58}" rx="${s * 0.1}" fill="${WARN}"/>`;
487  const label = small
488    ? ""
489    : `<text x="${cx}" y="${bodyY + s * 0.58 + 18}" text-anchor="middle" font-size="12" font-weight="600" letter-spacing="0.5" font-family="system-ui,-apple-system,sans-serif" fill="${WARN}">HELD</text>`;
490  return `<path d="${path}" fill="${WARN}1a"/>${lock}${label}`;
491};
492
493// Images side by side with a hairline gap, each clipped to a rounded frame, so a
494// pair reads as one card. A chip names each half when `chips` is set.
495const tileSvg = (slots: readonly Slot[], w: number, height: number, chips: boolean): string => {
496  const gap = 2;
497  const total = slots.length * w + (slots.length - 1) * gap;
498  const r = height > 40 ? 6 : 3;
499  const body = slots
500    .map((s, i) => {
501      const x = i * (w + gap);
502      const left = i === 0;
503      const right = i === slots.length - 1;
504      // Outer corners rounded, inner edges square.
505      const path =
506        `M${x + (left ? r : 0)},0 H${x + w - (right ? r : 0)} ` +
507        (right
508          ? `A${r},${r} 0 0 1 ${x + w},${r} V${height - r} A${r},${r} 0 0 1 ${x + w - r},${height} `
509          : `V${height} `) +
510        `H${x + (left ? r : 0)} ` +
511        (left ? `A${r},${r} 0 0 1 ${x},${height - r} V${r} A${r},${r} 0 0 1 ${x + r},0 Z` : `V0 Z`);
512      const img = s.held
513        ? heldCard(x, w, height, path)
514        : s.uri === ""
515          ? fileCard(x, w, height, s.ext, path)
516          : s.uri
517            ? `<image href="${esc(s.uri)}" x="${x}" y="0" width="${w}" height="${height}" preserveAspectRatio="xMidYMin slice" clip-path="url(#k${i})"/>`
518            : `<path d="${path}" fill="#8882"/>`;
519      const chip =
520        chips && s.chip
521          ? `<rect x="${x + 6}" y="${height - 22}" width="${s.chip.length * 6.4 + 12}" height="16" rx="8" fill="#000b"/>` +
522            `<text x="${x + 12}" y="${height - 10.5}" font-size="10" font-family="system-ui,-apple-system,sans-serif" font-weight="600" fill="#fff">${s.chip}</text>`
523          : "";
524      return `<clipPath id="k${i}"><path d="${path}"/></clipPath>${img}<path d="${path}" fill="none" stroke="#8884"/>${chip}`;
525    })
526    .join("");
527  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${total} ${height}" width="${total}" height="${height}">${body}</svg>`;
528};
529
530const roleName = (row: BandRow, file: FileRef): "Before" | "After" | null =>
531  row.kind === "pair" ? (file === row.before ? "Before" : "After") : null;
532
533const slotsOf = (row: BandRow, t: Record<string, string>): Slot[] =>
534  filesOf(row).map((f) => ({
535    uri: f.held || !f.src || !IMAGE_EXT.test(f.name) ? "" : (t[f.src] ?? null),
536    chip: roleName(row, f),
537    ext: extOf(f.name),
538    held: f.held,
539  }));
540
541const labelOf = (row: BandRow): string => (row.kind === "file" ? row.file.name : row.label);
542
543// Shortens the middle of a name to `max` characters, keeping the extension end.
544const fit = (name: string, max: number): string => {
545  if (name.length <= max) {
546    return name;
547  }
548  const tail = Math.min(8, Math.floor((max - 1) / 2));
549  return `${name.slice(0, max - 1 - tail)}…${name.slice(name.length - tail)}`;
550};
551// Characters that fit beside the staged time under a tile of this many images.
552const captionRoom = (row: BandRow): number => (filesOf(row).length > 1 ? 40 : 17);
553
554// When the row's newest file was staged, as "5m ago".
555const agoOf = (row: BandRow, now: number): string => {
556  const times = filesOf(row)
557    .map((f) => (f.stagedAt ? Date.parse(f.stagedAt) : NaN))
558    .filter((n) => !Number.isNaN(n));
559  if (times.length === 0) {
560    return "";
561  }
562  const s = Math.max(0, Math.round((now - Math.max(...times)) / 1000));
563  if (s < 60) {
564    return "just now";
565  }
566  if (s < 3600) {
567    return `${Math.floor(s / 60)}m ago`;
568  }
569  return s < 86400 ? `${Math.floor(s / 3600)}h ago` : `${Math.floor(s / 86400)}d ago`;
570};
571
572const markdownOf = (rows: readonly BandRow[]): string =>
573  rows
574    .flatMap((row) =>
575      filesOf(row).map((f) => {
576        const role = roleName(row, f);
577        const alt = role ? `${labelOf(row)} (${role.toLowerCase()})` : labelOf(row);
578        return f.src ? `![${alt}](${embedUrl(f.src)})` : "";
579      }),
580    )
581    .filter(Boolean)
582    .join("\n");
583
584const BAND_TILES = 4;
585const TILE_W = 168;
586const TILE_H = 105;
587
588async function openPane($: EngineInterface, title = PANE_TITLE): Promise<void> {
589  await $.ui.open({ id: PANE, title });
590}
591
592// Shows the pane's grid, fetching the thumbnails it will draw.
593async function showGrid($: EngineInterface): Promise<void> {
594  await update($, preview, () => null);
595  await openPane($);
596  const view = await read($, staged);
597  if (view && Array.isArray(view.rows)) {
598    void loadThumbs($, view.rows).catch(() => undefined);
599  }
600}
601
602// The pane swaps its grid for one row, large; "All attachments" returns to the grid.
603async function showRow($: EngineInterface, row: BandRow): Promise<void> {
604  await update($, preview, () => row);
605  await openPane($, labelOf(row));
606  void loadLarge($, row).catch(() => undefined);
607}
608
609async function removeRow($: EngineInterface, row: BandRow): Promise<void> {
610  for (const file of filesOf(row)) {
611    await run($, ["uploads", "delete", file.key], 30_000);
612  }
613  await refreshBand($);
614}
615
616// Approves the row's held files, then redraws the pane with them released.
617async function approveRow($: EngineInterface, row: BandRow): Promise<void> {
618  const keys = filesOf(row)
619    .filter((f) => f.held)
620    .map((f) => f.key);
621  const ok = (await run($, ["uploads", "approve", ...keys], 30_000)) !== null;
622  $.ui.toast(ok ? `Approved ${labelOf(row)}` : `Couldn't approve ${labelOf(row)}`);
623  await refreshBand($);
624  const view = await read($, staged);
625  const fresh = view?.rows.find((r) => labelOf(r) === labelOf(row));
626  if (fresh) {
627    await update($, preview, () => fresh);
628  }
629}
630
631async function copyText(
632  $: EngineInterface,
633  surface: Parameters<EngineInterface["ui"]["copy"]>[0]["surface"],
634  text: string,
635  what: string,
636): Promise<void> {
637  await $.ui.copy({ text, surface });
638  $.ui.toast(`Copied ${what}`);
639}
640
641// The PR's live feed link: created on first use through the CLI, then kept.
642async function copyFeedLink(
643  $: EngineInterface,
644  surface: Parameters<EngineInterface["ui"]["copy"]>[0]["surface"],
645  view: Staged,
646  pr: { number: number },
647): Promise<void> {
648  let url = await read($, feedUrl);
649  if (!url) {
650    const out = await run(
651      $,
652      ["uploads", "feed", "create", "--repo", view.repo, "--pr", String(pr.number)],
653      30_000,
654    );
655    url = out?.trim().split("\n")[0] || null;
656    if (!url) {
657      $.ui.toast("Couldn't get the PR feed link");
658      return;
659    }
660    await update($, feedUrl, () => url);
661  }
662  await copyText($, surface, url, "the PR feed link");
663}
664
665let lastRefresh = 0;
666
667// Runs a command; null when it can't start, times out, or exits non-zero.
668async function run(
669  $: EngineInterface,
670  argv: readonly string[],
671  timeoutMs: number,
672): Promise<string | null> {
673  try {
674    const ran = await $.process.run(argv, { timeoutMs });
675    return ran.exitCode === 0 ? ran.stdout : null;
676  } catch {
677    return null;
678  }
679}
680
681// Reads staged files through the CLI; a missing CLI, a directory outside a
682// git repo, or a signed-out CLI all read as null. With no `scope` the CLI
683// resolves the session directory's branch and repo.
684async function fetchStaged(
685  $: EngineInterface,
686  scope: { branch: string; repo: string } | null,
687): Promise<Staged | null> {
688  const argv = ["uploads", "staged", "--format", "json"];
689  if (scope) {
690    argv.push("--branch", scope.branch, "--repo", scope.repo);
691  }
692  const stdout = await run($, argv, 15_000);
693  return stdout === null ? null : parseStaged(stdout);
694}
695
696// The open PR for the session directory's branch, for the pane's feed link.
697async function fetchOpenPr($: EngineInterface): Promise<{ number: number; url: string } | null> {
698  const stdout = await run($, ["gh", "pr", "view", "--json", "number,url,state"], 15_000);
699  try {
700    const doc = JSON.parse(stdout ?? "");
701    return typeof doc?.number === "number" && doc.state === "OPEN"
702      ? { number: doc.number, url: String(doc.url) }
703      : null;
704  } catch {
705    return null;
706  }
707}
708
709// The first row with a file held since the last look at the same branch, so
710// the pane opens on its Approve. The first look of a session opens nothing.
711const newHold = (before: Staged | null, view: Staged | null): BandRow | null => {
712  if (!before || !view || before.repo !== view.repo || before.branch !== view.branch) {
713    return null;
714  }
715  const wasHeld = new Set(
716    (Array.isArray(before.rows) ? before.rows : [])
717      .flatMap(filesOf)
718      .filter((f) => f.held)
719      .map((f) => f.key),
720  );
721  return view.rows.find((row) => filesOf(row).some((f) => f.held && !wasHeld.has(f.key))) ?? null;
722};
723
724// Refreshes what the band shows: the session directory's branch.
725async function refreshBand($: EngineInterface): Promise<void> {
726  const before = await read($, staged);
727  const view = await fetchStaged($, null);
728  await update($, staged, () => view);
729  const newlyHeld = newHold(before, view);
730  if (newlyHeld) {
731    await showRow($, newlyHeld);
732  }
733  const pr = view && view.count > 0 ? await fetchOpenPr($) : null;
734  if ((await read($, openPr))?.number !== pr?.number) {
735    await update($, feedUrl, () => null);
736  }
737  await update($, openPr, () => pr);
738  if (view) {
739    await loadThumbs($, view.rows.slice(0, BAND_TILES));
740  }
741}
742
743// Schedules a band refresh outside the current dispatch, so no tool result waits on it.
744async function kick($: EngineInterface, ms = 0): Promise<void> {
745  lastRefresh = await $.clock.now();
746  $.clock.after(ms, () => void refreshBand($).catch(() => undefined));
747}
748
749// The PR's head branch. The Bash call may have run in another directory
750// (a `cd`, or a subagent's worktree), so the session's branch can't stand in.
751async function prHead($: EngineInterface, repo: string, pr: number): Promise<string | null> {
752  const argv = [
753    "gh",
754    "pr",
755    "view",
756    String(pr),
757    "--repo",
758    repo,
759    "--json",
760    "headRefName",
761    "-q",
762    ".headRefName",
763  ];
764  const head = (await run($, argv, 15_000))?.trim();
765  return head ? head : null;
766}
767
768type Outcome = {
769  toast: string;
770  context?: string;
771  record?: Omit<Attached, "pr" | "repo" | "branch">;
772};
773
774export const register: Register = (on, options) => {
775  const autoPromote = options.autoPromote !== false;
776
777  on("session.start", async ($, e, next) => {
778    await $.command.register({
779      name: "uploads-staged",
780      description: "Show the attachments staged on uploads.sh for this branch",
781    });
782    await kick($);
783    return next(e);
784  });
785
786  on("command.run", { command: "uploads-staged" }, async ($) => {
787    await refreshBand($);
788    await showGrid($);
789    return { text: "Opened the staged attachments pane." };
790  });
791
792  on("turn.complete", async ($, e, next) => {
793    if ((await $.clock.now()) - lastRefresh > IDLE_REFRESH_MS) {
794      await kick($);
795    }
796    return next(e);
797  });
798
799  on("tool.call", { tool: "Bash" }, async ($, e, next) => {
800    const ran = await next(e);
801    if (!REFRESH_AFTER.test(e.command)) {
802      return ran;
803    }
804    if (!PR_CREATE.test(e.command) || ran.deny !== undefined || ran.isError === true) {
805      await kick($);
806      return ran;
807    }
808
809    const target = parsePrUrl(ran.text);
810    await kick($, AFTER_PR_REFRESH_MS);
811    if (!target) {
812      return ran;
813    }
814    const head = await prHead($, target.repo, target.pr);
815    if (!head) {
816      return ran;
817    }
818
819    // What the band last saw for this branch, before the GitHub App could act.
820    const before = await read($, staged);
821    const prior = before?.repo === target.repo && before.branch === head ? before.count : 0;
822    const view = await fetchStaged($, { branch: head, repo: target.repo });
823    if (!view) {
824      return ran;
825    }
826
827    const pr = `PR #${target.pr}`;
828    const promoteArgv = [
829      "uploads",
830      "attach",
831      "--promote",
832      "--pr",
833      String(target.pr),
834      "--repo",
835      target.repo,
836      "--from-branch",
837      head,
838    ];
839    const command = promoteArgv.join(" ");
840    const files = attachments(view.count);
841
842    let outcome: Outcome | null = null;
843    if (view.count === 0) {
844      // The App's webhook already promoted them between the PR opening and this read.
845      if (prior > 0 && view.autoAttach) {
846        outcome = {
847          toast: `uploads: ${attachments(prior)} added to ${pr} by the uploads-sh bot`,
848          context: `uploads: the GitHub App added the ${attachments(prior)} for ${head} to ${pr}. Don't re-upload them.`,
849          record: { count: prior, via: "app" },
850        };
851      } else if (view.foreignBranches.length > 0) {
852        const cmds = view.foreignBranches
853          .map((name) => `uploads unstage --branch ${name}`)
854          .join("; ");
855        outcome = {
856          toast: `uploads: nothing on ${head} for ${pr}; run ${cmds}`,
857          context: `uploads: ${view.foreignBranches.join(", ")} still has staged files, and they are not on ${head}. If they are stale or on the wrong branch, run \`${cmds}\`.`,
858        };
859      }
860    } else if (viewIsStale(view, await $.clock.now())) {
861      const cmd = `uploads unstage --branch ${head}`;
862      const verb = view.count === 1 ? "looks" : "look";
863      outcome = {
864        toast: `uploads: ${files} for ${head} ${verb} stale; run ${cmd}`,
865        context: `uploads: ${files} for ${head} ${view.count === 1 ? "was" : "were"} staged more than 30 days ago. If ${view.count === 1 ? "it is" : "they are"} not for ${pr}, run \`${cmd}\`.`,
866      };
867    } else if (view.binding === "other") {
868      outcome = {
869        toast: `uploads: ${files} won't attach to ${pr}: this repo is linked to another workspace`,
870      };
871    } else if (view.autoAttach) {
872      outcome = {
873        toast: `uploads: ${files} will attach to ${pr} via the uploads-sh bot`,
874        context: `uploads: the GitHub App attaches the ${files} for ${head} to ${pr}. Don't re-upload them.`,
875        record: { count: view.count, via: "app" },
876      };
877    } else if (!autoPromote) {
878      outcome = {
879        toast: `uploads: ${files} waiting for ${pr}; run ${command}`,
880        context: `uploads: ${files} for ${head} are staged but not attached to ${pr}. To attach them, run \`${command}\`.`,
881      };
882    } else {
883      // The command exits 0 even when the server call failed, so trust only
884      // the `promotion` it reports: what moved, and what it skipped.
885      const result = parsePromotion(await run($, [...promoteArgv, "--json"], 60_000));
886      if (result === null || result.promoted === 0) {
887        outcome = {
888          toast: `uploads: couldn't add ${files} to ${pr}; run uploads attach --promote`,
889          context: `uploads: ${files} for ${head} did not attach to ${pr}. Run \`${command}\`.`,
890        };
891      } else if (result.skipped > 0) {
892        const moved = attachments(result.promoted);
893        outcome = {
894          toast: `uploads: added ${moved} to ${pr}; ${result.skipped} skipped`,
895          context: `uploads: added ${moved} for ${head} to ${pr}; ${result.skipped} ${result.skipped === 1 ? "was" : "were"} skipped. Run \`${command}\` to retry them.`,
896          record: { count: result.promoted, via: "cli" },
897        };
898      } else if (result.held > 0) {
899        const held = `${result.held} ${result.held === 1 ? "is" : "are"} held for review`;
900        outcome = {
901          toast: `uploads: added ${attachments(result.promoted)} to ${pr}; ${held}`,
902          context: `uploads: added ${attachments(result.promoted)} for ${head} to ${pr}'s attachments comment, and ${held}: uploads.sh thinks ${result.held === 1 ? "it shows" : "they show"} a secret or personal data. Don't re-upload. Ask the user to check; \`uploads approve --pr ${target.pr}\` lists them, and \`--all\` approves. If one shows a real credential, it should be rotated and the file deleted instead.`,
903          record: { count: result.promoted, via: "cli" },
904        };
905      } else {
906        outcome = {
907          toast: `uploads: added ${attachments(result.promoted)} to ${pr}`,
908          context: `uploads: added ${attachments(result.promoted)} for ${head} to ${pr}'s attachments comment. Don't re-upload them.`,
909          record: { count: result.promoted, via: "cli" },
910        };
911        // Nothing is left staged for the head; the scheduled refresh confirms it.
912        await update($, staged, (s) =>
913          s?.repo === target.repo && s.branch === head ? { ...s, count: 0, rows: [] } : s,
914        );
915      }
916    }
917    if (outcome === null) {
918      return ran;
919    }
920
921    $.ui.toast(outcome.toast);
922    const { record } = outcome;
923    if (record) {
924      await update(
925        $,
926        attached,
927        (): Attached => ({ ...record, repo: target.repo, branch: head, pr: target.pr }),
928      );
929    }
930    return outcome.context ? { ...ran, context: [...(ran.context ?? []), outcome.context] } : ran;
931  });
932
933  on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
934    const view = await read($, staged);
935    if (e.props.hasSurvey || view === null) {
936      return next(e);
937    }
938    const line = bandLine(view, await read($, attached));
939    if (line === null) {
940      return next(e);
941    }
942    // State saved by an older version of this module has no `rows`.
943    const rows = Array.isArray(view.rows) ? view.rows : [];
944
945    if (e.surface === "desktop") {
946      const { Box, Button, Svg, Text } = $.ui.resolve(e);
947      // Hidden until the staged set changes.
948      if (view.count > 0 && (await read($, dismissed)) === setKey(view)) {
949        return next(e);
950      }
951      const t = await read($, thumbs);
952      return (
953        <Box flexDirection="row" alignItems="center" justifyContent="space-between" gap={1}>
954          <Box flexDirection="row" alignItems="center" gap={1}>
955            <Svg source={MARK_SVG} alt="uploads" width={14} height={14} />
956            <Text color={BRAND} bold>
957              uploads
958            </Text>
959            <Text color={line.warn ? WARN : undefined} dimColor={!line.warn}>
960              {line.text}
961            </Text>
962          </Box>
963          {view.count > 0 && (
964            <Box flexDirection="row" alignItems="center" gap={1}>
965              {rows.slice(0, BAND_TILES).map((row, i) => (
966                <Svg
967                  key={`tile-${i}`}
968                  source={tileSvg(slotsOf(row, t), 40, 25, false)}
969                  alt={labelOf(row)}
970                  height={25}
971                />
972              ))}
973              {rows.length > BAND_TILES && <Text dimColor>+{rows.length - BAND_TILES}</Text>}
974              <Button key="view" label="View" plain dimColor onPress={() => void showGrid($)} />
975              <Button
976                key="hide"
977                label="Hide"
978                role="dismiss"
979                onPress={() => void update($, dismissed, () => setKey(view))}
980              />
981            </Box>
982          )}
983        </Box>
984      );
985    }
986
987    const els = $.ui.resolve(e);
988    const { Box, Button, Link, Text } = els;
989    const Image = "Image" in els ? els.Image : null;
990    const canExpand = rows.length > 0;
991    const expanded = canExpand && (await read($, isExpanded));
992    // The header row takes one line, and a "+N more" row may take another.
993    const shown = expanded
994      ? rows.slice(0, Math.min(MAX_ROWS, Math.max(1, e.props.maxRows - 2)))
995      : [];
996    const more = view.count - shown.reduce((sum, row) => sum + filesIn(row), 0);
997
998    // A file as a link named by `label`, or plain text when the CLI gave no URL.
999    const fileLink = (file: FileRef, label: string) =>
1000      file.url ? <Link href={file.url} label={label} /> : <Text>{label}</Text>;
1001    // One side of a pair: a link to that file, or an amber dash where it's missing.
1002    const half = (file: FileRef | null, role: "before" | "after") =>
1003      file ? fileLink(file, role) : <Text color={WARN}>—</Text>;
1004
1005    // The engine's own `[-]` at the row's end collapses the band, so it needs no hide control.
1006    return (
1007      <Box flexDirection="column">
1008        <Box>
1009          {Image ? (
1010            <Image key="mark" source={MARK} columns={2} rows={1} alt="⇡" />
1011          ) : (
1012            <Text color={BRAND}>⇡</Text>
1013          )}
1014          <Text color={BRAND} bold>
1015            {" uploads "}
1016          </Text>
1017          {canExpand && (
1018            <Button
1019              key="files"
1020              plain
1021              label={expanded ? "▾" : "▸"}
1022              onPress={() => update($, isExpanded, (open) => !open)}
1023            />
1024          )}
1025          <Text color={line.warn ? WARN : undefined} dimColor={!line.warn}>
1026            {" "}
1027            {line.text}
1028          </Text>
1029        </Box>
1030        {shown.map((row, i) =>
1031          row.kind === "file" ? (
1032            <Box key={`file-${i}`}>
1033              <Text dimColor>{"  · "}</Text>
1034              {fileLink(row.file, row.file.name)}
1035              <Text dimColor> {formatSize(row.file.size)}</Text>
1036              {row.file.held && <Text color={WARN}> held for review</Text>}
1037            </Box>
1038          ) : (
1039            <Box key={`pair-${i}`}>
1040              <Text dimColor>{"  · "}</Text>
1041              <Text>{row.label} </Text>
1042              {half(row.before, "before")}
1043              <Text dimColor>{" → "}</Text>
1044              {half(row.after, "after")}
1045              {/* A lone half's size; a full pair needs none. */}
1046              {(row.before === null) !== (row.after === null) && (
1047                <Text dimColor> {formatSize((row.before ?? row.after)!.size)}</Text>
1048              )}
1049            </Box>
1050          ),
1051        )}
1052        {expanded && more > 0 && <Text dimColor>{`  + ${more} more (uploads staged)`}</Text>}
1053      </Box>
1054    );
1055  });
1056
1057  on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
1058    const els = $.ui.resolve(e);
1059    const { Box, Button, Link, Text } = els;
1060    const Svg = "Svg" in els ? els.Svg : null;
1061    const desktop = e.surface === "desktop" && Svg !== null;
1062    const chosen = await read($, preview);
1063
1064    // One row, large, in the same pane as the grid.
1065    if (chosen) {
1066      const big = await read($, large);
1067      const small = await read($, thumbs);
1068      return (
1069        <Box flexDirection="column" gap={1}>
1070          <Box flexDirection="row" alignItems="center" justifyContent="space-between" gap={1}>
1071            <Button
1072              key="back"
1073              label="← All attachments"
1074              plain
1075              dimColor
1076              onPress={() => void showGrid($)}
1077            />
1078            <Box flexDirection="row" alignItems="center" gap={1}>
1079              {filesOf(chosen).some((f) => f.held) && (
1080                <Button
1081                  key="approve"
1082                  label="Approve"
1083                  variant="primary"
1084                  onPress={() => void approveRow($, chosen)}
1085                />
1086              )}
1087              <Button
1088                key="copy-row"
1089                label="Copy markdown"
1090                onPress={(p) => void copyText($, p.surface, markdownOf([chosen]), "markdown")}
1091              />
1092              <Button
1093                key="remove"
1094                label="Remove"
1095                onPress={async () => {
1096                  await removeRow($, chosen);
1097                  await showGrid($);
1098                }}
1099              />
1100            </Box>
1101          </Box>
1102          <Text bold>{labelOf(chosen)}</Text>
1103          {filesOf(chosen).map((f) => {
1104            if (f.held) {
1105              return (
1106                <Box key={f.key} flexDirection="column" gap={1}>
1107                  {desktop && (
1108                    <Svg
1109                      source={tileSvg(
1110                        [{ uri: "", chip: null, ext: extOf(f.name), held: true }],
1111                        480,
1112                        200,
1113                        false,
1114                      )}
1115                      alt={`${f.name}, held for review`}
1116                    />
1117                  )}
1118                  <Text color={WARN}>
1119                    {f.name} is held for review: uploads.sh thinks it shows a secret or personal
1120                    data.
1121                  </Text>
1122                  <Box flexDirection="row" alignItems="center" gap={1}>
1123                    <Text dimColor>
1124                      Check it before you approve. If it shows a real credential, rotate it and
1125                      remove the file.
1126                    </Text>
1127                    {f.url ? <Link href={f.url} label="Review on uploads.sh" /> : null}
1128                  </Box>
1129                </Box>
1130              );
1131            }
1132            const link = f.url ? <Link href={f.url} label="Open on uploads.sh" /> : null;
1133            const previewable = !!f.src && IMAGE_EXT.test(f.name) && small[f.src] !== "";
1134            if (!previewable) {
1135              return (
1136                <Box key={f.key} flexDirection="column" gap={1}>
1137                  {desktop && (
1138                    <Svg
1139                      source={tileSvg(
1140                        [{ uri: "", chip: null, ext: extOf(f.name) }],
1141                        480,
1142                        200,
1143                        false,
1144                      )}
1145                      alt={f.name}
1146                    />
1147                  )}
1148                  <Box flexDirection="row" alignItems="center" gap={1}>
1149                    <Text dimColor>{f.name} can't be previewed here.</Text>
1150                    {link}
1151                  </Box>
1152                </Box>
1153              );
1154            }
1155            const uri = big[f.src!] ?? small[f.src!] ?? null;
1156            const role = roleName(chosen, f);
1157            return (
1158              <Box key={f.key} flexDirection="column">
1159                <Box flexDirection="row" alignItems="center" gap={1}>
1160                  {role ? <Text bold>{role}</Text> : null}
1161                  {link}
1162                </Box>
1163                {desktop && (
1164                  <Svg
1165                    source={tileSvg([{ uri, chip: null, ext: extOf(f.name) }], 1000, 625, false)}
1166                    alt={f.name}
1167                  />
1168                )}
1169              </Box>
1170            );
1171          })}
1172        </Box>
1173      );
1174    }
1175
1176    const view = await read($, staged);
1177    const rows = view && Array.isArray(view.rows) ? view.rows : [];
1178    if (!view || view.count === 0) {
1179      return <Text dimColor>Nothing staged for this branch.</Text>;
1180    }
1181    const t = await read($, thumbs);
1182    const pr = await read($, openPr);
1183    const feed = await read($, feedUrl);
1184    const line = headline(view);
1185    const now = await $.clock.now();
1186
1187    return (
1188      <Box flexDirection="column" gap={1}>
1189        {/* Header: where these go, and the links worth sharing. */}
1190        <Box flexDirection="row" alignItems="center" gap={1}>
1191          <Box flexDirection="column" flexGrow={1}>
1192            <Text bold color={line.warn ? WARN : undefined}>
1193              {line.text}
1194            </Text>
1195            <Text dimColor>
1196              {view.repo} · {view.branch}
1197            </Text>
1198          </Box>
1199          {pr ? (
1200            <Button
types/index.d.ts 72 lines
1export type Binding = "self" | "none" | "other" | "unknown";
2
3/** One staged file as the expanded band links it. */
4export type FileRef = {
5  /** The full object key, what `uploads delete` takes. */
6  key: string;
7  name: string;
8  /** The uploads.sh file page, or null when the CLI gave no URL. */
9  url: string | null;
10  /** The storage URL, a thumbnail's source; null when the CLI gave no URL. */
11  src: string | null;
12  size: number | null;
13  /** ISO time the file was staged, when the CLI reported it. */
14  stagedAt: string | null;
15  /** Held for review: its bytes stay private until a member approves it. */
16  held: boolean;
17};
18
19/**
20 * One row of the expanded band: a before/after pair under its shared name
21 * (by the attachments comment's pairing rule; either half may be missing),
22 * or a file that is neither.
23 */
24export type BandRow =
25  | { kind: "pair"; label: string; before: FileRef | null; after: FileRef | null }
26  | { kind: "file"; file: FileRef };
27
28/** What `uploads staged --format json` reported for one branch. */
29export type Staged = {
30  repo: string;
31  branch: string;
32  count: number;
33  /** Every staged file's row; `count` is the number of files. */
34  rows: BandRow[];
35  binding: Binding;
36  autoAttach: boolean;
37  /** Branches named on files this view dropped. Empty when the CLI omitted them. */
38  foreignBranches: string[];
39};
40
41/** The last PR this session opened that had staged files waiting for it. */
42export type Attached = {
43  repo: string;
44  branch: string;
45  pr: number;
46  count: number;
47  via: "app" | "cli";
48};
49
50declare module "claude-code" {
51  interface PluginState {
52    uploads: {
53      staged: Staged | null;
54      attached: Attached | null;
55      /** Whether the band lists the staged files under its header. */
56      isExpanded: boolean;
57      /** Desktop: storage URL to a small JPEG data URI; "" when the fetch failed. */
58      thumbs: Record<string, string>;
59      /** Desktop: storage URL to a larger JPEG data URI for the pane's detail view. */
60      large: Record<string, string>;
61      /** The row the pane's detail view shows; null shows the grid. */
62      preview: BandRow | null;
63      /** The open PR for the session branch, if any. */
64      openPr: { number: number; url: string } | null;
65      /** The PR's live feed URL once created. */
66      feedUrl: string | null;
67      /** The staged set the desktop band is hidden for; a change shows it again. */
68      dismissed: string | null;
69    };
70  }
71}
72