create-pmos 0.473.0 → 0.475.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 (51) 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 -27
  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/index.md +2 -2
  16. package/workspace/guide/launcher.md +14 -32
  17. package/workspace/guide/layout.md +1 -1
  18. package/workspace/guide/published-board.md +1 -1
  19. package/workspace/guide/settings.md +3 -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/route-modules.js +2 -0
  28. package/workspace/lib/routes-onboard.js +188 -0
  29. package/workspace/lib/routes-onboarding.js +5 -4
  30. package/workspace/lib/routes-setup.js +88 -0
  31. package/workspace/package-lock.json +2 -2
  32. package/workspace/package.json +1 -1
  33. package/workspace/project-onboard-flow-test.js +135 -0
  34. package/workspace/public/pm/cozy-claude-setup.js +90 -0
  35. package/workspace/public/pm/cozy-onboard.css +60 -0
  36. package/workspace/public/pm/cozy-onboard.js +226 -0
  37. package/workspace/public/pm/cozy-settings.js +8 -2
  38. package/workspace/public/pm/home-app.js +10 -0
  39. package/workspace/public/pm/premium-first.js +1 -1
  40. package/workspace/public/pm/premium-welcome-model.js +1 -1
  41. package/workspace/public/pm/premium-welcome.js +107 -62
  42. package/workspace/public/pm/premium.css +16 -0
  43. package/workspace/public/pm/readonly.js +1 -1
  44. package/workspace/public/pm/setup-checklist.js +22 -0
  45. package/workspace/public/premium.html +1 -0
  46. package/workspace/server.js +28 -6
  47. package/workspace/skills/calendar-sync.skill +1 -1
  48. package/workspace/test-files.json +6 -3
  49. package/workspace/test-lists/briefing-premium.json +1 -3
  50. package/workspace/test-lists/claude-onboarding-build.json +9 -0
  51. package/workspace/premium-welcome-test.js +0 -219
@@ -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.473.0",
3
+ "version": "0.475.0",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "pmos-workspace",
9
- "version": "0.473.0",
9
+ "version": "0.475.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.473.0",
3
+ "version": "0.475.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
+ }
@@ -0,0 +1,60 @@
1
+ /* cozy-onboard.css — the project-first setup conversation in the Home chat (initiative claude-onboarding-build). Only Cozy tokens; the turns,
2
+ * cards, buttons, chips and composer are the Home chat's own (cozy-home.css, cozy-today.css). */
3
+ body.ob-on #hmChat[hidden] { display: none; }
4
+ .ob-chat .hm-log { gap: 18px; }
5
+ .ob-chat .hm-ab { display: flex; flex-direction: column; gap: 10px; min-width: 0; flex: 1; }
6
+ .ob-chat .hm-ab > p { margin: 0; line-height: 1.5; }
7
+ .ob-hello { margin: 24px auto 8px; display: flex; flex-direction: column; align-items: center; gap: 6px; }
8
+ .ob-hello p { margin: 0; }
9
+ .ob-hello b { color: var(--cz-ink); font-size: var(--fs-5); }
10
+ .ob-card { display: flex; flex-direction: column; gap: 2px; padding: 6px; max-width: 720px; }
11
+ .ob-opt { display: flex; gap: 10px; align-items: flex-start; padding: 10px 12px; border-radius: 12px; cursor: pointer; min-height: 44px; box-sizing: border-box; }
12
+ .ob-opt.on { background: var(--cz-bluebg); }
13
+ .ob-opt.off { cursor: default; color: var(--cz-ink3); }
14
+ .ob-opt input { margin: 3px 0 0; accent-color: var(--cz-solid); flex: none; }
15
+ .ob-opt span { display: flex; flex-direction: column; gap: 2px; min-width: 0; font-size: var(--fs-3); }
16
+ .ob-opt em { font-style: normal; font-size: var(--fs-2); color: var(--cz-ink2); }
17
+ .ob-opt code, .ob-chat code { font-size: var(--fs-2); word-break: break-all; }
18
+ .ob-row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; padding: 6px 4px 2px; }
19
+ .ob-row a.hm-chip { text-decoration: none; }
20
+ .ob-note { margin: 0; font-size: var(--fs-2); color: var(--cz-ink3); padding: 0 4px; }
21
+ .ob-sub { margin: 0; font-size: var(--fs-2); color: var(--cz-ink2); }
22
+ .ob-live { text-align: center; }
23
+ .ob-good, .ob-bad { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; border-radius: 14px; padding: 10px 14px; max-width: 720px; box-sizing: border-box; }
24
+ .ob-good { background: var(--cz-okbg); color: var(--cz-ok); }
25
+ .ob-good span { color: var(--cz-ink2); font-size: var(--fs-2); }
26
+ .ob-bad { background: var(--cz-redbg); color: var(--cz-red); flex-direction: column; align-items: flex-start; gap: 4px; }
27
+ .ob-bad span { color: var(--cz-ink2); font-size: var(--fs-2); }
28
+ .ob-srcs { display: flex; gap: 6px; flex-wrap: wrap; }
29
+ .ob-src { font-size: var(--fs-2); font-weight: 700; border-radius: 999px; padding: 3px 10px; background: var(--cz-bluebg); color: var(--cz-blueink); }
30
+ .ob-src.empty { background: var(--cz-well); color: var(--cz-ink2); }
31
+ .ob-src.failed { background: var(--cz-redbg); color: var(--cz-red); }
32
+ .ob-ctx { padding: 12px 16px 8px; gap: 0; }
33
+ .ob-ctx > p { margin: 0 0 6px; font-size: var(--fs-3); }
34
+ .ob-fld { display: grid; grid-template-columns: 130px minmax(0, 1fr) auto; gap: 12px; align-items: center; padding: 7px 0; border-top: 1px solid var(--cz-hair); }
35
+ .ob-fld b { font-size: var(--fs-2); color: var(--cz-ink2); }
36
+ .ob-fld input { font: inherit; font-size: var(--fs-3); color: var(--cz-ink); border: 0; border-radius: 10px; background: var(--cz-well); padding: 8px 10px; width: 100%; box-sizing: border-box; min-height: 36px; }
37
+ .ob-tag { font-size: var(--fs-1); font-weight: 700; border-radius: 999px; padding: 2px 9px; white-space: nowrap; background: var(--cz-bluebg); color: var(--cz-blueink); }
38
+ .ob-tag a { color: inherit; }
39
+ .ob-tag.you { background: var(--cz-well); color: var(--cz-ink2); }
40
+ .ob-tag.miss { background: var(--cz-riskbg, var(--cz-well)); color: var(--cz-ink2); }
41
+ .ob-done { list-style: none; margin: 0; padding: 10px 16px; display: flex; flex-direction: column; gap: 6px; max-width: 720px; }
42
+ .ob-done li { display: flex; gap: 10px; align-items: center; font-size: var(--fs-3); }
43
+ .ob-done li svg { color: var(--cz-ok); flex: none; }
44
+ .ob-path { display: flex; gap: 8px; align-items: flex-end; padding: 6px 4px; flex-wrap: wrap; }
45
+ .ob-path .ut-field { flex: 1 1 260px; }
46
+ .ob-path .ut-field input { min-height: 40px; }
47
+ .ob-term { height: 280px; border-radius: 12px; overflow: hidden; background: var(--term-bg); }
48
+ @media (max-width: 760px) {
49
+ body.cz-home.ob-on.hm-plist .ob-chat { display: flex; padding: 16px 16px 0; }
50
+ body.cz-home.ob-on.hm-plist .hm-list { display: none; }
51
+ body.cz-home.ob-on.hm-plist .ob-chat .hm-foot { padding-bottom: 84px; } /* the floating menu button sits over the corner */
52
+ .ob-fld { grid-template-columns: minmax(0, 1fr) auto; }
53
+ .ob-fld input { grid-column: 1 / -1; grid-row: 2; }
54
+ .ob-chat .ut-btn { min-height: 44px; }
55
+ }
56
+ /* Home's Claude repair card (setup-checklist.js): only when the saved login failed */
57
+ .cs-checklist { margin: 0 0 12px; display: flex; flex-direction: column; gap: 6px; }
58
+ .cs-checklist[hidden] { display: none; }
59
+ .cs-checklist p { margin: 0; font-size: var(--fs-2); color: var(--cz-ink2); }
60
+ .cs-checklist .ut-btn { align-self: flex-start; text-decoration: none; }