create-pmos 0.474.0 → 0.476.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 (61) hide show
  1. package/README.md +5 -3
  2. package/bin/create-pmos.js +23 -1
  3. package/install.ps1 +2 -1
  4. package/install.sh +6 -1
  5. package/package.json +27 -33
  6. package/payload/KIT-VERSION +1 -1
  7. package/payload/planning/evals/eval-calibration.md +1 -1
  8. package/payload/planning/okrs/health-budgets.md +1 -1
  9. package/payload/state/discoveries.md +1 -1
  10. package/workspace/README.md +1 -1
  11. package/workspace/bin/pmos.js +1 -1
  12. package/workspace/changelog.json +26 -0
  13. package/workspace/fixtures/fake-claude-onboard.js +48 -0
  14. package/workspace/guide/briefing-premium.md +2 -7
  15. package/workspace/guide/claude-proposes.md +5 -1
  16. package/workspace/guide/index.md +2 -2
  17. package/workspace/guide/launcher.md +14 -32
  18. package/workspace/guide/layout.md +1 -1
  19. package/workspace/guide/settings.md +12 -3
  20. package/workspace/guide/welcome.md +64 -21
  21. package/workspace/lib/claude-readiness.js +143 -0
  22. package/workspace/lib/engine/calendar-import.js +5 -0
  23. package/workspace/lib/freshness.js +5 -3
  24. package/workspace/lib/launcher-cli.js +83 -8
  25. package/workspace/lib/onboarding-progress.js +36 -0
  26. package/workspace/lib/project-onboard.js +363 -0
  27. package/workspace/lib/proposals.js +4 -3
  28. package/workspace/lib/route-modules.js +3 -0
  29. package/workspace/lib/routes-grill.js +70 -0
  30. package/workspace/lib/routes-onboard.js +188 -0
  31. package/workspace/lib/routes-onboarding.js +5 -4
  32. package/workspace/lib/routes-proposals.js +8 -6
  33. package/workspace/lib/routes-setup.js +88 -0
  34. package/workspace/package-lock.json +2 -2
  35. package/workspace/package.json +1 -1
  36. package/workspace/project-onboard-flow-test.js +135 -0
  37. package/workspace/public/pm/cozy-claude-setup.js +90 -0
  38. package/workspace/public/pm/cozy-ev.css +6 -0
  39. package/workspace/public/pm/cozy-insights.css +2 -0
  40. package/workspace/public/pm/cozy-onboard.css +60 -0
  41. package/workspace/public/pm/cozy-onboard.js +226 -0
  42. package/workspace/public/pm/cozy-settings.js +35 -5
  43. package/workspace/public/pm/cozy-today.css +3 -0
  44. package/workspace/public/pm/grill-words.js +53 -0
  45. package/workspace/public/pm/home-app.js +41 -1
  46. package/workspace/public/pm/home-today.js +3 -1
  47. package/workspace/public/pm/ini-props.js +41 -8
  48. package/workspace/public/pm/ini-view.css +62 -37
  49. package/workspace/public/pm/premium-first.js +1 -1
  50. package/workspace/public/pm/premium-insights.js +43 -5
  51. package/workspace/public/pm/premium-welcome-model.js +1 -1
  52. package/workspace/public/pm/premium-welcome.js +107 -62
  53. package/workspace/public/pm/premium.css +16 -0
  54. package/workspace/public/pm/setup-checklist.js +22 -0
  55. package/workspace/public/premium.html +1 -0
  56. package/workspace/server.js +28 -6
  57. package/workspace/skills/calendar-sync.skill +1 -1
  58. package/workspace/test-files.json +6 -3
  59. package/workspace/test-lists/briefing-premium.json +1 -3
  60. package/workspace/test-lists/claude-onboarding-build.json +9 -0
  61. package/workspace/premium-welcome-test.js +0 -219
@@ -0,0 +1,188 @@
1
+ 'use strict';
2
+ /* routes-onboard.js — the project-first onboarding conversation (initiative claude-onboarding-build).
3
+ *
4
+ * These routes work BEFORE any project is registered: they are bound to no workspace. Every press is the PM's own page press
5
+ * (launch nonce + a `pm:` actor), progress lives in the runtime state directory (never in a repository), and no credential
6
+ * is read or stored. Claude is run only through the verified binding of the profile the PM tested (claudeSetup.bound).
7
+ *
8
+ * GET /api/onboard/state progress, the Claude profiles and their check state
9
+ * POST /api/onboard/own make the separate PMOS profile
10
+ * POST /api/onboard/login { profile } open the sign-in session of exactly that profile
11
+ * POST /api/onboard/check { profile } the bounded, tool-free check (uses a little account allowance)
12
+ * POST /api/onboard/project { name, team, jira, link, description }
13
+ * POST /api/onboard/folder { mode: new|existing, root?, parent? } (+ { pick: true } opens the native chooser)
14
+ * POST /api/onboard/discover the verified profile's connectors, no model call
15
+ * POST /api/onboard/search { sources: [id], local: bool } read-only search of the ticked sources
16
+ * POST /api/onboard/review { fields, jira } the PM's edits to the draft
17
+ * POST /api/onboard/init initialize or reuse, register, open in My Work (resumable)
18
+ * POST /api/onboard/reset start again (the folder and anything written stay)
19
+ */
20
+ const fs = require('fs');
21
+ const isDirSafe = (d) => { try { return fs.statSync(d).isDirectory(); } catch { return false; } };
22
+ const path = require('path');
23
+ const crypto = require('crypto');
24
+ const guard = require('./pm-guard.js');
25
+ const P = require('./project-onboard.js');
26
+
27
+ function file(ctx) { return path.join(ctx.runtimeDir, 'onboarding', 'project.json'); }
28
+ function journal(ctx) { return path.join(ctx.runtimeDir, 'onboarding', 'project-init.json'); }
29
+ function read(ctx) { try { const v = JSON.parse(fs.readFileSync(file(ctx), 'utf8')); return v && typeof v === 'object' ? v : {}; } catch { return {}; } }
30
+ function write(ctx, v) {
31
+ const f = file(ctx); fs.mkdirSync(path.dirname(f), { recursive: true, mode: 0o700 });
32
+ const tmp = f + '.' + crypto.randomBytes(6).toString('hex') + '.tmp';
33
+ try { fs.writeFileSync(tmp, JSON.stringify({ ...v, updated_at: new Date().toISOString() }) + '\n', { mode: 0o600, flag: 'wx' }); fs.renameSync(tmp, f); }
34
+ finally { try { fs.unlinkSync(tmp); } catch {} }
35
+ return v;
36
+ }
37
+ const str = (v, n) => String(v == null ? '' : v).replace(/[\u0000-\u001f\u007f]+/g, ' ').trim().slice(0, n);
38
+
39
+ /** The verified binding, only when it is the profile the conversation tested and nothing about it changed since. */
40
+ function verified(ctx, st) {
41
+ if (!st.profile || !ctx.claudeSetup.bound) return null;
42
+ const b = ctx.claudeSetup.bound(st.profile);
43
+ return b && b.fingerprint === st.fingerprint ? b : null;
44
+ }
45
+ /** Results bound to an older profile or binding are dropped, so a changed login can never reuse them. */
46
+ function fresh(ctx, st) {
47
+ const b = verified(ctx, st);
48
+ const next = { ...st };
49
+ if (!b) { delete next.discovered; delete next.found; }
50
+ else {
51
+ if (next.discovered && next.discovered.fingerprint !== b.fingerprint) delete next.discovered;
52
+ if (next.found && next.found.fingerprint !== b.fingerprint) delete next.found;
53
+ }
54
+ return { st: next, bound: b };
55
+ }
56
+ function view(ctx) {
57
+ const { st, bound } = fresh(ctx, read(ctx));
58
+ const ws = st.done && st.done.ws && ctx.getWs(st.done.ws);
59
+ return { ok: true, progress: { ...st, verified: !!bound, done: ws ? st.done : null }, claude: ctx.claudeSetup.list(), platform: process.platform,
60
+ // a project the PM already has: a registered workspace with PMOS in it, or with the planning/ folder a PMOS workspace keeps its records in
61
+ has_projects: (ctx.workspaceList ? ctx.workspaceList() : []).some((w) => w && w.root && (!!P.pmosIn(w.root) || isDirSafe(path.join(w.root, 'planning')))) };
62
+ }
63
+
64
+ async function handle(req, res, url, ctx) {
65
+ const m = /^\/api\/onboard\/(state|own|login|check|project|folder|discover|search|review|init|reset)$/.exec(url.pathname);
66
+ if (!m) return false;
67
+ const send = (body, code = 200) => { ctx.json(res, body, code); return true; };
68
+ if (!ctx.claudeSetup) return send({ ok: false, error: 'Claude setup is unavailable.' }, 503);
69
+ const verb = m[1];
70
+ if (verb === 'state') return req.method === 'GET' ? send(view(ctx)) : send({ ok: false, error: 'GET only' }, 405);
71
+ if (req.method !== 'POST') return send({ ok: false, error: 'POST only' }, 405);
72
+ const got = await ctx.readJson(req); if (!got.ok) return send({ ok: false, error: 'Invalid JSON.' }, 400);
73
+ const b = got.body || {}, g = guard.requirePagePress(req, b);
74
+ if (!g.ok) return send({ ok: false, error: g.error }, g.status);
75
+ if (!g.actor || !/^pm:/.test(g.actor.by)) return send({ ok: false, error: 'Set up a project from the PMOS page.' }, 403);
76
+ let st = read(ctx);
77
+ try {
78
+ if (verb === 'reset') { write(ctx, {}); try { fs.unlinkSync(journal(ctx)); } catch {} return send(view(ctx)); }
79
+ if (verb === 'own') return send(ctx.claudeSetup.ensureOwn());
80
+ if (verb === 'login') {
81
+ const dir = path.join(ctx.runtimeDir, 'onboarding', 'signin'); fs.mkdirSync(dir, { recursive: true });
82
+ const r = ctx.claudeSetup.login(b.profile, null, 'login', dir);
83
+ if (r.ok) write(ctx, { ...st, profile: r.profile, fingerprint: null });
84
+ return send(r);
85
+ }
86
+ if (verb === 'check') {
87
+ if (!ctx.claudeSetup.candidate(b.profile)) return send({ ok: false, state: 'profile_missing', message: 'That Claude login is not available. Choose one explicitly.' });
88
+ const r = await ctx.claudeSetup.check(b.profile);
89
+ const bound = r.ok && ctx.claudeSetup.bound(r.profile);
90
+ // A new check of another login, or a failed check, drops everything bound to the old one.
91
+ const keep = bound && st.profile === r.profile && st.fingerprint === bound.fingerprint;
92
+ write(ctx, { ...(keep ? st : { project: st.project, folder: st.folder }), profile: r.profile || b.profile, fingerprint: bound ? bound.fingerprint : null, checked: { state: r.state, at: r.checked_at || null } });
93
+ return send({ ...view(ctx), ...r });
94
+ }
95
+ const bound = verified(ctx, st);
96
+ if (!bound) return send({ ok: false, error: 'Test the selected Claude login first.', need: 'check' }, 409);
97
+ if (verb === 'project') {
98
+ const name = str(b.name, 120);
99
+ if (!name) return send({ ok: false, error: 'Give the product or project a name.' }, 400);
100
+ const project = { name, team: str(b.team, 120), jira: str(b.jira, 20).toUpperCase().replace(/[^A-Z0-9_]/g, ''), link: str(b.link, 500), description: str(b.description, 1000) };
101
+ const next = { ...st, project };
102
+ if (next.folder && next.folder.mode === 'new' && !next.folder.chosen) next.folder = { ...next.folder, ...P.proposeFolder(next.folder.parent, name) };
103
+ delete next.found;
104
+ write(ctx, next); return send(view(ctx));
105
+ }
106
+ if (!st.project) return send({ ok: false, error: 'Tell me about the project first.', need: 'project' }, 409);
107
+ if (verb === 'folder') {
108
+ let root = b.root ? str(b.root, 1000) : null, parent = b.parent ? str(b.parent, 1000) : null;
109
+ if (b.pick && ctx.pickFolder) {
110
+ const r = await ctx.pickFolder(b.mode === 'new' ? parent : root);
111
+ if (r.unsupported) return send({ ok: false, unsupported: true, error: 'This computer has no folder chooser. Type the folder path instead.' });
112
+ if (r.cancelled || !r.path) return send({ ok: false, cancelled: true });
113
+ if (b.mode === 'new') parent = r.path; else root = r.path;
114
+ }
115
+ if (b.mode === 'new') {
116
+ const pr = P.proposeFolder(parent, st.project.name);
117
+ if (!pr.ok) return send(pr, 400);
118
+ const facts = P.folderFacts(pr.parent);
119
+ write(ctx, { ...st, folder: { mode: 'new', root: pr.root, parent: pr.parent, chosen: !!parent, parent_in_git: !!(facts.ok && facts.git) } });
120
+ return send(view(ctx));
121
+ }
122
+ if (b.mode !== 'existing' || !root) return send({ ok: false, error: 'Choose a folder.' }, 400);
123
+ const facts = P.folderFacts(root);
124
+ if (!facts.ok) return send(facts, 400);
125
+ if (!facts.exists) return send({ ok: false, error: 'That folder does not exist. Choose another, or make a new one.' }, 400);
126
+ write(ctx, { ...st, folder: { mode: 'existing', root: facts.root, facts, chosen: true } });
127
+ return send(view(ctx));
128
+ }
129
+ if (verb === 'discover') {
130
+ const r = await P.discover({ bound });
131
+ if (!r.ok) return send(r);
132
+ const next = { ...st, discovered: { fingerprint: bound.fingerprint, at: new Date().toISOString(), sources: r.sources } };
133
+ delete next.found; delete next.reviewed;
134
+ write(ctx, next);
135
+ return send(view(ctx));
136
+ }
137
+ if (verb === 'search') {
138
+ const all = (st.discovered && st.discovered.sources) || [];
139
+ const picked = all.filter((s) => Array.isArray(b.sources) && b.sources.includes(s.id) && s.status === 'connected');
140
+ const local = b.local !== false && st.folder && st.folder.mode === 'existing';
141
+ if (!picked.length && !local) return send({ ok: false, error: 'Tick at least one source, or continue with your own description.' }, 400);
142
+ let found = { ok: true, sources: [], findings: [], jira: [], fields: {} };
143
+ if (picked.length) {
144
+ const inv = await P.inventory({ bound, sources: picked });
145
+ found = inv.ok ? await P.search({ bound, project: st.project, sources: picked, tools: inv.tools }) : { ok: false, error: inv.error };
146
+ if (!found.ok) return send({ ok: false, error: found.error });
147
+ }
148
+ const folder = local ? P.folderFacts(st.folder.root) : null;
149
+ if (local) found.sources.push({ id: 'folder', label: 'The folder', state: folder && folder.ok ? (folder.readme || folder.commits ? 'found' : 'empty') : 'failed', count: folder && folder.commits || 0 });
150
+ const jiraMatches = found.jira.length ? found.jira : [];
151
+ const draft = P.draftContext({ project: st.project, folder: folder || (st.folder && st.folder.facts), found });
152
+ write(ctx, { ...st, found: { fingerprint: bound.fingerprint, at: new Date().toISOString(), sources: found.sources, findings: found.findings, jira: jiraMatches }, review: { fields: draft, jira: jiraMatches.length === 1 ? jiraMatches[0].key : null } });
153
+ return send(view(ctx));
154
+ }
155
+ if (verb === 'review') {
156
+ const fields = { ...((st.review && st.review.fields) || P.draftContext({ project: st.project, folder: st.folder && st.folder.facts, found: null })) };
157
+ for (const k of ['name', 'purpose', 'team', 'owner', 'timeline', 'goals']) {
158
+ if (!(b.fields && k in b.fields)) continue;
159
+ const v = str(b.fields[k], 400);
160
+ fields[k] = v ? (fields[k] && fields[k].value === v ? fields[k] : { value: v, source: 'you' }) : null;
161
+ }
162
+ const matches = (st.found && st.found.jira) || [];
163
+ let jira = st.review && st.review.jira;
164
+ if ('jira' in b) jira = b.jira === null || b.jira === 'none' ? 'none' : (matches.some((j) => j.key === b.jira) ? b.jira : jira);
165
+ write(ctx, { ...st, review: { fields, jira }, reviewed: true });
166
+ return send(view(ctx));
167
+ }
168
+ if (verb === 'init') {
169
+ if (!st.folder) return send({ ok: false, error: 'Choose where the project lives first.', need: 'folder' }, 409);
170
+ const matches = (st.found && st.found.jira) || [];
171
+ const jiraKey = st.review && st.review.jira;
172
+ if (matches.length > 1 && !jiraKey) return send({ ok: false, error: 'Choose which Jira project this is, or Neither.', need: 'jira' }, 409);
173
+ const fields = (st.review && st.review.fields) || P.draftContext({ project: st.project, folder: st.folder.facts, found: null });
174
+ const jira = jiraKey && jiraKey !== 'none' ? (matches.find((j) => j.key === jiraKey) || null) : null;
175
+ const name = (fields.name && fields.name.value) || st.project.name;
176
+ const plan = { mode: st.folder.mode, root: st.folder.root, name, context: { name, fields, jira, sources: (st.found && st.found.findings || []).slice(0, 20) } };
177
+ const r = P.initialize({ plan, journalFile: journal(ctx) });
178
+ if (!r.ok) { write(ctx, { ...st, init: { ok: false, step: r.step, error: r.error, steps: r.journal && r.journal.steps } }); return send({ ...view(ctx), ok: false, error: r.error, step: r.step }); }
179
+ const w = ctx.registerWorkspace(r.root, name);
180
+ if (!w) { write(ctx, { ...st, init: { ok: false, step: 'register', error: 'The project could not be added to My Work.', steps: r.journal.steps } }); return send({ ...view(ctx), ok: false, error: 'The project could not be added to My Work.' }); }
181
+ if (ctx.broadcast) ctx.broadcast({ t: 'focus', ws: w.id });
182
+ write(ctx, { ...st, init: { ok: true, steps: r.journal.steps }, done: { ws: w.id, name, root: r.root, context: r.journal.steps.context && r.journal.steps.context.detail, at: new Date().toISOString() } });
183
+ return send(view(ctx));
184
+ }
185
+ } catch { return send({ ok: false, error: 'This step could not finish. Nothing you had was removed. Try again.' }, 500); }
186
+ return false;
187
+ }
188
+ module.exports = { prefixes: ['/api/onboard'], handle, view };
@@ -64,12 +64,13 @@ function status(ctx, w) {
64
64
  const have = loadScan(dir);
65
65
  const imp = have ? imported(dir) : { boards: 0, initiatives: 0, imports: [], live: false };
66
66
  const state = !have ? 'new' : imp.live ? 'imported' : 'scanned';
67
- // first_run: `pmos` opens Welcome on its own only for a plain folder (no PMOS state folder of its own) that is not imported and
68
- // where the PM did not choose "Not now". A PMOS repository, or a kit tenant, opens the console as before; `pmos welcome` still works.
67
+ // New kit folders still need setup. Existing populated PMOS repositories and previous imports keep opening Home.
69
68
  let ownState = false; try { ownState = typeof ctx.stateDirFor === 'function' && !!ctx.stateDirFor(w); } catch { ownState = false; }
70
69
  const dismissed = fs.existsSync(path.join(dir, 'dismissed.json'));
71
- const first_run = state !== 'imported' && !dismissed && !ownState;
72
- return { status: 200, body: { ok: true, state, first_run, dismissed, scanning: running.has(w.id), scan_id: have ? have.scan.scan_id : null, imported: { boards: imp.boards, initiatives: imp.initiatives }, imports: imp.imports } };
70
+ const setup = require('./onboarding-progress').read(stateRootOf(ctx), w.id);
71
+ const existing = require('./onboarding-progress').hasWork(ctx, w);
72
+ const first_run = !setup.completed && state !== 'imported' && !dismissed && !(ownState && existing);
73
+ return { status: 200, body: { ok: true, state, first_run, dismissed, scanning: running.has(w.id), scan_id: have ? have.scan.scan_id : null, setup, imported: { boards: imp.boards, initiatives: imp.initiatives }, imports: imp.imports } };
73
74
  }
74
75
 
75
76
  /* The scan runs in a child process (scripts/onboarding/scan-worker.js): a large folder takes a minute or more, and the server
@@ -4,7 +4,7 @@
4
4
  * initiative goes through the board's own writer (routes-boards writeAs), so its checks and its ledger line are the route's own. A Jira
5
5
  * ticket is never written: a proposal for one becomes a drafted comment in the outbox (rule 8). A draft plan is never touched (rule 9).
6
6
  *
7
- * GET /api/proposals?ws&board&initiative → { ok, props, found } props: lib/proposals.js viewOf (null: nothing to show)
7
+ * GET /api/proposals?ws&board&initiative[&grill=all] → { ok, props, found } props: lib/proposals.js viewOf (null: nothing to show); grill=all unfolds every grill finding
8
8
  * POST /api/proposals/keep { ws, board, initiative, ids?: [id] | all: true, choices?: { <from>><to>: 'keep' | 'ignore' } }
9
9
  * → { ok, batch, said, counts, props } ✓ one proposal, or ✓ in the header (all: every one Claude is sure of;
10
10
  * Check these and a Jira ticket's comment never ride on it). One batch, one toast, one Undo.
@@ -41,7 +41,7 @@ function stagesOf(ctx, p, ini) {
41
41
  try { const r = RB.initiativeWorkflow(ctx, p.w, ini); if (r.ok) return (r.row.wfStages || []).map((s) => ({ key: s.key, name: s.name })); } catch { /* none */ }
42
42
  return [];
43
43
  }
44
- function view(ctx, p, ini, f) {
44
+ function view(ctx, p, ini, f, o = {}) {
45
45
  const dir = dirOf(ctx, p.w); if (!dir) return null;
46
46
  f = f || TLR.frame(ctx, p.w, p.board);
47
47
  if (!f) return null;
@@ -50,7 +50,7 @@ function view(ctx, p, ini, f) {
50
50
  let linkProps = [];
51
51
  try { const lv = TL.viewOf(LF, ini, { T: f.T, today: todayIso(), limit: f.limit, src: TLR.sourcesOf(p.w.root, ini, f.items) }); linkProps = lv ? lv.proposals : []; } catch { linkProps = []; }
52
52
  const T = new Map(); for (const x of f.items) { if (!x || !(x.uid || x.key)) continue; const t = PR.taskOf(x); T.set(t.uid, t); }
53
- return PR.viewOf(F, ini, { T, today: todayIso(), stages: stagesOf(ctx, p, ini), links, settle: TL.settle, linkProps });
53
+ return PR.viewOf(F, ini, { T, today: todayIso(), stages: stagesOf(ctx, p, ini), links, settle: TL.settle, linkProps, grillAll: !!o.grillAll });
54
54
  }
55
55
  function viewFor(ctx, w, boardId, ini) {
56
56
  const fr = RB.frameFor(ctx, w), board = fr.boards.find((b) => b.id === boardId);
@@ -134,7 +134,9 @@ function applyOne(ctx, p, g, f, ini, x, choices, outbox) {
134
134
  }
135
135
  } else if (x.group === 'grill') {
136
136
  // a grill finding (lib/grill.js): ✓ adds its next step as a task, with the finding and its sources in the notes
137
- const next = x.data && x.data.next;
137
+ // ✎ on the finding: the PM's own words for the next step (choices[id]) replace Claude's
138
+ const own = choices && typeof choices[x.id] === 'string' ? choices[x.id].replace(/\s+/g, ' ').trim().slice(0, 200) : '';
139
+ const next = own || (x.data && x.data.next);
138
140
  if (next) {
139
141
  const r = RB.taskAdd(ctx, { ws: p.w.id, board: p.board.id, initiative: ini, title: String(next).slice(0, 200),
140
142
  notes: [x.title, x.why, source ? 'From ' + source : ''].filter(Boolean).join('\n').slice(0, 1900) }, g);
@@ -208,7 +210,7 @@ const READS = {
208
210
  const ini = url.searchParams.get('initiative') || '';
209
211
  if (!ini) return fail(ctx, res, 400, 'initiative is required');
210
212
  const dir = dirOf(ctx, p.w);
211
- ctx.json(res, { ok: true, props: dir ? view(ctx, p, ini) : null, found: dir ? PR.foundOf(PR.read(dir), ini) : null });
213
+ ctx.json(res, { ok: true, props: dir ? view(ctx, p, ini, null, { grillAll: url.searchParams.get('grill') === 'all' }) : null, found: dir ? PR.foundOf(PR.read(dir), ini) : null });
212
214
  },
213
215
  '/api/proposals/history': (ctx, res, url) => {
214
216
  const p = RB.postFrame(ctx, res, { ws: url.searchParams.get('ws') || null, board: url.searchParams.get('board') || '' });
@@ -228,7 +230,7 @@ const WRITES = {
228
230
  if (!ids.length && body.all !== true) return fail(ctx, res, 400, 'ids names the proposals to keep, or all: true');
229
231
  const f = TLR.frame(ctx, p.w, p.board);
230
232
  if (!f) return fail(ctx, res, 202, 'The board is still being read. Try again in a moment.');
231
- const v = view(ctx, p, ini, f), all = v ? v.groups.flatMap((x) => x.props) : [];
233
+ const v = view(ctx, p, ini, f, { grillAll: true }), all = v ? v.groups.flatMap((x) => x.props) : []; // a folded grill finding can be kept by its id
232
234
  // ✓ in the header keeps all Claude is sure of: Check these, Not placed and Jira-only proposals wait for their own ✓
233
235
  const want = body.all === true ? all.filter((x) => x.section === 'sure') : all.filter((x) => ids.includes(x.id));
234
236
  if (!want.length) return fail(ctx, res, 409, 'Those proposals are no longer open');
@@ -0,0 +1,88 @@
1
+ 'use strict';
2
+ const guard = require('./pm-guard.js');
3
+ const fs = require('fs'), path = require('path');
4
+ const progress = require('./onboarding-progress');
5
+ const freshness = require('./freshness');
6
+ function workspace(ctx, id) { const w = typeof id === 'string' && ctx.getWs(id); return w && w.id === id ? w : null; }
7
+ function sourceStates(ctx, w, p) {
8
+ const rows = ctx.freshness ? ctx.freshness.sources({ id: w.id, root: w.root, repoStateDir: ctx.stateDirFor && ctx.stateDirFor(w) }) : [];
9
+ const sessions = ctx.sessionList ? ctx.sessionList() : [];
10
+ return Object.entries(p.sources || {}).map(([id, r]) => {
11
+ const row = rows.find(x => x.id === id), session = sessions.find(x => x.id === r.session);
12
+ const advanced = row && row.as_of && Date.parse(row.as_of) >= Date.parse(r.started_at);
13
+ const state = advanced && session && session.profile_id === r.profile && session.outcome && session.outcome.ok ? 'complete' : session && (session.outcome && !session.outcome.ok || session.state === 'exited') ? 'failed' : session ? 'reading' : 'interrupted';
14
+ let count = null, preview = [];
15
+ if (state === 'complete') {
16
+ try {
17
+ if (id === 'my-work') { const read = JSON.parse(fs.readFileSync(path.join(ctx.runtimeDir, 'my-work', 'read.json'), 'utf8')); count = read.items.length; preview = read.items.slice(0, 5).map(i => i.title || i.key); }
18
+ else { const read = JSON.parse(fs.readFileSync(path.join(ctx.runtimeDir, 'calendar-import', 'read.json'), 'utf8')); count = read.count; preview = require('./routes-calendar-import').readEvents(ctx.runtimeDir).filter(e => Date.parse(e.fetched_at || '') >= Date.parse(r.started_at)).slice(0, 5).map(e => e.title || e.summary || 'Meeting'); }
19
+ } catch { /* no preview is safer than guessing */ }
20
+ }
21
+ return { id, state, read_at: advanced ? row.as_of : null, session: r.session, profile: r.profile, count, preview };
22
+ });
23
+ }
24
+ function state(ctx, w) {
25
+ const p = progress.read(ctx.runtimeDir, w.id);
26
+ return { ok: true, progress: p, claude: ctx.claudeSetup.list(), sources: sourceStates(ctx, w, p), existing_work: progress.hasWork(ctx, w) };
27
+ }
28
+ async function handle(req, res, url, ctx) {
29
+ const match = /^\/api\/setup\/(state|progress|own|login|check|task|read|finish)$/.exec(url.pathname);
30
+ if (!match) return false;
31
+ const send = (body, code = 200) => { ctx.json(res, body, code); return true; };
32
+ if (!ctx.claudeSetup) return send({ ok: false, error: 'Claude setup is unavailable.' }, 503);
33
+ const verb = match[1];
34
+ if (verb === 'state') {
35
+ if (req.method !== 'GET') return send({ ok: false, error: 'GET only' }, 405);
36
+ const w = workspace(ctx, url.searchParams.get('ws')); return w ? send(state(ctx, w)) : send({ ok: false, error: 'No such workspace.' }, 404);
37
+ }
38
+ if (req.method !== 'POST') return send({ ok: false, error: 'POST only' }, 405);
39
+ const got = await ctx.readJson(req); if (!got.ok) return send({ ok: false, error: 'Invalid JSON.' }, 400);
40
+ const b = got.body || {}, g = guard.requirePagePress(req, b);
41
+ if (!g.ok) return send({ ok: false, error: g.error }, g.status);
42
+ if (!g.actor || !/^pm:/.test(g.actor.by)) return send({ ok: false, error: 'Use setup from the workspace page.' }, 403);
43
+ const w = workspace(ctx, b.ws); if (!w) return send({ ok: false, error: 'No such workspace.' }, 404);
44
+ try {
45
+ if (verb === 'own') return send(ctx.claudeSetup.ensureOwn());
46
+ if (verb === 'login') return send(ctx.claudeSetup.login(b.profile, w.id, b.purpose));
47
+ if (verb === 'check') return send(await ctx.claudeSetup.check(b.profile));
48
+ if (verb === 'progress') {
49
+ if (!progress.STEPS.includes(b.step)) return send({ ok: false, error: 'Choose a setup step.' }, 400);
50
+ const patch = { step: b.step };
51
+ if (typeof b.manual === 'boolean') patch.manual = b.manual;
52
+ if (typeof b.profile === 'string' && ctx.claudeSetup.candidate(b.profile)) patch.profile = b.profile;
53
+ if (['task', 'folder', 'sources'].includes(b.review)) patch.review = b.review;
54
+ if (b.draft && typeof b.draft.title === 'string') patch.draft = { title: b.draft.title.slice(0, 500), due: String(b.draft.due || '').slice(0, 10), request_id: String(b.draft.request_id || '').slice(0, 80) };
55
+ return send({ ok: true, progress: progress.save(ctx.runtimeDir, w.id, patch) });
56
+ }
57
+ if (verb === 'task') {
58
+ const item = progress.task(ctx, w, b);
59
+ return send({ ok: true, item, progress: progress.save(ctx.runtimeDir, w.id, { step: 'found', item, task_request_id: b.request_id, work_added: true, completed: false }) });
60
+ }
61
+ if (verb === 'read') {
62
+ if (!ctx.claudeSetup.status().ready) return send({ ok: false, error: 'Check and use a Claude profile before reading a work tool.' }, 409);
63
+ const src = freshness.SOURCES.find(s => s.id === b.source && ['calendar', 'my-work'].includes(s.id));
64
+ if (!src) return send({ ok: false, error: 'Choose Jira or Calendar.' }, 400);
65
+ const p = progress.read(ctx.runtimeDir, w.id), old = (p.sources || {})[src.id];
66
+ if (old && sourceStates(ctx, w, p).find(s => s.id === src.id && s.state === 'reading')) return send({ ok: true, joined: true });
67
+ const started_at = new Date().toISOString(), r = ctx.startSkill(w.id, src.skill, src.label + ' · setup read');
68
+ if (!r.ok) return send({ ok: false, error: 'The read could not start. Open this profile’s sign-in session and check its source permissions.' }, 409);
69
+ progress.save(ctx.runtimeDir, w.id, { sources: { ...p.sources, [src.id]: { session: r.session, profile: ctx.claudeSetup.selected(), started_at } } });
70
+ return send({ ok: true, session: r.session });
71
+ }
72
+ if (verb === 'finish') {
73
+ const p = progress.read(ctx.runtimeDir, w.id), ob = require('./routes-onboarding');
74
+ const scan = ob.status(ctx, w).body;
75
+ const completedSources = sourceStates(ctx, w, p).filter(s => s.state === 'complete');
76
+ const sourceComplete = completedSources.length > 0;
77
+ const scanned = scan.state === 'scanned' || scan.state === 'imported';
78
+ if (!p.work_added && !scanned && !sourceComplete) return send({ ok: false, error: 'Add a task or finish a folder or source read first. You can explore Home without completing setup.' }, 409);
79
+ if (scan.state === 'scanned') {
80
+ const structure = ob.structureRoute(ctx, w);
81
+ if (!b.skip_import && structure.body && structure.body.boards && structure.body.boards.some(x => x.initiatives && x.initiatives.length)) return send({ ok: false, error: 'Confirm the folder import, or leave it out before finishing.' }, 409);
82
+ }
83
+ return send({ ok: true, progress: progress.save(ctx.runtimeDir, w.id, { completed: true, step: 'found', work_added: !!p.item || scan.imported.initiatives > 0 || completedSources.some(s => s.count > 0), empty_read: !p.item && !scan.imported.initiatives && !completedSources.some(s => s.count > 0) }) });
84
+ }
85
+ } catch (e) { if (/^(Enter a task|Choose a valid due|A task request)/.test(e.message || '')) return send({ ok: false, error: e.message }, 400); return send({ ok: false, error: 'Setup could not save or complete this action. Your earlier work is unchanged. Try again.' }, 500); }
86
+ return false;
87
+ }
88
+ module.exports = { prefixes: ['/api/setup'], handle, state, sourceStates };
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.474.0",
3
+ "version": "0.476.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.474.0",
9
+ "version": "0.476.0",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@anthropic-ai/sdk": "^1.3.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pmos-workspace",
3
- "version": "0.474.0",
3
+ "version": "0.476.0",
4
4
  "private": true,
5
5
  "description": "PMOS Terminal Workspace — local companion hosting real PTYs beside the library and gates (D62)",
6
6
  "license": "MIT",
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+ /* project-onboard-flow-test.js — the project-first setup conversation in the real Home page, against the real server, with a FIXTURE `claude`
4
+ * (fixtures/fake-claude-onboard.js). It proves the plumbing and the page, not a live account: no real sign-in, no real connector.
5
+ * Covers: login gating (a failed test unlocks nothing), the project question, the proposed new folder, connector listing, the read-only
6
+ * search flags, a denied source contributing nothing, two Jira matches needing a choice, a real kit install in a temporary folder, the project
7
+ * shown in My Work with next steps, reuse of an existing PMOS folder, and desktop and phone widths. SHOTS=<dir> saves screenshots. */
8
+ const fs = require('fs');
9
+ const os = require('os');
10
+ const path = require('path');
11
+ const assert = require('assert/strict');
12
+ const { spawn } = require('child_process');
13
+ const { findBrowser } = require('./lib/find-browser');
14
+ const T = require('./test-run').configure({ name: 'project-onboard-flow' });
15
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pmos-onboard-flow-'));
16
+ const HOME = path.join(tmp, 'home'), BIN = path.join(tmp, 'bin'), LOG = path.join(tmp, 'claude-argv.log'), MODE = path.join(tmp, 'mode');
17
+ fs.mkdirSync(HOME); fs.mkdirSync(BIN);
18
+ fs.writeFileSync(path.join(BIN, 'claude'), `#!/bin/sh\nexec "${process.execPath}" "${path.join(__dirname, 'fixtures', 'fake-claude-onboard.js')}" "$@"\n`, { mode: 0o755 });
19
+ fs.writeFileSync(MODE, 'signed_out');
20
+ const SHOTS = process.env.SHOTS || null;
21
+ let n = 0, srv, browser;
22
+ const step = async (label, fn) => { await fn(); n++; console.log('✓ ' + label); };
23
+ const shot = async (p, name) => { if (SHOTS) { fs.mkdirSync(SHOTS, { recursive: true }); await p.screenshot({ path: path.join(SHOTS, name + '.png') }); } };
24
+ (async () => {
25
+ const { chromium } = require('playwright-core');
26
+ srv = spawn(process.execPath, [path.join(__dirname, 'server.js')], { cwd: __dirname, stdio: 'ignore',
27
+ env: T.env({ PMOS_WS_PORT: String(T.PORT), HOME, USERPROFILE: HOME, PATH: BIN + path.delimiter + process.env.PATH, FAKE_CLAUDE_LOG: LOG, FAKE_CLAUDE_MODE_FILE: MODE, CLAUDE_CONFIG_DIR: '' }) });
28
+ await T.waitForServer(T.BASE);
29
+ browser = await chromium.launch({ executablePath: findBrowser() });
30
+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });
31
+ const p = await ctx.newPage();
32
+ const errs = []; p.on('pageerror', (e) => errs.push(e.message));
33
+ const log = () => fs.existsSync(LOG) ? fs.readFileSync(LOG, 'utf8').trim().split('\n').map((l) => JSON.parse(l)) : [];
34
+ const btn = (label) => p.locator('#obChat button', { hasText: label }).first();
35
+
36
+ await step('The old Welcome page opens the Home conversation, not the three-step wizard', async () => {
37
+ await p.goto(T.BASE + '/premium-welcome.html?ws=x&step=sources');
38
+ assert.match(p.url(), /\/premium\.html\?onboard=1$/);
39
+ await p.waitForSelector('#obChat .ob-card');
40
+ assert(await p.locator('#hmChat').isHidden(), 'one chat at a time'); assert(await p.locator('#hmList').isVisible(), 'the list stays');
41
+ });
42
+ await step('A failed login test is honest and unlocks nothing', async () => {
43
+ await shot(p, 'onboard-1-connect');
44
+ await btn('Test this login').click();
45
+ await p.waitForSelector('#obChat .ob-bad');
46
+ assert.match(await p.locator('#obChat .ob-bad').innerText(), /won’t switch to a different account/);
47
+ assert(await p.locator('#obChat textarea').isDisabled(), 'no project question before a passing test');
48
+ });
49
+ await step('A passing test of that login asks about the project', async () => {
50
+ fs.writeFileSync(MODE, 'ready');
51
+ await btn('Test this login').click();
52
+ await p.waitForSelector('#obChat .ob-good');
53
+ assert(await p.locator('#obChat textarea').isEnabled());
54
+ const check = log().find((a) => a.includes('-p') && a.includes('--output-format') && a[a.indexOf('--output-format') + 1] === 'json');
55
+ assert(check && check.includes('--safe-mode') && check[check.indexOf('--tools') + 1] === '', 'the test is the bounded, tool-free check');
56
+ await shot(p, 'onboard-2-tested');
57
+ });
58
+ await step('The answer names the project and proposes a new folder that overwrites nothing', async () => {
59
+ await p.fill('#obChat textarea', 'Checkout redesign, payments team. Jira key PAY.');
60
+ await p.keyboard.press('Enter');
61
+ await p.waitForSelector('#obChat input[name="ob-folder"][value="new"]');
62
+ const card = await p.locator('#obChat .ob-card').first().innerText();
63
+ assert(card.includes(path.join(HOME, 'PMOS', 'checkout-redesign')), card);
64
+ assert(!fs.existsSync(path.join(HOME, 'PMOS', 'checkout-redesign')), 'nothing created before the confirmation');
65
+ });
66
+ await step('Sources come from the verified login, with no model call, and nothing is searched before the press', async () => {
67
+ const before = log().length;
68
+ await btn('Show what I can read').click();
69
+ await p.waitForSelector('#obChat input[name="ob-src"]');
70
+ assert.deepEqual(log().slice(before), [['mcp', 'list']]);
71
+ assert(await p.locator('#obChat input[name="ob-src"][value="claude.ai Google Drive"]').isDisabled(), 'a source that needs sign-in cannot be ticked');
72
+ await shot(p, 'onboard-3-folder-sources');
73
+ });
74
+ await step('The search is read-only by its flags; a denied source contributes nothing; two Jira matches ask for a choice', async () => {
75
+ await btn('Search, read-only').click();
76
+ await p.waitForSelector('#obChat input[name="ob-jira"]', { timeout: 30000 });
77
+ const run = log().find((a) => a.includes('--allowedTools'));
78
+ const at = (f) => run[run.indexOf(f) + 1];
79
+ assert.equal(at('--permission-mode'), 'dontAsk'); assert.equal(at('--tools'), ''); assert.deepEqual(JSON.parse(at('--settings')), { disableAllHooks: true });
80
+ const allow = at('--allowedTools').split(',');
81
+ assert.deepEqual(allow.sort(), ['mcp__claude_ai_Atlassian__getVisibleJiraProjects', 'mcp__claude_ai_Atlassian__searchJiraIssuesUsingJql', 'mcp__claude_ai_Slack__slack_search_public']);
82
+ const text = await p.locator('#obChat').innerText();
83
+ assert.match(text, /Atlassian · 3 found/); assert.match(text, /Slack · couldn’t read/); assert(!text.includes('#checkout'), 'nothing from the denied source');
84
+ assert.equal(await p.locator('#obChat input[name="owner"]').inputValue(), '', 'a field cited from a failed source stays empty');
85
+ assert.equal(await p.locator('#obChat input[name="purpose"]').inputValue(), 'Reduce checkout drop-off on mobile');
86
+ await shot(p, 'onboard-4-review');
87
+ });
88
+ await step('Setup waits for the Jira choice, then installs PMOS for real and opens the project in My Work', async () => {
89
+ await btn('Set up PMOS in').click();
90
+ await p.waitForFunction(() => /Choose which Jira project/.test((document.querySelector('#obChat .ob-live') || {}).innerText || ''), null, { timeout: 15000 });
91
+ await p.check('#obChat input[name="ob-jira"][value="PAY"]');
92
+ await p.fill('#obChat input[name="goals"]', 'Raise mobile checkout conversion');
93
+ await btn('Set up PMOS in').click();
94
+ try { await p.waitForURL(/onboarded=1/, { timeout: 60000 }); } catch (e) { await shot(p, 'onboard-x-stuck'); console.log(await p.locator('#obChat').innerText()); throw e; }
95
+ await p.waitForSelector('#obChat .ob-done');
96
+ const root = path.join(HOME, 'PMOS', 'checkout-redesign');
97
+ for (const f of ['.git', 'pmos/AGENTS.md', 'pmos/state', 'CLAUDE.md', '.pmos-profile']) assert(fs.existsSync(path.join(root, f)), f);
98
+ const ctxText = fs.readFileSync(path.join(root, 'pmos', 'planning', 'project-context.md'), 'utf8');
99
+ assert.match(ctxText, /Reduce checkout drop-off on mobile \(source: Atlassian, Checkout brief/); assert.match(ctxText, /Raise mobile checkout conversion \(source: the PM\)/);
100
+ assert.match(ctxText, /Jira:\*\* PAY · Payments Platform/); assert(!/Invented Person/.test(ctxText));
101
+ await p.waitForFunction(() => /Checkout redesign/i.test(document.querySelector('#hmList').innerText), null, { timeout: 15000 });
102
+ assert(await p.locator('#obChat a.hm-chip').count() >= 3, 'a next action, not an empty success');
103
+ await shot(p, 'onboard-5-done');
104
+ const ph = await (await browser.newContext({ viewport: { width: 390, height: 844 } })).newPage();
105
+ await ph.goto(p.url()); await ph.waitForSelector('#obChat .ob-done'); await shot(ph, 'onboard-5-done-phone');
106
+ assert(await ph.locator('#obChat').isVisible()); await ph.close();
107
+ });
108
+ await step('The same folder again is reused as existing PMOS, never reinstalled', async () => {
109
+ const root = path.join(HOME, 'PMOS', 'checkout-redesign');
110
+ fs.writeFileSync(path.join(root, 'pmos', 'AGENTS.md'), '# edited by the PM');
111
+ const h = await T.pressHeaders(T.BASE);
112
+ await fetch(T.BASE + '/api/onboard/reset', { method: 'POST', headers: h, body: '{}' });
113
+ const ph = await (await browser.newContext({ viewport: { width: 390, height: 844 } })).newPage();
114
+ await ph.goto(T.BASE + '/premium.html?onboard=1');
115
+ await ph.locator('#obChat button', { hasText: 'Test this login' }).click();
116
+ await ph.waitForSelector('#obChat .ob-good');
117
+ await ph.fill('#obChat textarea', `Checkout redesign. The folder is ${root}`); await ph.keyboard.press('Enter');
118
+ await ph.waitForSelector('#obChat input[name="ob-folder"][value="existing"]');
119
+ assert.match(await ph.locator('#obChat .ob-card').first().innerText(), /PMOS is already here/);
120
+ await shot(ph, 'onboard-6-existing-pmos-phone');
121
+ await ph.locator('#obChat button', { hasText: 'Show what I can read' }).click();
122
+ await ph.locator('#obChat button', { hasText: 'Skip, use my description' }).click();
123
+ await Promise.all([ph.waitForURL(/onboarded=1/, { timeout: 60000 }), ph.locator('#obChat button', { hasText: 'Open PMOS in' }).click()]);
124
+ await ph.waitForSelector('#obChat .ob-done');
125
+ assert.match(await ph.locator('#obChat .ob-done').innerText(), /reused as it is/);
126
+ assert.equal(fs.readFileSync(path.join(root, 'pmos', 'AGENTS.md'), 'utf8'), '# edited by the PM');
127
+ await ph.close();
128
+ });
129
+ assert.deepEqual(errs, []);
130
+ console.log(n + ' passed (fixture claude; no live account or connector was used)');
131
+ })().catch((e) => { console.error(e); process.exitCode = 1; }).finally(async () => {
132
+ try { if (browser) await browser.close(); } catch {}
133
+ try { srv && srv.kill('SIGKILL'); } catch {}
134
+ T.killTmux(); fs.rmSync(tmp, { recursive: true, force: true });
135
+ });
@@ -0,0 +1,90 @@
1
+ /* Shared profile-specific sign-in and verification for Welcome and Settings. */
2
+ import { pmGet, pmPost, pageNonce } from './http.js';
3
+ const esc = v => String(v == null ? '' : v).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
4
+ const scripts = new Map();
5
+ function load(src) {
6
+ if (!scripts.has(src)) scripts.set(src, new Promise((resolve, reject) => { const s = document.createElement('script'); s.src = src; s.onload = resolve; s.onerror = () => { scripts.delete(src); reject(new Error('The sign-in terminal could not load. Reload and try again.')); }; document.head.append(s); }));
7
+ return scripts.get(src);
8
+ }
9
+ export async function signInTerminal(el, sid) {
10
+ if (!/^sess-\d+$/.test(sid)) return () => {};
11
+ if (!document.querySelector('[data-setup-xterm]')) { const l = document.createElement('link'); l.rel = 'stylesheet'; l.href = '/vendor/xterm.css'; l.dataset.setupXterm = '1'; document.head.append(l); }
12
+ await load('/vendor/xterm.js'); await load('/vendor/addon-fit.js'); await load('/vendor/addon-web-links.js');
13
+ if (!el.isConnected) return () => {};
14
+ const term = new window.Terminal({ cursorBlink: true, scrollback: 1500 });
15
+ const fit = new window.FitAddon.FitAddon(); term.loadAddon(fit);
16
+ term.loadAddon(new window.WebLinksAddon.WebLinksAddon((_e, uri) => { if (/^https?:\/\//i.test(uri)) window.open(uri, '_blank', 'noopener,noreferrer'); }));
17
+ term.open(el); fit.fit();
18
+ const sock = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/?pmos-nonce=' + encodeURIComponent(pageNonce()));
19
+ const send = data => { if (sock.readyState === WebSocket.OPEN) sock.send(JSON.stringify(data)); };
20
+ sock.addEventListener('open', () => send({ t: 'attach', id: sid }));
21
+ sock.addEventListener('message', e => {
22
+ if (!el.isConnected) { cleanup(); return; }
23
+ let m; try { m = JSON.parse(e.data); } catch { return; }
24
+ if (m.t === 'attached') { term.reset(); if (m.buf) term.write(m.buf); send({ t: 'resize', id: sid, cols: term.cols, rows: term.rows }); }
25
+ if (m.t === 'data' && m.id === sid) term.write(m.data);
26
+ if (m.t === 'error') term.write('\r\nThe session could not be attached. Reopen sign-in.\r\n');
27
+ });
28
+ const input = term.onData(data => send({ t: 'input', id: sid, data }));
29
+ const resize = new ResizeObserver(() => { if (!el.isConnected) return cleanup(); fit.fit(); send({ t: 'resize', id: sid, cols: term.cols, rows: term.rows }); }); resize.observe(el);
30
+ let closed = false;
31
+ function cleanup() { if (closed) return; closed = true; resize.disconnect(); input.dispose(); sock.close(); term.dispose(); }
32
+ term.focus(); return cleanup;
33
+ }
34
+ export function mountClaudeSetup(el, { ws, onReady = () => {}, onManual = null } = {}) {
35
+ let data = null, profile = null, note = '', busy = false, session = null, disposeTerm = null, disposed = false;
36
+ const post = (verb, body = {}) => pmPost('/api/setup/' + verb, { ws, ...body });
37
+ const stopTerm = () => { if (disposeTerm) { disposeTerm(); disposeTerm = null; } };
38
+ async function refresh() {
39
+ const r = await pmGet('/api/setup/state?ws=' + encodeURIComponent(ws));
40
+ if (disposed || !el.isConnected) return;
41
+ if (!r || !r.ok) { note = (r && r.error) || 'Setup could not be read. Reload and try again.'; draw(); return; }
42
+ data = r.claude; profile = profile || r.progress.profile || data.selected; draw();
43
+ }
44
+ function draw() {
45
+ if (disposed || !el.isConnected) return;
46
+ stopTerm();
47
+ const status = data && data.status;
48
+ const choices = data ? data.profiles : [];
49
+ const missing = profile && !choices.some(p => p.id === profile);
50
+ el.innerHTML = `<div class="cs-panel"><p>Sign in through Claude using the setup you want PMOS to use. Your password stays with Claude.</p>
51
+ <p>Keep PMOS separate from account switches in your usual terminal, or use an existing setup.</p>
52
+ <button type="button" class="wl-btn alt" data-cs="own"${busy ? ' disabled' : ''}>Set up a separate PMOS login</button>
53
+ <label class="cs-label">Existing Claude setup<select data-cs-profile${busy || !data ? ' disabled' : ''}>${missing ? '<option selected value="' + esc(profile) + '">Saved profile unavailable</option>' : ''}${choices.map(p => `<option value="${esc(p.id)}"${p.id === profile ? ' selected' : ''}>${esc(p.label)}</option>`).join('')}</select></label>
54
+ <p role="status" aria-live="polite">${esc(note || (status && status.profile === profile ? status.message + (status.checked_at ? ' Last checked ' + new Date(status.checked_at).toLocaleString() + '.' : '') : 'This setup has not been checked.'))}</p>
55
+ ${data && data.discovery_failed ? '<p role="alert">Some profile information could not be read. Your usual login is still a separate candidate, not a verified account.</p>' : ''}
56
+ <div class="cs-actions"><button type="button" class="wl-btn" data-cs="check"${busy || !data || missing ? ' disabled' : ''}>${busy ? 'Working…' : 'Check and use this profile'}</button><button type="button" class="wl-btn alt" data-cs="login"${busy || !data || missing ? ' disabled' : ''}>Sign in to this profile</button></div>
57
+ <p class="note">Checking makes a small Claude request and may use your account allowance. It does not scan your project.</p>
58
+ ${session ? '<p>Complete Claude’s sign-in below. Type <code>/login</code> here if needed. Then select <b>Check and use this profile</b>.</p><div class="cs-term" aria-label="Claude sign-in terminal"></div>' : ''}
59
+ ${onManual ? '<button type="button" class="wl-btn quiet" data-cs="manual">Continue without Claude</button>' : ''}</div>`;
60
+ if (session) signInTerminal(el.querySelector('.cs-term'), session).then(stop => { if (disposed || !el.isConnected) stop(); else disposeTerm = stop; }).catch(e => { note = e.message; session = null; draw(); });
61
+ }
62
+ el.addEventListener('change', async e => {
63
+ if (!e.target.matches('[data-cs-profile]')) return;
64
+ profile = e.target.value; session = null; note = 'This setup has not been checked.'; draw();
65
+ await post('progress', { step: 'claude', profile });
66
+ });
67
+ el.addEventListener('click', async e => {
68
+ const b = e.target.closest('[data-cs]'); if (!b || b.disabled || busy) return;
69
+ const act = b.dataset.cs;
70
+ if (act === 'manual') { await onManual(); return; }
71
+ busy = true; note = act === 'check' ? 'Checking Claude access…' : 'Opening the selected sign-in setup…'; draw();
72
+ try {
73
+ if (act === 'own') {
74
+ const own = await post('own'); if (!own || !own.ok) throw new Error((own && own.error) || 'The PMOS profile could not be created.');
75
+ profile = own.id;
76
+ }
77
+ const r = await post(act === 'check' ? 'check' : 'login', { profile });
78
+ if (!r || !r.ok) { note = (r && (r.message || r.error)) || 'This action did not finish. Try again.'; }
79
+ else {
80
+ profile = r.profile || profile; note = r.message || 'Sign in below, then check Claude access.';
81
+ if (r.session) session = r.session;
82
+ await post('progress', { step: 'claude', profile });
83
+ if (act === 'check') { session = null; await onReady(r); }
84
+ }
85
+ } catch { note = 'This action could not finish. Check your connection and try again.'; }
86
+ busy = false; if (el.isConnected) await refresh();
87
+ });
88
+ refresh();
89
+ return () => { disposed = true; stopTerm(); };
90
+ }
@@ -313,3 +313,9 @@
313
313
  .nv-row b { flex: none; font-weight: 800; }
314
314
  .nv-row span { flex: 1; min-width: 0; text-align: right; color: var(--cz-ink2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
315
315
  .nv-row svg { flex: none; color: var(--cz-ink3); }
316
+ /* Settings › Claude's checks (canvas GrillEntry): what this month used of the credit, as one quiet bar */
317
+ .cz .ev-gcap { flex-wrap: wrap; }
318
+ .cz .ev-gcap .ev-small { flex: 1 1 160px; }
319
+ .cz .ev-gbar { position: relative; flex: 1 1 200px; height: 8px; border-radius: 4px; background: var(--cz-well2, var(--cz-well)); overflow: hidden; }
320
+ .cz .ev-gbar i { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 4px; background: var(--cz-blue); }
321
+ @media (max-width: 600px) { .cz .ev-trow:has(.ev-seg[aria-label="Grill by itself"]), .cz .ev-trow:has(.ev-seg[aria-label="Monthly credit for checks"]) { flex-wrap: wrap; } }