tabherd 0.0.1 → 0.6.0

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 (68) hide show
  1. package/CHANGELOG.md +166 -0
  2. package/LICENSE +674 -0
  3. package/README.md +538 -2
  4. package/launcher/npm.js +9 -0
  5. package/lib/agents.js +324 -0
  6. package/lib/codex-client.js +306 -0
  7. package/lib/codex-rollout.js +251 -0
  8. package/lib/codex.js +424 -0
  9. package/lib/comfy.js +479 -0
  10. package/lib/completed.js +55 -0
  11. package/lib/copilot.js +359 -0
  12. package/lib/cursor.js +516 -0
  13. package/lib/dismissed.js +30 -0
  14. package/lib/filters.js +120 -0
  15. package/lib/groups.js +144 -0
  16. package/lib/history.js +253 -0
  17. package/lib/llamacpp.js +159 -0
  18. package/lib/lmstudio.js +134 -0
  19. package/lib/localai.js +291 -0
  20. package/lib/memory.js +55 -0
  21. package/lib/ollama.js +124 -0
  22. package/lib/open-dashboard.js +39 -0
  23. package/lib/opencode.js +371 -0
  24. package/lib/repos.js +81 -0
  25. package/lib/saved.js +33 -0
  26. package/lib/secrets.js +196 -0
  27. package/lib/session-id.js +9 -0
  28. package/lib/settings.js +231 -0
  29. package/lib/store.js +44 -0
  30. package/lib/terminals/index.js +62 -0
  31. package/lib/terminals/kitty.js +126 -0
  32. package/lib/terminals/linux.js +310 -0
  33. package/lib/terminals/macos.js +468 -0
  34. package/lib/terminals/tmux.js +89 -0
  35. package/lib/terminals/unix-driver.js +172 -0
  36. package/lib/terminals/unix.js +204 -0
  37. package/lib/terminals/unsupported.js +22 -0
  38. package/lib/terminals/wezterm.js +103 -0
  39. package/lib/terminals/windows-close.ps1 +125 -0
  40. package/lib/terminals/windows-focus.ps1 +235 -0
  41. package/lib/terminals/windows-pick-folder.ps1 +57 -0
  42. package/lib/terminals/windows-titles.js +124 -0
  43. package/lib/terminals/windows-titles.ps1 +95 -0
  44. package/lib/terminals/windows.js +166 -0
  45. package/lib/ticket-refs.js +184 -0
  46. package/lib/tickets.js +437 -0
  47. package/lib/todos.js +166 -0
  48. package/lib/trackers.js +541 -0
  49. package/lib/transcript.js +314 -0
  50. package/lib/updates.js +186 -0
  51. package/package.json +35 -7
  52. package/public/app.js +4077 -0
  53. package/public/favicon.svg +1 -0
  54. package/public/icons/tabherd-128.png +0 -0
  55. package/public/icons/tabherd-16.png +0 -0
  56. package/public/icons/tabherd-20.png +0 -0
  57. package/public/icons/tabherd-24.png +0 -0
  58. package/public/icons/tabherd-256.png +0 -0
  59. package/public/icons/tabherd-32.png +0 -0
  60. package/public/icons/tabherd-40.png +0 -0
  61. package/public/icons/tabherd-48.png +0 -0
  62. package/public/icons/tabherd-512.png +0 -0
  63. package/public/icons/tabherd-64.png +0 -0
  64. package/public/index.html +655 -0
  65. package/public/lang/es.js +742 -0
  66. package/public/style.css +1443 -0
  67. package/server.js +814 -0
  68. package/placeholder.js +0 -3
@@ -0,0 +1,184 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ // Finding the tickets a session is about: Claim: and Unclaim: lines in its
7
+ // prompts and replies, ticket links in its prompts, and keys in its branch's
8
+ // name. Nothing here is looked up, and a link is only read for its key, never
9
+ // fetched. See docs/ticket-links.md.
10
+ //
11
+ // A ref is { key, hint }. The key is "ABC-123" (Jira or Linear),
12
+ // "owner/repo#12" (GitHub) or "#12" (an issue in the session's own GitHub
13
+ // repository, or with a Zendesk hint, a Zendesk ticket). The hint, if any,
14
+ // says where to look: a tracker's type or name, lower case, or
15
+ // "host:<address>" from a link.
16
+
17
+ const MAX_PER_TEXT = 20;
18
+ const MAX_PER_LINE = 10;
19
+ const KEY = /^([A-Za-z][A-Za-z0-9_]{0,19})-([1-9]\d{0,8})$/;
20
+ const GITHUB = /^([A-Za-z0-9][A-Za-z0-9-]{0,38})\/([A-Za-z0-9._-]{1,100})#([1-9]\d{0,8})$/;
21
+ const NUMBER = /^#?([1-9]\d{0,9})$/;
22
+ // A line that claims tickets, or gives them up: "Claim: ABC-123, ENG-42",
23
+ // maybe as a list item or in bold, as a reply may write it.
24
+ const CLAIM_LINE = /^\s*(?:[-*>]\s+)?[*_]*(claim|unclaim)[*_]*\s*:[*_]*\s*(.+?)\s*$/i;
25
+ // Text worth looking through: most isn't.
26
+ const MAYBE = /claim\s*:|\/browse\/|selectedIssue=|linear\.app\/|github\.com\/|\/agent\/tickets\//i;
27
+ // Words before a number in a branch's name that aren't a ticket's key:
28
+ // "utf-8", "v1-2", "release-3".
29
+ const NOT_A_KEY = /^(UTF|ISO|SHA|MD|RFC|CVE|IPV|HTTP|PY|NODE|ES|V\d+|PHASE|STEP|PART|WEEK|DAY|SPRINT|RELEASE|VERSION|FEATURE|BUGFIX|HOTFIX|FIX|TEST|ISSUES?|PR|PULL|MERGE)$/;
30
+
31
+ const LINKS = [
32
+ // A Jira issue, on any site: /browse/ABC-123, or a board with it open.
33
+ { re: /https?:\/\/([a-z0-9.-]+)(?::\d+)?(?:\/[^\s/?#]+)*?\/browse\/([A-Za-z][A-Za-z0-9_]*-[1-9]\d*)/gi, ref: (m) => ({ key: m[2].toUpperCase(), hint: `host:${m[1].toLowerCase()}` }) },
34
+ { re: /https?:\/\/([a-z0-9.-]+)(?::\d+)?\/[^\s]*?[?&]selectedIssue=([A-Za-z][A-Za-z0-9_]*-[1-9]\d*)/gi, ref: (m) => ({ key: m[2].toUpperCase(), hint: `host:${m[1].toLowerCase()}` }) },
35
+ { re: /https?:\/\/linear\.app\/[^\s/]+\/issue\/([A-Za-z][A-Za-z0-9]*-[1-9]\d*)/gi, ref: (m) => ({ key: m[1].toUpperCase(), hint: 'linear' }) },
36
+ { re: /https?:\/\/github\.com\/([A-Za-z0-9][A-Za-z0-9-]*)\/([A-Za-z0-9._-]+)\/issues\/([1-9]\d*)/gi, ref: (m) => ({ key: `${m[1]}/${m[2]}#${m[3]}`.toLowerCase(), hint: 'github' }) },
37
+ { re: /https?:\/\/([a-z0-9.-]+)(?::\d+)?\/agent\/tickets\/([1-9]\d*)/gi, ref: (m) => ({ key: `#${m[2]}`, hint: `host:${m[1].toLowerCase()}` }) },
38
+ ];
39
+
40
+ // The tickets linked in some text, in the order they're in it.
41
+ function linksIn(text) {
42
+ const found = [];
43
+ for (const { re, ref } of LINKS) for (const m of String(text).matchAll(re)) found.push({ at: m.index, ...ref(m) });
44
+ return found.sort((a, b) => a.at - b.at).map(({ key, hint }) => ({ key, hint }));
45
+ }
46
+
47
+ // One key, as written: ABC-123, owner/repo#12, #12 or 12.
48
+ function keyIn(token) {
49
+ const t = String(token).replace(/^[`'"([{<*_]+|[`'"\])}>*_.!?:]+$/g, '');
50
+ let m = t.match(KEY);
51
+ if (m) return `${m[1].toUpperCase()}-${m[2]}`;
52
+ m = t.match(GITHUB);
53
+ if (m) return `${m[1]}/${m[2]}#${m[3]}`.toLowerCase();
54
+ m = t.match(NUMBER);
55
+ return m ? `#${m[1]}` : null;
56
+ }
57
+
58
+ // What a claim line names: keys or links, separated by commas, each maybe
59
+ // with where to look first ("Linear ENG-42", "Zendesk 4567") or a note
60
+ // after it ("ABC-123 (the login bug)").
61
+ function itemsIn(list) {
62
+ const refs = [];
63
+ for (const part of String(list).split(/[,;]/)) {
64
+ const item = part.trim();
65
+ if (!item) continue;
66
+ const links = linksIn(item);
67
+ if (links.length) {
68
+ refs.push(...links);
69
+ continue;
70
+ }
71
+ const words = item.split(/\s+/);
72
+ const keys = words.map(keyIn);
73
+ if (keys.every(Boolean)) {
74
+ for (const key of keys) refs.push({ key, hint: null });
75
+ } else if (keys[keys.length - 1] && !keys.slice(0, -1).some(Boolean)) {
76
+ const hint = words.slice(0, -1).join(' ').replace(/[*_`]/g, '').trim().toLowerCase();
77
+ refs.push({ key: keys[keys.length - 1], hint: hint || null });
78
+ } else if (keys[0] && !keys.slice(1).some(Boolean)) {
79
+ refs.push({ key: keys[0], hint: null });
80
+ }
81
+ }
82
+ return refs.slice(0, MAX_PER_LINE);
83
+ }
84
+
85
+ // Claims, unclaims and (in prompts) links in a prompt or reply, in order:
86
+ // [{ op: 'claim' | 'unclaim', key, hint }]. A key mentioned in passing isn't
87
+ // one: only a line that starts with Claim: or Unclaim: claims, and only a
88
+ // link you sent links.
89
+ function find(text, from = 'prompt') {
90
+ const t = typeof text === 'string' ? text : '';
91
+ if (!MAYBE.test(t)) return [];
92
+ const found = [];
93
+ for (const line of t.split(/\r?\n/)) {
94
+ const claim = line.match(CLAIM_LINE);
95
+ if (claim) for (const ref of itemsIn(claim[2])) found.push({ op: claim[1].toLowerCase(), ...ref });
96
+ else if (from === 'prompt') for (const ref of linksIn(line)) found.push({ op: 'claim', ...ref });
97
+ if (found.length >= MAX_PER_TEXT) break;
98
+ }
99
+ return found.slice(0, MAX_PER_TEXT);
100
+ }
101
+
102
+ // The tickets in a branch's name: keys anywhere in it, in any case, as
103
+ // Linear's own branch names are lower case ("eng-42-fix-login"), and a GitHub
104
+ // issue's number when its last part starts with one, as GitHub names a
105
+ // branch made from an issue ("123-fix-login").
106
+ function inBranch(branch) {
107
+ const b = typeof branch === 'string' ? branch : '';
108
+ const found = [];
109
+ for (const m of b.matchAll(/(?:^|[^A-Za-z0-9])([A-Za-z][A-Za-z0-9]{1,9})-([1-9]\d{0,6})(?=$|[^0-9])/g)) {
110
+ const prefix = m[1].toUpperCase();
111
+ if (!NOT_A_KEY.test(prefix)) found.push({ key: `${prefix}-${m[2]}`, hint: null });
112
+ }
113
+ const last = b.split('/').pop();
114
+ const issue = last.match(/^([1-9]\d{0,8})-[A-Za-z]/) || last.match(/(?:^|[^A-Za-z])issues?[-_]?([1-9]\d{0,8})(?=$|[^0-9])/i);
115
+ if (issue) found.push({ key: `#${issue[1]}`, hint: 'github' });
116
+ return found.slice(0, 3);
117
+ }
118
+
119
+ const refId = (r) => `${r.hint || ''}|${r.key}`;
120
+
121
+ // ---- the repository a folder is in -------------------------------------------------
122
+
123
+ const REPO_CACHE_MS = 30000;
124
+ const repos = new Map();
125
+
126
+ // The .git folder for a folder in a repository, and the folder its config is
127
+ // in, which for a worktree is the main one's.
128
+ function gitDirs(cwd) {
129
+ let dir = path.resolve(cwd);
130
+ for (let i = 0; i < 40; i++) {
131
+ const dotGit = path.join(dir, '.git');
132
+ let st;
133
+ try {
134
+ st = fs.statSync(dotGit);
135
+ } catch {
136
+ st = null;
137
+ }
138
+ if (st?.isDirectory()) return { git: dotGit, common: dotGit };
139
+ if (st?.isFile()) {
140
+ const m = fs.readFileSync(dotGit, 'utf8').match(/^gitdir:\s*(.+?)\s*$/m);
141
+ if (!m) return null;
142
+ const git = path.resolve(dir, m[1]);
143
+ let common = git;
144
+ try {
145
+ common = path.resolve(git, fs.readFileSync(path.join(git, 'commondir'), 'utf8').trim());
146
+ } catch {}
147
+ return { git, common };
148
+ }
149
+ const up = path.dirname(dir);
150
+ if (up === dir) return null;
151
+ dir = up;
152
+ }
153
+ return null;
154
+ }
155
+
156
+ // "owner/repo" from a GitHub remote's address, in any of its forms.
157
+ function githubRepo(url) {
158
+ const m = String(url || '').match(/^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9][A-Za-z0-9-]*)\/([A-Za-z0-9._-]+?)(?:\.git)?\/?$/i);
159
+ return m ? `${m[1]}/${m[2]}`.toLowerCase() : null;
160
+ }
161
+
162
+ // A folder's branch, and its GitHub repository if its origin is on GitHub:
163
+ // { branch, github }. Read from its .git, not by running git, and kept for
164
+ // half a minute.
165
+ function repoOf(cwd, now = Date.now()) {
166
+ if (typeof cwd !== 'string' || !cwd) return { branch: null, github: null };
167
+ const hit = repos.get(cwd);
168
+ if (hit && now - hit.at < REPO_CACHE_MS) return hit.info;
169
+ let info = { branch: null, github: null };
170
+ try {
171
+ const dirs = gitDirs(cwd);
172
+ if (dirs) {
173
+ const head = fs.readFileSync(path.join(dirs.git, 'HEAD'), 'utf8').match(/^ref:\s*refs\/heads\/(.+?)\s*$/m);
174
+ const config = fs.readFileSync(path.join(dirs.common, 'config'), 'utf8');
175
+ const origin = config.match(/\[remote "origin"\][^[]*?^\s*url\s*=\s*(.+?)\s*$/m);
176
+ info = { branch: head ? head[1] : null, github: origin ? githubRepo(origin[1]) : null };
177
+ }
178
+ } catch {}
179
+ repos.set(cwd, { at: now, info });
180
+ if (repos.size > 500) repos.delete(repos.keys().next().value);
181
+ return info;
182
+ }
183
+
184
+ module.exports = { find, inBranch, itemsIn, linksIn, keyIn, refId, repoOf, githubRepo };
package/lib/tickets.js ADDED
@@ -0,0 +1,437 @@
1
+ 'use strict';
2
+
3
+ // The tickets on cards. ticket-refs.js finds which tickets each session is
4
+ // about: its branch, the Claim: lines and links in what it was asked and
5
+ // said, and its to-do's. Each is looked up in the trackers Settings →
6
+ // Tickets has, and linked in each that has it: no ticket, no link. What each
7
+ // session claimed, and the tickets added or taken off by hand, are kept in
8
+ // tickets.json, with the last status read of each ticket, so cards have
9
+ // them at once after a restart. See docs/ticket-links.md.
10
+
11
+ const store = require('./store');
12
+ const settings = require('./settings');
13
+ const trackers = require('./trackers');
14
+ const ticketRefs = require('./ticket-refs');
15
+ const { isSessionId } = require('./session-id');
16
+
17
+ const FRESH_MS = 5 * 60 * 1000;
18
+ const MISSING_MS = 60 * 60 * 1000;
19
+ const RETRY_MS = 60 * 1000;
20
+ const AT_ONCE = 4;
21
+ const WAIT_MS = 12000;
22
+ const SAVE_DELAY_MS = 2000;
23
+ const SEEN_EVERY_MS = 60 * 60 * 1000;
24
+ const MAX_SESSIONS = 1000;
25
+ const MAX_KNOWN = 2000;
26
+ const MAX_REFS = 50;
27
+ const SESSION_APPS = new Set(['claude', 'codex', 'copilot', 'opencode', 'cursor']);
28
+
29
+ // The trackers in Settings → Tickets; tests give their own.
30
+ let trackerList = () => settings.get().trackers || [];
31
+ const useTrackers = (fn) => {
32
+ trackerList = fn;
33
+ };
34
+
35
+ // ---- what's kept -----------------------------------------------------------------
36
+
37
+ function cleanRef(r) {
38
+ if (!r || typeof r.key !== 'string' || r.key.length > 200) return null;
39
+ if (r.hint !== null && r.hint !== undefined && (typeof r.hint !== 'string' || r.hint.length > 100)) return null;
40
+ return { key: r.key, hint: r.hint || null };
41
+ }
42
+ const strings = (list, max) => (Array.isArray(list) ? list.filter((s) => typeof s === 'string' && s.length <= 300).slice(-max) : []);
43
+ const refList = (list) => (Array.isArray(list) ? list.map(cleanRef).filter(Boolean).slice(-MAX_REFS) : []);
44
+
45
+ function load() {
46
+ const saved = store.read('tickets', null);
47
+ const sessions = {};
48
+ for (const [id, r] of Object.entries(saved?.sessions || {})) {
49
+ if (!isSessionId(id) || !r || typeof r !== 'object') continue;
50
+ sessions[id] = { claims: refList(r.claims), manual: refList(r.manual), dropped: strings(r.dropped, MAX_REFS), removed: strings(r.removed, MAX_REFS), seen: Number(r.seen) || 0 };
51
+ }
52
+ const known = {};
53
+ for (const [id, k] of Object.entries(saved?.known || {})) {
54
+ if (typeof id === 'string' && k?.ticket && typeof k.ticket.key === 'string' && Number.isFinite(k.at)) known[id] = { ticket: k.ticket, at: k.at };
55
+ }
56
+ return { sessions, known };
57
+ }
58
+
59
+ let data = load();
60
+ // Each lookup's last answer, by "<tracker ID> <key>": { ticket, at },
61
+ // { missing: true, at }, or with error and errorAt when it couldn't say.
62
+ const lookups = new Map(Object.entries(data.known));
63
+ const pending = new Map();
64
+ const queue = [];
65
+ let running = 0;
66
+ // Each tracker's last problem: { error, auth, at }.
67
+ const problems = new Map();
68
+ let saveTimer = null;
69
+
70
+ function write() {
71
+ const newest = (obj, at, max) =>
72
+ Object.fromEntries(
73
+ Object.entries(obj)
74
+ .sort(([, a], [, b]) => at(b) - at(a))
75
+ .slice(0, max),
76
+ );
77
+ data = { sessions: newest(data.sessions, (r) => r.seen, MAX_SESSIONS), known: newest(data.known, (k) => k.at, MAX_KNOWN) };
78
+ try {
79
+ store.write('tickets', data);
80
+ } catch {}
81
+ }
82
+
83
+ function saveSoon() {
84
+ if (saveTimer) return;
85
+ saveTimer = setTimeout(() => {
86
+ saveTimer = null;
87
+ write();
88
+ }, SAVE_DELAY_MS);
89
+ saveTimer.unref?.();
90
+ }
91
+
92
+ function record(id, now = Date.now()) {
93
+ if (!data.sessions[id]) data.sessions[id] = { claims: [], manual: [], dropped: [], removed: [], seen: now };
94
+ return data.sessions[id];
95
+ }
96
+
97
+ const sameRef = (a, b) => a.key === b.key && (a.hint || null) === (b.hint || null);
98
+
99
+ // Claim and Unclaim, in order. Replaying the same ones again changes
100
+ // nothing, so a transcript read again from the start is fine.
101
+ function apply(r, ops) {
102
+ for (const op of ops) {
103
+ const ref = cleanRef(op);
104
+ if (!ref) continue;
105
+ if (op.op === 'unclaim') {
106
+ r.claims = r.claims.filter((x) => x.key !== ref.key);
107
+ r.manual = r.manual.filter((x) => x.key !== ref.key);
108
+ if (!r.dropped.includes(ref.key)) r.dropped.push(ref.key);
109
+ } else {
110
+ if (!r.claims.some((x) => sameRef(x, ref))) r.claims.push(ref);
111
+ r.dropped = r.dropped.filter((k) => k !== ref.key);
112
+ }
113
+ }
114
+ r.claims = r.claims.slice(-MAX_REFS);
115
+ r.dropped = r.dropped.slice(-MAX_REFS);
116
+ }
117
+
118
+ // ---- where each ticket is looked up ----------------------------------------------------
119
+
120
+ const hostOf = (url) => {
121
+ try {
122
+ return new URL(url).hostname.toLowerCase();
123
+ } catch {
124
+ return '';
125
+ }
126
+ };
127
+
128
+ // Whether a ref's hint names this tracker: its type, its name, or the
129
+ // address a link was on.
130
+ function named(hint, t) {
131
+ if (!hint) return true;
132
+ if (hint.startsWith('host:')) return hostOf(t.url) === hint.slice(5);
133
+ return hint === t.type || hint === t.name.toLowerCase() || (t.type === 'github' && ['github issues', 'gh'].includes(hint));
134
+ }
135
+
136
+ // The trackers a ref could be in, and its key in each: [{ t, key }]. "#12"
137
+ // is a Zendesk ticket where a Zendesk tracker is named, else an issue in the
138
+ // session's GitHub repository.
139
+ function where(ref, list, github) {
140
+ const key = ref.key;
141
+ const is = (type) => list.filter((t) => t.type === type && named(ref.hint, t));
142
+ const m = key.match(/^([A-Z][A-Z0-9_]*)-\d+$/);
143
+ if (m) return list.filter((t) => (t.type === 'jira' || t.type === 'linear') && named(ref.hint, t) && (!t.prefixes.length || t.prefixes.includes(m[1]))).map((t) => ({ t, key }));
144
+ if (/^[a-z0-9][a-z0-9-]*\/[a-z0-9._-]+#\d+$/.test(key)) return is('github').map((t) => ({ t, key }));
145
+ if (/^#\d+$/.test(key)) {
146
+ const zendesk = ref.hint ? is('zendesk') : [];
147
+ if (zendesk.length) return zendesk.map((t) => ({ t, key }));
148
+ return github ? is('github').map((t) => ({ t, key: `${github}${key}` })) : [];
149
+ }
150
+ return [];
151
+ }
152
+
153
+ // ---- looking up -------------------------------------------------------------------------
154
+
155
+ // Whether a lookup's answer is still good: a ticket for five minutes, none
156
+ // for an hour, and after a failure, a minute before trying again.
157
+ function fresh(info, now) {
158
+ if (!info) return false;
159
+ if (info.errorAt && now - info.errorAt < RETRY_MS) return true;
160
+ if (info.missing) return now - info.at < MISSING_MS;
161
+ return Boolean(info.ticket) && now - info.at < FRESH_MS;
162
+ }
163
+
164
+ function pump() {
165
+ while (running < AT_ONCE && queue.length) {
166
+ const job = queue.shift();
167
+ running++;
168
+ trackers
169
+ .read(job.t, job.key)
170
+ .then((r) => {
171
+ const at = Date.now();
172
+ if (r.ok) {
173
+ const ticket = { ...r.ticket, title: String(r.ticket.title || '').slice(0, 300) };
174
+ lookups.set(job.id, { ticket, at });
175
+ data.known[job.id] = { ticket, at };
176
+ problems.delete(job.t.id);
177
+ saveSoon();
178
+ } else if (r.missing) {
179
+ lookups.set(job.id, { missing: true, at });
180
+ if (data.known[job.id]) {
181
+ delete data.known[job.id];
182
+ saveSoon();
183
+ }
184
+ problems.delete(job.t.id);
185
+ } else {
186
+ // Its last known status stays until it answers again.
187
+ lookups.set(job.id, { ...(lookups.get(job.id) || { at: 0 }), error: r.error, errorAt: at });
188
+ problems.set(job.t.id, { error: r.error, auth: Boolean(r.auth), at });
189
+ }
190
+ })
191
+ .finally(() => {
192
+ running--;
193
+ const done = pending.get(job.id);
194
+ pending.delete(job.id);
195
+ done?.resolve();
196
+ pump();
197
+ });
198
+ }
199
+ }
200
+
201
+ // Looks a ticket up unless its last answer is still good. Resolves once
202
+ // it's answered.
203
+ function want(t, key, now = Date.now()) {
204
+ const id = `${t.id} ${key}`;
205
+ if (pending.has(id)) return pending.get(id).promise;
206
+ if (fresh(lookups.get(id), now)) return Promise.resolve();
207
+ let resolve;
208
+ const promise = new Promise((r) => (resolve = r));
209
+ pending.set(id, { promise, resolve });
210
+ queue.push({ t, key, id });
211
+ pump();
212
+ return promise;
213
+ }
214
+
215
+ // ---- a session's tickets --------------------------------------------------------------
216
+
217
+ // The tickets linked to a session or to-do, as chips: { id, tracker,
218
+ // trackerName, type, key, title, status, category, assignee, url }. Ones not
219
+ // looked up yet are asked for, and show once they're found.
220
+ function linked(subject, r, list, now, { branch = true } = {}) {
221
+ const repo = ticketRefs.repoOf(subject.cwd, now);
222
+ const dropped = new Set(r?.dropped || []);
223
+ const removed = new Set(r?.removed || []);
224
+ const all = [
225
+ ...(branch ? ticketRefs.inBranch(subject.gitBranch || repo.branch) : []),
226
+ ...refList(subject.todo?.ticketRefs),
227
+ ...(r?.claims || []),
228
+ ...(r?.manual || []),
229
+ ];
230
+ const chips = [];
231
+ for (const ref of all) {
232
+ if (dropped.has(ref.key)) continue;
233
+ for (const { t, key } of where(ref, list, repo.github)) {
234
+ want(t, key, now);
235
+ const ticket = lookups.get(`${t.id} ${key}`)?.ticket;
236
+ if (!ticket) continue;
237
+ const id = `${t.id} ${ticket.key}`;
238
+ if (removed.has(id) || chips.some((c) => c.id === id)) continue;
239
+ chips.push({ id, tracker: t.id, trackerName: t.name, type: t.type, ...ticket });
240
+ }
241
+ }
242
+ return chips;
243
+ }
244
+
245
+ // Each session's claims, as its transcript gave them, by session ID: the
246
+ // list and how much of it is applied. A new list (the transcript was read
247
+ // again) is applied from the start.
248
+ const applied = new Map();
249
+
250
+ // Called with each snapshot: records what each session claimed, and puts its
251
+ // tickets on its card as `tickets`.
252
+ function observe(agents, now = Date.now()) {
253
+ const list = trackerList();
254
+ const live = new Set();
255
+ for (const a of agents) {
256
+ const ops = Array.isArray(a.ticketRefs) ? a.ticketRefs : null;
257
+ delete a.ticketRefs;
258
+ if (!SESSION_APPS.has(a.app) || !isSessionId(a.id)) continue;
259
+ live.add(a.id);
260
+ if (ops?.length) {
261
+ const last = applied.get(a.id);
262
+ const unseen = last?.list === ops && ops.length >= last.n ? ops.slice(last.n) : ops;
263
+ applied.set(a.id, { list: ops, n: ops.length });
264
+ if (unseen.length) {
265
+ const r = record(a.id, now);
266
+ const before = JSON.stringify(r);
267
+ apply(r, unseen);
268
+ if (JSON.stringify(r) !== before) saveSoon();
269
+ }
270
+ }
271
+ const r = data.sessions[a.id];
272
+ if (r && now - r.seen > SEEN_EVERY_MS) {
273
+ r.seen = now;
274
+ saveSoon();
275
+ }
276
+ if (list.length) a.tickets = linked(a, r, list, now);
277
+ }
278
+ for (const id of applied.keys()) if (!live.has(id)) applied.delete(id);
279
+ }
280
+
281
+ // A to-do's tickets, as chips. A to-do isn't on its folder's branch yet.
282
+ function forTodo(todo, now = Date.now()) {
283
+ const list = trackerList();
284
+ if (!list.length || !todo.ticketRefs?.length) return [];
285
+ return linked({ cwd: todo.cwd, todo }, null, list, now, { branch: false });
286
+ }
287
+
288
+ // What was typed into + Ticket or a to-do's Tickets field, as refs.
289
+ const parse = (text) => ticketRefs.itemsIn(String(text || '').slice(0, 2000));
290
+
291
+ const withTimeout = (promise) => Promise.race([promise, new Promise((resolve) => setTimeout(resolve, WAIT_MS).unref?.())]);
292
+
293
+ // Links what was pasted into a session's + Ticket: links or keys, as in a
294
+ // Claim: line. Waits for them to be looked up, to say which weren't found.
295
+ async function add(subject, text, now = Date.now()) {
296
+ const refs = parse(text);
297
+ if (!refs.length) return { ok: false, error: 'Paste a ticket link or key, such as ABC-123.' };
298
+ const list = trackerList();
299
+ if (!list.length) return { ok: false, error: 'Add your trackers in Settings → Tickets first.' };
300
+ const repo = ticketRefs.repoOf(subject.cwd, now);
301
+ const r = record(subject.id, now);
302
+ const linkedKeys = [];
303
+ const notFound = [];
304
+ const unsure = [];
305
+ for (const ref of refs) {
306
+ const places = where(ref, list, repo.github);
307
+ await withTimeout(Promise.all(places.map(({ t, key }) => want(t, key, now))));
308
+ const answers = places.map(({ t, key }) => ({ t, info: lookups.get(`${t.id} ${key}`) }));
309
+ const found = answers.filter((x) => x.info?.ticket);
310
+ if (found.length) {
311
+ for (const { t, info } of found) {
312
+ r.removed = r.removed.filter((id) => id !== `${t.id} ${info.ticket.key}`);
313
+ linkedKeys.push(info.ticket.key);
314
+ }
315
+ } else if (answers.length && answers.every((x) => x.info?.missing)) {
316
+ notFound.push(ref.key);
317
+ continue;
318
+ } else if (!answers.length) {
319
+ notFound.push(ref.key);
320
+ continue;
321
+ } else {
322
+ unsure.push(ref.key);
323
+ }
324
+ if (!r.manual.some((x) => sameRef(x, ref))) r.manual.push(ref);
325
+ r.dropped = r.dropped.filter((k) => k !== ref.key);
326
+ }
327
+ r.manual = r.manual.slice(-MAX_REFS);
328
+ saveSoon();
329
+ return { ok: true, linked: [...new Set(linkedKeys)], notFound, unsure };
330
+ }
331
+
332
+ // Takes a ticket's chip off a session's card, for good.
333
+ function remove(sessionId, chipId, now = Date.now()) {
334
+ if (typeof chipId !== 'string' || chipId.length > 300) return { ok: false, error: 'Not a ticket.' };
335
+ const r = record(sessionId, now);
336
+ if (!r.removed.includes(chipId)) r.removed.push(chipId);
337
+ r.removed = r.removed.slice(-MAX_REFS);
338
+ saveSoon();
339
+ return { ok: true };
340
+ }
341
+
342
+ // ---- a to-do from a ticket ------------------------------------------------------------
343
+
344
+ // A to-do's longest title and notes, as todos.js keeps them.
345
+ const TODO_TITLE = 200;
346
+ const TODO_NOTES = 20000;
347
+ const cut = (s, max) => (s.length > max ? `${s.slice(0, max - 1)}…` : s);
348
+
349
+ // What was pasted as a new to-do's title, if it's one ticket's link or key,
350
+ // read with its description: { ok: true, ticket: { key, title, description,
351
+ // trackerName } }, cut to fit a to-do. Anything else pasted answers { ok:
352
+ // true, ticket: null }. Read afresh, with only its status kept, so its chip
353
+ // shows at once.
354
+ async function describe(text, now = Date.now()) {
355
+ const pasted = String(text || '').trim();
356
+ const refs = /\s/.test(pasted) || pasted.length > 2000 ? [] : parse(pasted);
357
+ // "#12" alone could be any repository's issue, or a Zendesk ticket.
358
+ if (refs.length !== 1 || (refs[0].key.startsWith('#') && !refs[0].hint)) return { ok: true, ticket: null };
359
+ const list = trackerList();
360
+ if (!list.length) return { ok: false, error: 'Add your trackers in Settings → Tickets first.' };
361
+ const answers = await Promise.all(where(refs[0], list, null).map(({ t, key }) => trackers.read(t, key, { description: true }).then((r) => ({ t, key, r }))));
362
+ const found = answers.find((x) => x.r.ok);
363
+ if (!found) return { ok: false, error: answers.find((x) => x.r.error)?.r.error || "That ticket wasn't found in your trackers." };
364
+ const { description, ...ticket } = found.r.ticket;
365
+ const known = { ticket: { ...ticket, title: ticket.title.slice(0, 300) }, at: now };
366
+ lookups.set(`${found.t.id} ${found.key}`, known);
367
+ data.known[`${found.t.id} ${found.key}`] = known;
368
+ problems.delete(found.t.id);
369
+ saveSoon();
370
+ return { ok: true, ticket: { key: ticket.key, title: cut(ticket.title.replace(/\s+/g, ' ').trim() || ticket.key, TODO_TITLE), description: cut(description, TODO_NOTES), trackerName: found.t.name } };
371
+ }
372
+
373
+ // A tracker was changed or removed: what was read with its old sign-in goes.
374
+ function forget(trackerId) {
375
+ for (const id of [...lookups.keys()]) if (id.startsWith(`${trackerId} `)) lookups.delete(id);
376
+ for (const id of Object.keys(data.known)) if (id.startsWith(`${trackerId} `)) delete data.known[id];
377
+ problems.delete(trackerId);
378
+ saveSoon();
379
+ }
380
+
381
+ // ---- writing back on Complete --------------------------------------------------------
382
+
383
+ const MAX_COMMENT = 20000;
384
+
385
+ // For the Complete dialog: how each of a session's tickets could be moved to
386
+ // done. One that's already done or closed, or a pull request, isn't moved.
387
+ async function doneOptions(agent) {
388
+ const list = trackerList();
389
+ const tickets = await Promise.all(
390
+ (agent.tickets || []).map(async (c) => {
391
+ const t = list.find((x) => x.id === c.tracker);
392
+ if (!t) return { chip: c.id, moves: [], error: 'That tracker is gone.' };
393
+ if (c.pullRequest || c.category === 'done' || c.category === 'closed') return { chip: c.id, moves: [] };
394
+ const r = (await withTimeout(trackers.doneMoves(t, c.key))) || { ok: false, error: "It didn't answer in time." };
395
+ return r.ok ? { chip: c.id, moves: r.moves } : { chip: c.id, moves: [], error: r.error };
396
+ }),
397
+ );
398
+ return { ok: true, tickets };
399
+ }
400
+
401
+ // Posts what the Complete dialog asked for, ticket by ticket: [{ chip,
402
+ // comment, publicReply, move }]. Only tickets on the session's card can be
403
+ // written to. Answers each one's result, with what was done before anything
404
+ // failed, so it isn't done twice when tried again.
405
+ async function writeBack(agent, writes) {
406
+ if (!Array.isArray(writes) || writes.length > MAX_REFS) return { ok: false, error: 'Not a ticket.' };
407
+ const list = trackerList();
408
+ const results = [];
409
+ for (const w of writes) {
410
+ const chip = (agent.tickets || []).find((c) => c.id === w?.chip);
411
+ const t = chip && list.find((x) => x.id === chip.tracker);
412
+ if (!t) {
413
+ results.push({ chip: typeof w?.chip === 'string' ? w.chip : null, ok: false, error: 'That ticket is no longer on its card.', done: [] });
414
+ continue;
415
+ }
416
+ const comment = typeof w.comment === 'string' && w.comment.trim() ? w.comment.slice(0, MAX_COMMENT) : null;
417
+ const move = typeof w.move === 'string' && w.move.length <= 100 && !chip.pullRequest ? w.move : null;
418
+ const r = comment || move ? await trackers.write(t, chip.key, { comment, publicReply: w.publicReply === true, move }) : { ok: true, done: [] };
419
+ results.push({ chip: chip.id, ok: r.ok, error: r.ok ? null : r.error, done: r.done || [] });
420
+ // Read its status again, now it's changed.
421
+ if (r.done?.length) {
422
+ const id = `${t.id} ${chip.key}`;
423
+ const info = lookups.get(id);
424
+ if (info) lookups.set(id, { ...info, at: 0, errorAt: 0 });
425
+ want(t, chip.key);
426
+ }
427
+ }
428
+ return { ok: true, results };
429
+ }
430
+
431
+ // Each tracker's last problem, for Settings → Tickets: { [id]: { error, auth, at } }.
432
+ const problemsNow = () => Object.fromEntries(problems);
433
+
434
+ // Once every lookup asked for has answered.
435
+ const settled = () => Promise.all([...pending.values()].map((p) => p.promise));
436
+
437
+ module.exports = { observe, forTodo, add, remove, describe, forget, parse, doneOptions, writeBack, problems: problemsNow, where, apply, cleanRef, flush: write, useTrackers, settled };