ccdeck 3.47.0 → 3.48.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +28 -4
  2. package/bin/cli/commands.js +17 -9
  3. package/bin/cli/help.js +9 -4
  4. package/bin/cli/second-start.js +4 -2
  5. package/bin/cli/startup.js +3 -2
  6. package/bin/cli/tui.js +544 -0
  7. package/dist/web/assets/BrowserWatchModal-Dfsuy2cT.js +1 -0
  8. package/dist/web/assets/IntegrationModal-CcSR7YB-.js +7 -0
  9. package/dist/web/assets/{RadioPanel-DbmJJPsz.js → RadioPanel-s7WXdS6v.js} +1 -1
  10. package/dist/web/assets/{TrafficRadar-CPjAXd5e.js → TrafficRadar-C5GXMIwi.js} +1 -1
  11. package/dist/web/assets/UsageHistoryModal-CiExD9wF.js +1 -0
  12. package/dist/web/assets/app-BFaxhiED.js +321 -0
  13. package/dist/web/assets/app-DjlHxWHg.css +1 -0
  14. package/dist/web/assets/{index-Ca87aJP9.js → index-ByovgZ_7.js} +1 -1
  15. package/dist/web/index.html +3 -3
  16. package/package.json +1 -1
  17. package/release-notes.json +30 -3
  18. package/src/server/args.mjs +1 -0
  19. package/src/server/cli-lines.mjs +46 -0
  20. package/src/server/deck-prefs.mjs +23 -13
  21. package/src/server/gpu-metrics.mjs +78 -0
  22. package/src/server/integrations/jira-move.mjs +239 -0
  23. package/src/server/integrations/jira.mjs +30 -8
  24. package/src/server/integrations/proxy.mjs +3 -4
  25. package/src/server/integrations/routes.mjs +19 -5
  26. package/src/server/lan-deck.mjs +2 -1
  27. package/src/server/system-metrics.mjs +4 -0
  28. package/src/server/term.mjs +14 -5
  29. package/src/server/tui-screen.mjs +110 -0
  30. package/src/server/tui-view.mjs +1072 -0
  31. package/src/server/way-back.mjs +27 -0
  32. package/dist/web/assets/BrowserWatchModal-Bau0ttnH.js +0 -1
  33. package/dist/web/assets/IntegrationModal-8tTi25gA.js +0 -6
  34. package/dist/web/assets/UsageHistoryModal-qfmvXdWJ.js +0 -1
  35. package/dist/web/assets/app-BFFG6Wz8.js +0 -321
  36. package/dist/web/assets/app-DfcfHvcX.css +0 -1
@@ -1 +1 @@
1
- import"./app-BFFG6Wz8.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerPolicy&&(r.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?r.credentials="include":e.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(e){if(e.ep)return;e.ep=!0;const r=s(e);fetch(e.href,r)}})();
1
+ import"./app-BFaxhiED.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const e of document.querySelectorAll('link[rel="modulepreload"]'))i(e);new MutationObserver(e=>{for(const r of e)if(r.type==="childList")for(const o of r.addedNodes)o.tagName==="LINK"&&o.rel==="modulepreload"&&i(o)}).observe(document,{childList:!0,subtree:!0});function s(e){const r={};return e.integrity&&(r.integrity=e.integrity),e.referrerPolicy&&(r.referrerPolicy=e.referrerPolicy),e.crossOrigin==="use-credentials"?r.credentials="include":e.crossOrigin==="anonymous"?r.credentials="omit":r.credentials="same-origin",r}function i(e){if(e.ep)return;e.ep=!0;const r=s(e);fetch(e.href,r)}})();
@@ -77,9 +77,9 @@
77
77
  document.documentElement.setAttribute("data-density", density === "tightest" || density === "tighter" || density === "compact" || density === "comfortable" ? density : "default");
78
78
  })();
79
79
  </script>
80
- <script type="module" crossorigin src="/assets/index-Ca87aJP9.js"></script>
81
- <link rel="modulepreload" crossorigin href="/assets/app-BFFG6Wz8.js">
82
- <link rel="stylesheet" crossorigin href="/assets/app-DfcfHvcX.css">
80
+ <script type="module" crossorigin src="/assets/index-ByovgZ_7.js"></script>
81
+ <link rel="modulepreload" crossorigin href="/assets/app-BFaxhiED.js">
82
+ <link rel="stylesheet" crossorigin href="/assets/app-DjlHxWHg.css">
83
83
  </head>
84
84
  <body>
85
85
  <div id="root"></div>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ccdeck",
3
- "version": "3.47.0",
3
+ "version": "3.48.1",
4
4
  "description": "Local dashboard for Claude Code and Codex CLI sessions: which Claude Code session needs input, every tool call and Claude Code subagent live, token cost and quota, several Claude accounts. Run npx ccdeck.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -16,8 +16,8 @@
16
16
  "fire, anything that is invisible when it is correct.",
17
17
  "",
18
18
  "Write it for the person running the deck, not for the person reading the",
19
- "diff. `title` is the sentence they scan; `body` is what they need in order",
20
- "to act on it, or to stop worrying about it.",
19
+ "diff. `title` is the one line the deck shows them, so it has to stand on",
20
+ "its own; `body` is the fuller account, kept here for the release text.",
21
21
  "",
22
22
  "Keys are versions exactly as package.json spells them. A key that is not a",
23
23
  "version, or an entry missing either field, fails the suite rather than",
@@ -78,7 +78,34 @@
78
78
  "3.40.1",
79
79
  "3.41.3",
80
80
  "3.43.1",
81
- "3.43.3"
81
+ "3.43.3",
82
+ "3.48.1"
83
+ ],
84
+ "3.48.0": [
85
+ {
86
+ "title": "🗂️ Jira: move issues between sprints and the backlog",
87
+ "body": "On a Scrum board ordered by Rank, drag issues or use Move to reorder them or send them to another sprint or the backlog, one at a time or up to 50 together. Browsing still only reads."
88
+ },
89
+ {
90
+ "title": "🔎 The Jira list is easier to scan",
91
+ "body": "Titles keep more room, a row's preview no longer covers the next row, the issue key shows once in the detail, and Clear filters stays in reach on a phone."
92
+ },
93
+ {
94
+ "title": "⌨️ ccdeck tui keeps your Claude accounts on one screen over SSH",
95
+ "body": "Switch accounts, turn Auto-switch on or off, and sign an account in with a link you open in any browser, all from the terminal."
96
+ },
97
+ {
98
+ "title": "🎮 Machine shows NVIDIA GPU readings",
99
+ "body": "On Linux and Windows with nvidia-smi: each GPU's utilization, video memory, temperature and power."
100
+ },
101
+ {
102
+ "title": "👤 Claude accounts are quieter, and an expired login has a Sign in button",
103
+ "body": "Telemetry is a small shield explained on hover or focus, and an account whose login expired shows Sign in on its own row."
104
+ },
105
+ {
106
+ "title": "🩹 Fewer page errors from browser extensions and translation",
107
+ "body": "The Accounts panel recovers when an extension breaks its requests, and Local network keeps working while the browser translates the page."
108
+ }
82
109
  ],
83
110
  "3.47.0": [
84
111
  {
@@ -183,6 +183,7 @@ export const COMMANDS = Object.freeze({
183
183
  usage: "usage", quota: "usage",
184
184
  sessions: "sessions", ps: "sessions",
185
185
  open: "open",
186
+ tui: "tui",
186
187
  });
187
188
  const FLAG_WORDS = Object.freeze({
188
189
  status: "status", stop: "stop", logs: "logs", help: "help", version: "version",
@@ -77,6 +77,52 @@ const padStart = (s, n) => " ".repeat(Math.max(0, n - textWidth(s))) + s;
77
77
  export const clip = (s, n, ellipsis = "…") => (textWidth(s) <= n ? s
78
78
  : n <= textWidth(ellipsis) ? takeCells(s, n) : `${takeCells(s, n - textWidth(ellipsis))}${ellipsis}`);
79
79
 
80
+ /**
81
+ * A painted line cut to `n` columns, its colour codes kept and not counted.
82
+ * The full-screen view's last word on a row (`ccdeck tui`): every line is laid
83
+ * out to fit already, and this is what holds when one was not — a row one
84
+ * column too long wraps into the row under it, and the screen below it is
85
+ * then one row off from what the view drew. The `ellipsis` says a line was
86
+ * cut, inside the same `n`, and a line that had colour ends on a reset; one
87
+ * that had none gains none, so NO_COLOR stays free of escapes.
88
+ */
89
+ export function fitPainted(s, n, ellipsis = "") {
90
+ const text = String(s);
91
+ if (textWidth(text) <= n) return text;
92
+ const room = Math.max(0, n - textWidth(ellipsis));
93
+ let out = "";
94
+ let w = 0;
95
+ for (let i = 0; i < text.length;) {
96
+ const esc = /^\x1b\[[0-9;?]*[a-zA-Z]/.exec(text.slice(i, i + 32));
97
+ if (esc) { out += esc[0]; i += esc[0].length; continue; }
98
+ const ch = String.fromCodePoint(text.codePointAt(i));
99
+ const c = cellsOf(ch);
100
+ if (w + c > room) break;
101
+ out += ch;
102
+ w += c;
103
+ i += ch.length;
104
+ }
105
+ return `${out}${room < n ? ellipsis : ""}${text.includes("\x1b[") ? "\x1b[0m" : ""}`;
106
+ }
107
+
108
+ /**
109
+ * The columns `from` to `to` of a plain line, exactly that wide: a wide
110
+ * character cut in half becomes a space, and a short line is padded. What
111
+ * `ccdeck tui` lays a dialog over the screen with.
112
+ */
113
+ export function sliceCells(s, from, to) {
114
+ let out = "";
115
+ let at = 0;
116
+ for (const ch of String(s)) {
117
+ const c = cellsOf(ch);
118
+ if (at >= to) break;
119
+ if (at >= from && at + c <= to) out += ch;
120
+ else if (at + c > from) out += " ".repeat(Math.min(at + c, to) - Math.max(at, from));
121
+ at += c;
122
+ }
123
+ return out + " ".repeat(Math.max(0, to - Math.max(from, at)));
124
+ }
125
+
80
126
  /** What is wrong with an account, in words, or null when nothing is. */
81
127
  export function accountTrouble(a) {
82
128
  if (a.disabled) return { word: "disabled", tone: "muted" };
@@ -171,16 +171,18 @@ export const DEFAULTS = Object.freeze({
171
171
  // of one person's machines show each other where they are working; off, and
172
172
  // paired decks read "current account hidden" instead.
173
173
  shareActive: true,
174
- // THE LOGIN THIS DECK IS USING, SENT TO A PAIRED DECK, off unless somebody
175
- // turns it on (#2192). A ticked account goes to every paired deck that
176
- // lacks it or holds an expired copy — and when it is the one this deck is
177
- // signed in to, the two machines then hold one login. A Claude login renews
178
- // once: whichever copy renews it first keeps it, and the other machine is
179
- // signed out. So while this deck is on an account, that account stays
180
- // here, and goes out like any other the moment this deck switches away. A
181
- // new field, so nobody's saved choice is changed: the ticks are untouched,
182
- // and what they hand out is every login except the one in use.
183
- sendInUse: false,
174
+ // THE LOGIN THIS DECK IS USING, SENT TO A PAIRED DECK, on unless somebody
175
+ // turns it off: a ticked account goes out whether or not this deck is on it
176
+ // (owner, 2026-10-27, 3.48.1). From #2192 until then it was off, and people
177
+ // read a ticked account that never arrived as sharing being broken. The
178
+ // cost is the one #2192 found: the two machines then hold one login, and a
179
+ // Claude login renews once, so whichever copy renews second is signed out.
180
+ // The "Also active on" warning and Auto-switch avoiding an account active
181
+ // on another deck (#2192) stay, and the switch keeps it here for whoever
182
+ // wants that. See `sendInUseSet` in normalise for why a saved false from
183
+ // before 3.48.1 does not count.
184
+ sendInUse: true,
185
+ sendInUseSet: false,
184
186
  // FINDING THIS PERSON'S OTHER MACHINES OVER TAILSCALE, off until they turn
185
187
  // it on: it is a new path off this machine, and the owner chooses it. Its
186
188
  // two permissions ship on, like the local pair above, and they are narrower
@@ -321,9 +323,14 @@ function normaliseLan(raw) {
321
323
  // Whether paired decks are told which shared account this one is on. Absent
322
324
  // is on — the default above — and only a real boolean turns it off.
323
325
  shareActive: flagOr(src.shareActive, DEFAULTS.lan.shareActive),
324
- // Whether the login in use here may be sent. Off unless a real boolean
325
- // says on.
326
- sendInUse: flagOr(src.sendInUse, DEFAULTS.lan.sendInUse),
326
+ // Whether the login in use here may be sent. On unless somebody turned it
327
+ // off on 3.48.1 or later. Every write saves the whole normalised `lan`, so
328
+ // a deck from before then holds `sendInUse: false` whether or not anybody
329
+ // pressed the switch: the old default, written back with a tick or a name.
330
+ // That false says nothing, so it counts only beside `sendInUseSet`, which
331
+ // the page's own write of the switch adds (pagePatch).
332
+ sendInUse: src.sendInUseSet === true ? flagOr(src.sendInUse, DEFAULTS.lan.sendInUse) : DEFAULTS.lan.sendInUse,
333
+ sendInUseSet: src.sendInUseSet === true,
327
334
  // The Tailscale switch and its two permissions. Only a real boolean
328
335
  // overrides a default, as above.
329
336
  tailscale: flagOr(src.tailscale, DEFAULTS.lan.tailscale),
@@ -753,6 +760,9 @@ export function pagePatch(body) {
753
760
  };
754
761
  const patch = pick(body, PAGE_FIELDS.top);
755
762
  const lan = pick(body?.lan, PAGE_FIELDS.lan);
763
+ // Somebody pressed the switch, so from now on its value is a choice, not the
764
+ // default written back (see `sendInUseSet` in normalise).
765
+ if (Object.hasOwn(lan, "sendInUse")) lan.sendInUseSet = true;
756
766
  return Object.keys(lan).length ? { ...patch, lan } : patch;
757
767
  }
758
768
 
@@ -0,0 +1,78 @@
1
+ // Optional NVIDIA readings. Device discovery and numbers come from the driver;
2
+ // this module never changes its settings or installs a tool.
3
+ import { run } from "./metrics-run.mjs";
4
+
5
+ const QUERY = ["uuid", "name", "utilization.gpu", "memory.used", "memory.total", "temperature.gpu", "power.draw"];
6
+ const MIB = 1024 ** 2;
7
+
8
+ function number(text, max = Number.MAX_SAFE_INTEGER) {
9
+ if (!/^\d+(?:\.\d+)?$/.test(text)) return null;
10
+ const value = Number(text);
11
+ return Number.isFinite(value) && value <= max ? value : null;
12
+ }
13
+
14
+ // NVIDIA CSV may quote a product name. Reject malformed records rather than
15
+ // shifting columns and interpreting memory as temperature.
16
+ function columns(line) {
17
+ const cells = line.split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/).map(cell => cell.trim());
18
+ if (cells.length !== QUERY.length || cells.some(cell =>
19
+ cell.includes('"') && !/^"(?:[^"]|"")*"$/.test(cell))) return null;
20
+ return cells.map(cell => cell.startsWith('"')
21
+ ? cell.slice(1, -1).replace(/""/g, '"') : cell);
22
+ }
23
+
24
+ export function parseNvidiaReadings(output) {
25
+ if (typeof output !== "string") return [];
26
+ const devices = new Map();
27
+ for (const line of output.trim().split(/\r?\n/)) {
28
+ const cells = columns(line.trim());
29
+ if (!cells) continue;
30
+ const [id, name, utilization, used, total, temperature, power] = cells;
31
+ if (!/^GPU-[\w-]+$/.test(id) || !name || /[\x00-\x1f]/.test(name)) continue;
32
+ const memoryTotal = number(total, Number.MAX_SAFE_INTEGER / MIB);
33
+ const memoryUsed = number(used, Number.MAX_SAFE_INTEGER / MIB);
34
+ devices.set(id, {
35
+ id, name,
36
+ utilization: number(utilization, 100),
37
+ memoryTotal: memoryTotal > 0 ? memoryTotal * MIB : null,
38
+ memoryUsed: memoryUsed != null && (memoryTotal == null || memoryUsed <= memoryTotal)
39
+ ? memoryUsed * MIB : null,
40
+ temperature: number(temperature, 200),
41
+ power: number(power),
42
+ });
43
+ }
44
+ return [...devices.values()];
45
+ }
46
+
47
+ export function createGpuMetrics({ platform = process.platform, read = () => run(
48
+ "nvidia-smi", [`--query-gpu=${QUERY.join(",")}`, "--format=csv,noheader,nounits"], 2_000,
49
+ ) } = {}) {
50
+ let current = null;
51
+ function stop() {
52
+ if (current) clearTimeout(current.timer);
53
+ current = null;
54
+ }
55
+ function start() {
56
+ if (current || !["linux", "win32"].includes(platform)) return;
57
+ const state = { timer: null, devices: [] };
58
+ current = state;
59
+ const poll = async () => {
60
+ let devices = [];
61
+ try { devices = parseNvidiaReadings(await read()); } catch { /* optional driver */ }
62
+ if (current !== state) return;
63
+ state.devices = devices;
64
+ state.timer = setTimeout(poll, devices.length ? 5_000 : 60_000);
65
+ state.timer.unref?.();
66
+ };
67
+ void poll();
68
+ }
69
+ return {
70
+ start, stop,
71
+ snapshot: () => current?.devices.map(device => ({ ...device })) ?? [],
72
+ };
73
+ }
74
+
75
+ const gpu = createGpuMetrics();
76
+ export const startGpuMetrics = gpu.start;
77
+ export const stopGpuMetrics = gpu.stop;
78
+ export const gpuSnapshot = gpu.snapshot;
@@ -0,0 +1,239 @@
1
+ // One bounded Jira write: up to 50 top-level issues' sprint/backlog membership and
2
+ // rank. No URL, method, field id or arbitrary Jira body comes from the caller.
3
+ // Both Cloud and Server/DC support these Agile endpoints. Use assignment then
4
+ // rank separately: older Server schemas accept only `issues` on assignment.
5
+ // https://docs.atlassian.com/jira-software/REST/9.12.0/
6
+ // https://developer.atlassian.com/cloud/jira/software/rest/api-group-issue/
7
+ import { errorFromFetchFailure, errorFromStatus, errorResponse, integrationError } from "./errors.mjs";
8
+ import { isSafeTarget, originOf } from "./proxy.mjs";
9
+
10
+ const KEY = /^[A-Z][A-Z0-9_]{0,40}-[1-9]\d{0,11}$/;
11
+ const positiveId = n => Number.isSafeInteger(n) && n > 0 && n <= 999_999_999_999;
12
+ const object = v => v !== null && typeof v === "object" && !Array.isArray(v);
13
+ const only = (v, keys) => object(v) && Object.keys(v).every(k => keys.includes(k));
14
+ const invalid = message => integrationError("invalid", message);
15
+
16
+ export function parseJiraMove(body) {
17
+ if (!only(body, ["issueKey", "issueKeys", "target", "beforeIssue", "afterIssue"]) || Object.hasOwn(body, "issueKey") === Object.hasOwn(body, "issueKeys")) {
18
+ throw invalid("Supply either one issueKey or 2–50 ordered issueKeys and a sprint or backlog target.");
19
+ }
20
+ const key = value => typeof value === "string" && value === value.trim() && KEY.test(value) ? value : null;
21
+ const batch = Object.hasOwn(body, "issueKeys");
22
+ const issueKeys = batch ? body.issueKeys : [body.issueKey];
23
+ if (!Array.isArray(issueKeys) || issueKeys.length < (batch ? 2 : 1) || issueKeys.length > 50 ||
24
+ issueKeys.some(value => !key(value)) || new Set(issueKeys).size !== issueKeys.length) throw invalid("Supply unique, valid issue keys (2–50 for a batch).");
25
+ const t = body.target;
26
+ if (!only(t, t?.kind === "sprint" ? ["kind", "sprintId"] : ["kind"]) ||
27
+ !(t.kind === "backlog" || (t.kind === "sprint" && positiveId(t.sprintId)))) throw invalid("Not a valid issue key or move target.");
28
+ const beforeIssue = Object.hasOwn(body, "beforeIssue") ? key(body.beforeIssue) : undefined;
29
+ const afterIssue = Object.hasOwn(body, "afterIssue") ? key(body.afterIssue) : undefined;
30
+ if (beforeIssue === null || afterIssue === null || (beforeIssue && afterIssue) || issueKeys.includes(beforeIssue) || issueKeys.includes(afterIssue)) {
31
+ throw invalid("Use at most one other issue as the rank anchor.");
32
+ }
33
+ return { issueKeys: issueKeys.slice(), batch, target: t.kind === "sprint" ? { kind: "sprint", sprintId: t.sprintId } : { kind: "backlog" }, beforeIssue, afterIssue };
34
+ }
35
+
36
+ /** Conservative support, not a claim about the token's write permissions. */
37
+ export function jiraMoveCapability(config, filter) {
38
+ const rank = config?.ranking?.rankCustomFieldId;
39
+ if (config?.type !== "scrum" || !positiveId(rank)) return { enabled: false, reason: "Moving requires a Scrum board with a configured rank field." };
40
+ // Rank order must be the only ordering. An extra sort can make a successful
41
+ // rank invisible. Accept Jira's Rank alias or the configured field's JQL id.
42
+ const order = /\border\s+by\s+(.+)$/i.exec(String(filter?.jql ?? ""))?.[1]?.trim();
43
+ const field = order && /^(?:Rank|"Rank"|cf\[(\d+)\])\s+ASC$/i.exec(order);
44
+ if (!field || (field[1] && Number(field[1]) !== rank)) return { enabled: false, reason: "Moving requires the board filter to end with ORDER BY Rank ASC." };
45
+ return { enabled: true, rankCustomFieldId: rank };
46
+ }
47
+
48
+ export async function readJiraMoveCapability(read, agile, rest, boardId, config) {
49
+ const cfg = config ?? await read.json(`${agile}/board/${boardId}/configuration`);
50
+ if (cfg?.type !== "scrum" || !positiveId(cfg?.ranking?.rankCustomFieldId) || !/^\d{1,12}$/.test(String(cfg?.filter?.id ?? ""))) return jiraMoveCapability(cfg, null);
51
+ const filter = await read.json(`${rest}/filter/${cfg.filter.id}`);
52
+ return jiraMoveCapability(cfg, filter);
53
+ }
54
+
55
+ /** Only this closure can sign a write. The returned API takes a validated
56
+ * move, never an upstream address or HTTP method. */
57
+ export function createJiraMover({ secret, origins, sign, authCheck, fetchImpl = globalThis.fetch, reader, agile, rest, invalidate }) {
58
+ async function write(suffix, method, body, issueKeys, signal) {
59
+ const url = `${agile}/${suffix}`;
60
+ if (!isSafeTarget(url) || !origins().includes(originOf(url))) throw integrationError("permission", "This Jira write is outside the connection's token origins.");
61
+ const controller = new AbortController();
62
+ const stop = () => controller.abort(signal?.reason);
63
+ if (signal?.aborted) stop(); else signal?.addEventListener("abort", stop, { once: true });
64
+ const timer = setTimeout(() => controller.abort(), 15_000);
65
+ timer.unref?.();
66
+ let res;
67
+ try {
68
+ try {
69
+ res = await fetchImpl(url, { method, redirect: "manual", headers: { Accept: "application/json", "Content-Type": "application/json", "User-Agent": "ccdeck", ...sign(secret) }, body: JSON.stringify(body), signal: controller.signal });
70
+ } catch (err) { throw errorFromFetchFailure(err, "Jira"); }
71
+ // Never follow even a same-origin redirect: replaying a write is unsafe.
72
+ if (res.status >= 300 && res.status < 400) throw integrationError("upstream", "Jira redirected the write. It was not replayed; refresh the board before trying again.", { status: res.status });
73
+ const refused = authCheck(res.headers, secret);
74
+ if (refused) throw integrationError("expired", refused, { status: 401 });
75
+ if (res.status === 204) return;
76
+ if (res.status === 207) {
77
+ // Every requested key needs exactly one explicit success. A missing,
78
+ // duplicate or unrecognized entry is uncertainty, never success.
79
+ let size = 0;
80
+ const chunks = [];
81
+ if (res.body) for await (const chunk of res.body) {
82
+ size += chunk.byteLength;
83
+ if (size > 32_000) throw integrationError("upstream", "Jira's rank result was too large. Refresh the board to check its position.", { status: 207 });
84
+ chunks.push(Buffer.from(chunk));
85
+ }
86
+ let json;
87
+ try { json = JSON.parse(Buffer.concat(chunks).toString("utf8")); } catch { /* unknown result */ }
88
+ const entries = json?.entries;
89
+ const recognized = Array.isArray(entries) && entries.every(e => issueKeys.includes(e?.issueKey));
90
+ const results = new Map(issueKeys.map(key => {
91
+ const matches = recognized ? entries.filter(e => e.issueKey === key) : [];
92
+ const status = matches.length === 1 && Number.isInteger(matches[0].status) ? matches[0].status : null;
93
+ return [key, { status, state: status >= 200 && status < 300 ? "succeeded" : status >= 400 && status < 500 ? "failed" : "unknown" }];
94
+ }));
95
+ if ([...results.values()].every(r => r.state === "succeeded")) return;
96
+ const single = issueKeys.length === 1 ? results.get(issueKeys[0]) : null;
97
+ const err = single?.status >= 400 && single.status < 600
98
+ ? errorFromStatus(single.status, res.headers, { label: "Jira" })
99
+ : integrationError("upstream", "Jira did not confirm every requested issue update. Some issues may have changed; refresh the board to check them.", { status: 207 });
100
+ err.writeOutcomes = results;
101
+ throw err;
102
+ }
103
+ if (!res.ok) {
104
+ const err = errorFromStatus(res.status, res.headers, { label: "Jira" });
105
+ if (res.status === 403) err.message = "Jira refused the move: the account or token needs permission to edit and schedule this issue.";
106
+ throw err;
107
+ }
108
+ throw integrationError("upstream", "Jira did not confirm the write. Refresh the board to check the issue.", { status: res.status });
109
+ } finally {
110
+ clearTimeout(timer);
111
+ signal?.removeEventListener("abort", stop);
112
+ await res?.body?.cancel().catch(() => {});
113
+ }
114
+ }
115
+
116
+ return async (boardId, input, signal) => {
117
+ const move = parseJiraMove(input);
118
+ const { issueKeys, batch, target, beforeIssue, afterIssue } = move;
119
+ const anchor = beforeIssue ?? afterIssue;
120
+ const read = reader(signal);
121
+ const outcomes = new Map(issueKeys.map(key => [key, { membership: "unchanged", rank: "unchanged" }]));
122
+ let attempted = false;
123
+ let stage = "membership";
124
+ let pendingKeys = [];
125
+ try {
126
+ if (!/^[1-9]\d{0,11}$/.test(boardId) || boardId !== boardId.trim()) throw invalid("Not a board id.");
127
+ // No cached authorization, ordering, membership or sprint-state reads.
128
+ const board = await read.json(`${agile}/board/${boardId}`);
129
+ const cfg = await read.json(`${agile}/board/${boardId}/configuration`);
130
+ const capability = await readJiraMoveCapability(read, agile, rest, boardId, { ...cfg, type: board?.type });
131
+ if (!capability.enabled) throw invalid(capability.reason);
132
+ const keys = [...issueKeys, ...(anchor ? [anchor] : [])];
133
+ // The board may cap a page below 51 (50 moved keys plus their anchor).
134
+ // Read only these validated keys, stopping on no progress or at the bound.
135
+ const readIssues = async (suffix, selected, fields) => {
136
+ const found = new Map();
137
+ for (let startAt = 0, guard = 0; found.size < selected.length && guard < selected.length; guard++) {
138
+ const q = new URLSearchParams({ jql: `key in (${selected.join(",")})`, fields, maxResults: String(selected.length), startAt: String(startAt) });
139
+ const page = await read.json(`${agile}/board/${boardId}/${suffix}?${q}`);
140
+ const values = Array.isArray(page?.issues) ? page.issues : [];
141
+ const count = found.size;
142
+ for (const issue of values) if (selected.includes(issue?.key)) found.set(issue.key, issue);
143
+ if (found.size === count || page?.isLast === true || (Number.isInteger(page?.total) && startAt + values.length >= page.total)) break;
144
+ startAt += values.length;
145
+ }
146
+ return found;
147
+ };
148
+ const issues = await readIssues("issue", keys, "issuetype,status,sprint");
149
+ for (const key of keys) {
150
+ const issue = issues.get(key);
151
+ if (!issue) throw invalid("The issues and anchor must all belong to this board.");
152
+ if (issue.fields?.issuetype?.subtask !== false) throw invalid("The issues and rank anchor must be top-level issues.");
153
+ // Match Jira's issue normalizer, including renamed epic-level types.
154
+ const type = issue.fields?.issuetype;
155
+ const epic = type?.hierarchyLevel === 1 || /^epic$/i.test(String(type?.name ?? ""));
156
+ if (issueKeys.includes(key) && (epic || !["new", "indeterminate"].includes(issue.fields?.status?.statusCategory?.key))) {
157
+ throw invalid("Only unfinished top-level non-epic issues can be moved.");
158
+ }
159
+ }
160
+ const sources = new Map();
161
+ const sameGroup = source => source.kind === target.kind && (source.kind === "backlog" || source.sprintId === target.sprintId);
162
+ const groupId = group => group.kind === "backlog" ? "backlog" : `sprint:${group.sprintId}`;
163
+ const groups = new Map();
164
+ const wanted = new Set(target.kind === "sprint" ? [target.sprintId] : []);
165
+ for (const key of issueKeys) {
166
+ const raw = issues.get(key).fields?.sprint;
167
+ const current = raw == null ? [] : Array.isArray(raw) ? raw : [raw];
168
+ if (current.length > 1 || current.some(s => !positiveId(s?.id) || !["active", "future"].includes(s?.state))) throw invalid("Every issue must be in the backlog or one active or future sprint.");
169
+ const source = current.length ? { kind: "sprint", sprintId: current[0].id } : { kind: "backlog" };
170
+ sources.set(key, source);
171
+ if (source.kind === "sprint") wanted.add(source.sprintId);
172
+ const id = groupId(source);
173
+ if (!groups.has(id)) groups.set(id, { group: source, keys: [] });
174
+ groups.get(id).keys.push(key);
175
+ }
176
+ // A sprint visible elsewhere is not enough: it must be on this board.
177
+ for (let startAt = 0, guard = 0; wanted.size && guard < 20; guard++) {
178
+ const q = new URLSearchParams({ state: "active,future", startAt: String(startAt), maxResults: "50" });
179
+ const sprints = await read.json(`${agile}/board/${boardId}/sprint?${q}`);
180
+ const values = Array.isArray(sprints?.values) ? sprints.values : [];
181
+ for (const s of values) if (["active", "future"].includes(s?.state)) wanted.delete(s.id);
182
+ if (!values.length || sprints.isLast === true) break;
183
+ startAt += values.length;
184
+ }
185
+ if (wanted.size) throw invalid("The source and target must be active or future sprints on this board.");
186
+ const groupSuffix = group => group.kind === "sprint" ? `sprint/${group.sprintId}/issue` : "backlog";
187
+ for (const { group, keys } of groups.values()) {
188
+ const found = await readIssues(groupSuffix(group), keys, "issuetype");
189
+ if (keys.some(key => !found.has(key))) throw invalid("An issue's source changed or is a closed sprint. Refresh the board.");
190
+ }
191
+ if (anchor && !(await readIssues(groupSuffix(target), [anchor], "issuetype")).has(anchor)) throw invalid("The rank anchor must be in the target group. Refresh the board.");
192
+ const needed = issueKeys.filter(key => !sameGroup(sources.get(key)));
193
+ if (needed.length) {
194
+ attempted = true;
195
+ pendingKeys = needed;
196
+ const suffix = target.kind === "sprint" ? `sprint/${target.sprintId}/issue` : "backlog/issue";
197
+ await write(suffix, "POST", { issues: needed }, needed, signal);
198
+ for (const key of needed) outcomes.get(key).membership = "moved";
199
+ }
200
+ if (anchor) {
201
+ stage = "rank";
202
+ attempted = true;
203
+ pendingKeys = issueKeys;
204
+ await write("issue/rank", "PUT", { issues: issueKeys, rankCustomFieldId: capability.rankCustomFieldId,
205
+ ...(beforeIssue ? { rankBeforeIssue: beforeIssue } : { rankAfterIssue: afterIssue }) }, issueKeys, signal);
206
+ for (const key of issueKeys) outcomes.get(key).rank = "ranked";
207
+ }
208
+ return { status: 200, body: { ok: true, ...(batch ? { issueKeys } : { issueKey: issueKeys[0] }), target, refresh: true } };
209
+ } catch (err) {
210
+ const result = errorResponse(err);
211
+ if (attempted) {
212
+ const rejected = Number.isInteger(err?.status) && err.status >= 400 && err.status < 500;
213
+ for (const key of pendingKeys) {
214
+ const state = err?.writeOutcomes?.get(key)?.state ?? (rejected ? "failed" : "unknown");
215
+ outcomes.get(key)[stage] = state === "succeeded" ? (stage === "membership" ? "moved" : "ranked")
216
+ : state === "failed" ? (stage === "membership" ? "unchanged" : "failed") : "unknown";
217
+ }
218
+ const summarize = field => {
219
+ const states = new Set([...outcomes.values()].map(o => o[field]));
220
+ return states.size === 1 ? [...states][0] : states.has("unknown") ? "unknown" : "partial";
221
+ };
222
+ const outcome = { membership: summarize("membership"), rank: summarize("rank") };
223
+ const updated = [...outcomes.values()].some(o => o.membership === "moved" || o.rank === "ranked");
224
+ const prefix = batch && updated ? "Some issues were updated, but the whole batch was not confirmed. "
225
+ : !batch && outcome.membership === "moved" ? "The issue moved, but its requested position was not confirmed. " : "";
226
+ result.body.error.message = `${prefix}${result.body.error.message} Refresh the board before trying again.`;
227
+ result.body.refresh = true;
228
+ result.body.outcome = outcome;
229
+ if (batch) result.body.outcomes = issueKeys.map(issueKey => ({ issueKey, ...outcomes.get(issueKey) }));
230
+ }
231
+ return result;
232
+ } finally {
233
+ // Also after timeouts/redirects/partial failure: the remote may have
234
+ // applied a write. Replace the cache so older in-flight reads cannot
235
+ // repopulate the cache future requests use.
236
+ if (attempted) invalidate();
237
+ }
238
+ };
239
+ }
@@ -17,9 +17,10 @@
17
17
  // Agile 1.0. `Authorization: Bearer <PAT>`. Personal access tokens
18
18
  // arrived in Jira 8.14, so an older server is `incompatible`.
19
19
  //
20
- // Every request goes through the core's proxy (proxy.mjs), which
21
- // signs with `sign` below and only for the connection's allowed origins. The
22
- // routes are GET-only and answer normalised shapes (see `normaliseIssue`), so
20
+ // Reads go through the core's GET-only proxy (proxy.mjs), which signs with
21
+ // `sign` below and only for the connection's allowed origins. The one move
22
+ // route uses jira-move.mjs's private, non-replaying write transport. Reads
23
+ // answer normalised shapes (see `normaliseIssue`), so
23
24
  // the page draws Cloud and Server with one renderer: descriptions and comments
24
25
  // are Jira's own `renderedFields` HTML on both, sanitised in the browser
25
26
  // (src/web/jira-html.tsx).
@@ -27,6 +28,7 @@ import { createCache } from "./cache.mjs";
27
28
  import { errorResponse, integrationError, IntegrationError } from "./errors.mjs";
28
29
  import { createProxy, fetchImage, isLocalHost, isSafeTarget, normaliseBaseUrl, originOf } from "./proxy.mjs";
29
30
  import { createRouter } from "./registry.mjs";
31
+ import { createJiraMover, readJiraMoveCapability } from "./jira-move.mjs";
30
32
 
31
33
  export const MIN_SERVER_VERSION = [8, 14, 0];
32
34
  const ATLASSIAN_API = "https://api.atlassian.com";
@@ -464,6 +466,7 @@ async function boardConfig(ctx, boardId) {
464
466
  statusIds: (Array.isArray(c?.statuses) ? c.statuses : []).map(st => String(st?.id ?? "")).filter(id => /^\d{1,12}$/.test(id)),
465
467
  }));
466
468
  return {
469
+ moveConfig: cfg,
467
470
  estimation: { kind, fieldId: fieldId || null, label: text(field?.displayName, 80) || (kind === "time" ? "Original Time Estimate" : kind === "points" ? "Story points" : "Issue count") },
468
471
  columns,
469
472
  };
@@ -788,6 +791,14 @@ export function registerJiraRoutes(router) {
788
791
  hasSprints: scrum,
789
792
  hasBacklog: backlog,
790
793
  timeTracking: time,
794
+ moves: await ctx.cache.remember(`move-capability:${id}`, 10 * MINUTE, async () => {
795
+ try {
796
+ return await readJiraMoveCapability(ctx.client, agileBase(ctx.conn), restBase(ctx.conn), id, { ...config.moveConfig, type });
797
+ } catch {
798
+ // Viewing remains available when the token cannot inspect ordering.
799
+ return { enabled: false, reason: "The board's rank ordering could not be verified." };
800
+ }
801
+ }),
791
802
  };
792
803
  });
793
804
 
@@ -955,17 +966,22 @@ registerJiraRoutes(jiraRouter);
955
966
  */
956
967
  export function createJiraClient(conn, secret, { fetchImpl, apiOrigin } = {}) {
957
968
  let origins = Array.isArray(conn.allowedOrigins) && conn.allowedOrigins.length ? conn.allowedOrigins.slice() : [originOf(conn.baseUrl)].filter(Boolean);
958
- const cache = createCache();
969
+ let cache = createCache();
959
970
  const proxy = (list, phase, signal) => createProxy({
960
971
  conn: { ...conn, allowedOrigins: list }, secret, sign: signJira, phase, signal, fetchImpl,
961
972
  label: "Jira", errorDetail: jiraErrorDetail, authCheck: jiraAuthCheck,
962
973
  });
963
974
  let useProxy = null;
964
975
  const reader = () => (useProxy ??= proxy(origins, "use"));
976
+ const moveIssue = createJiraMover({ secret, origins: () => origins.slice(), sign: signJira, authCheck: jiraAuthCheck, fetchImpl,
977
+ reader: signal => ({ json: (url, opts = {}) => reader().json(url, { ...opts, signal }) }),
978
+ agile: agileBase(conn), rest: restBase(conn), invalidate: () => { cache = createCache(); },
979
+ });
965
980
  return {
966
981
  kind: "jira",
967
982
  conn,
968
- cache,
983
+ get cache() { return cache; },
984
+ moveIssue,
969
985
  get allowedOrigins() { return origins.slice(); },
970
986
  async validate({ phase = "validate", signal } = {}) {
971
987
  const result = await validateJira(conn, secret, { phase, signal, client: list => proxy(list, phase, signal) }, { apiOrigin });
@@ -994,9 +1010,15 @@ export function createJiraClient(conn, secret, { fetchImpl, apiOrigin } = {}) {
994
1010
  };
995
1011
  }
996
1012
 
997
- /** The panel's reads (registerJiraRoutes), as registry.mjs's `routes`. */
998
- export async function jiraRoutes(client, method, subpath, searchParams, _req, { signal } = {}) {
999
- if (method !== "GET" && method !== "HEAD") return errorResponse(integrationError("invalid", "The Jira panel only reads."));
1013
+ /** The panel's reads and its one bounded move, as registry.mjs's `routes`. */
1014
+ export async function jiraRoutes(client, method, subpath, searchParams, _req, { signal, moveBody } = {}) {
1015
+ const move = /^board\/([1-9]\d{0,11})\/move$/.exec(subpath);
1016
+ if (method === "POST" && move) {
1017
+ if ([...searchParams].length) return errorResponse(integrationError("invalid", "Move parameters belong in the JSON body."));
1018
+ try { return await client.moveIssue(move[1], moveBody, signal); }
1019
+ catch (err) { return errorResponse(err); }
1020
+ }
1021
+ if (method !== "GET" && method !== "HEAD") return errorResponse(integrationError("invalid", "That Jira operation is not supported."));
1000
1022
  const route = jiraRouter.find(subpath);
1001
1023
  if (!route) return errorResponse(integrationError("not-found", "No such Jira read."));
1002
1024
  try {
@@ -13,10 +13,9 @@
13
13
  // again, and one anywhere else is an error — the token is never re-sent to a
14
14
  // host the user did not connect.
15
15
  //
16
- // READ ONLY BY CONSTRUCTION. The proxy sends GET and nothing else. Browsing a
17
- // tracker is the whole feature; there is no route here that could change an
18
- // issue, and there is no generic "fetch this URL with my token" route anywhere
19
- // in the deck.
16
+ // READ ONLY BY CONSTRUCTION. This generic proxy sends GET and nothing else.
17
+ // Jira's bounded move has its own private write transport; it cannot turn this
18
+ // into a generic "fetch this URL with my token" route.
20
19
  import { errorFromFetchFailure, errorFromStatus, integrationError } from "./errors.mjs";
21
20
 
22
21
  /** HTTPS only, with one exception: a tracker on this machine (a mock, a