spequi 0.1.7 → 0.1.9

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 (45) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +27 -12
  3. package/bin/spequi.mjs +5 -3
  4. package/docs/agent-workflow.md +28 -4
  5. package/package.json +1 -1
  6. package/public/app.css +52 -2
  7. package/public/app.js +133 -64
  8. package/public/diff.css +62 -39
  9. package/public/index.html +230 -189
  10. package/public/requests.js +54 -27
  11. package/public/review.css +21 -4
  12. package/public/review.js +85 -50
  13. package/public/session.js +34 -20
  14. package/public/studio.css +191 -33
  15. package/public/studio.js +1 -1
  16. package/public/workflow.js +92 -6
  17. package/skills/spequi/SKILL.md +29 -10
  18. package/src/analytics.mjs +50 -16
  19. package/src/branches.mjs +52 -0
  20. package/src/commands.mjs +4 -41
  21. package/src/comment-controls.mjs +1 -1
  22. package/src/comment-view.mjs +6 -5
  23. package/src/creation-view.mjs +10 -3
  24. package/src/diff-view.mjs +3 -3
  25. package/src/document-view.mjs +9 -2
  26. package/src/drafts.mjs +19 -4
  27. package/src/feedback.mjs +2 -0
  28. package/src/jobs.mjs +71 -18
  29. package/src/lifecycle.mjs +12 -9
  30. package/src/plan-git.mjs +129 -0
  31. package/src/preview-view.mjs +14 -9
  32. package/src/previews.mjs +4 -1
  33. package/src/project.mjs +3 -2
  34. package/src/requests.mjs +1 -1
  35. package/src/review-images.mjs +51 -0
  36. package/src/review-store.mjs +16 -16
  37. package/src/review-view.mjs +3 -2
  38. package/src/server.mjs +54 -20
  39. package/src/source-preview-view.mjs +4 -4
  40. package/src/spec-context-view.mjs +3 -3
  41. package/src/spec-context.mjs +11 -8
  42. package/src/studio-view.mjs +64 -27
  43. package/src/updates.mjs +82 -0
  44. package/src/verification.mjs +6 -0
  45. package/src/views.mjs +53 -15
@@ -1,10 +1,36 @@
1
1
  (() => {
2
2
  const panel = () => document.getElementById('requests-panel');
3
3
  const workspace = () => document.getElementById('workspace');
4
- const labels = { stalled: 'No recent update', queued: 'Queued', running: 'Working', 'awaiting-input': 'Answer needed', completed: 'Completed', failed: 'Failed', cancelled: 'Cancelled' };
5
- const actions = { 'start-plan': 'New spec', 'plan-next': 'Next artifact', 'revise-plan': 'Spec revision', preview: 'Implementation preview', verify: 'Verification', explore: 'Question', 'update-specs': 'Review feedback', impact: 'File impact', archive: 'Archive' };
4
+ const labels = { stalled: 'In progress · check CLI', queued: 'Queued', running: 'Working', 'awaiting-input': 'Answer needed', completed: 'Completed', failed: 'Failed', cancelled: 'Cancelled' };
5
+ const actions = { 'commit-message': 'Commit message', 'start-plan': 'New spec', 'plan-next': 'Next artifact', 'revise-plan': 'Spec revision', preview: 'Implementation preview', verify: 'Verification', explore: 'Question', 'update-specs': 'Review feedback', impact: 'File impact', archive: 'Archive' };
6
6
  let page = 1, pages = 1, opener, activityPending, activityAgain = false, agent = {}, listGeneration = 0;
7
7
  const saves = new Map(), saved = new Map(), saveFailures = new Map(), deletedDrafts = new Set();
8
+ const notificationKey = `spequi-request-notifications:${location.host}`;
9
+ let notificationStates = new Map(), notificationBaseline = false;
10
+ const openedAt = Date.now();
11
+ try { notificationStates = new Map(JSON.parse(sessionStorage.getItem(notificationKey) || '[]')); notificationBaseline = notificationStates.size > 0; } catch {}
12
+ function notifyTransitions(jobs = []) {
13
+ for (const job of jobs) {
14
+ const previous = notificationStates.get(job.id);
15
+ const changed = previous !== job.status && (previous || notificationBaseline && Date.parse(job.updatedAt) >= openedAt);
16
+ if (changed && ['completed', 'failed', 'awaiting-input'].includes(job.status)) {
17
+ const title = job.status === 'completed' ? job.action === 'preview' ? 'Your file diff is ready' : 'Your request is complete' : job.status === 'awaiting-input' ? 'Your agent needs an answer' : 'Your request needs attention';
18
+ const message = `${title}${job.change ? ` · ${job.change}` : ''}.`;
19
+ const href = openLink(job).getAttribute('href');
20
+ document.dispatchEvent(new window.CustomEvent('spequi-toast', { detail: { message, href } }));
21
+ if ('Notification' in window && Notification.permission === 'granted' && document.visibilityState !== 'visible') {
22
+ try {
23
+ const notice = new Notification('Spequi', { body: message, tag: `spequi-${job.id}-${job.status}` });
24
+ notice.onclick = () => { window.focus(); location.assign(href); notice.close(); };
25
+ } catch {}
26
+ }
27
+ }
28
+ notificationStates.set(job.id, job.status);
29
+ }
30
+ notificationBaseline = true;
31
+ const retained = jobs.map(job => [job.id, job.status]);
32
+ try { sessionStorage.setItem(notificationKey, JSON.stringify(retained)); } catch {}
33
+ }
8
34
  async function api(url, payload) {
9
35
  const response = await fetch(url, payload === undefined ? { headers: { Accept: 'application/json' } } : { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]')?.content || '' }, body: JSON.stringify(payload), ...(url === '/api/drafts' ? { keepalive: true } : {}) });
10
36
  const result = await response.json();
@@ -34,25 +60,19 @@
34
60
  for (const toggle of document.querySelectorAll('[data-requests-toggle]')) toggle.setAttribute('aria-expanded', 'false');
35
61
  }
36
62
  function positionPanel() {
37
- const drawer = panel(), anchor = document.querySelector('.topbar [data-requests-toggle]') || opener;
38
- if (!drawer || drawer.hidden || !anchor?.getBoundingClientRect || !window.innerWidth) return;
39
- const trigger = anchor.getBoundingClientRect(), header = anchor.closest('.topbar')?.getBoundingClientRect();
40
- const gutter = window.innerWidth <= 520 ? 8 : 16, width = drawer.getBoundingClientRect().width;
41
- const left = Math.max(gutter, Math.min(trigger.left, window.innerWidth - width - gutter));
42
- const top = Math.max(gutter, Math.max(trigger.bottom, header?.bottom || 0) + 8);
43
- drawer.style.left = `${Math.round(left)}px`; drawer.style.right = 'auto'; drawer.style.top = `${Math.round(top)}px`;
44
- drawer.style.maxHeight = `${Math.max(0, Math.min(640, window.innerHeight - top - gutter))}px`;
63
+ const drawer = panel();
64
+ if (drawer && !drawer.hidden) window.spequiPositionDropdown?.(drawer, document.querySelector('.topbar [data-requests-toggle]') || opener);
45
65
  }
46
66
  function openLink(job) {
47
- const stage = ['preview', 'impact'].includes(job.action) ? 'implement' : ['verify', 'sync-specs', 'archive'].includes(job.action) ? 'finish' : 'shape';
67
+ const stage = ['preview', 'impact'].includes(job.action) ? 'implement' : ['verify', 'sync-specs', 'archive', 'commit-message'].includes(job.action) ? 'finish' : 'shape';
48
68
  const query = job.action === 'start-plan' ? { view: 'studio', new: '1', creation: job.id } : {
49
- change: job.change || '', view: stage === 'shape' ? 'studio' : job.status === 'completed' && ['preview', 'impact'].includes(job.action) ? 'preview' : 'workflow', ...(stage === 'shape' ? { stage } : {}),
69
+ change: job.change || '', view: stage === 'shape' ? 'studio' : ['preview', 'impact'].includes(job.action) ? 'preview' : 'workflow', ...(stage === 'shape' ? { stage } : {}),
50
70
  ...(job.status === 'awaiting-input' ? { pane: 'conversation' } : {}),
51
71
  ...(job.action === 'preview' ? { job: job.id } : {}),
52
72
  ...(job.action === 'impact' ? { job: job.reviewPreview, file: job.reviewFile } : {})
53
73
  };
54
- const link = node('a', job.status === 'awaiting-input' ? 'Reply' : 'Open', 'button request-open');
55
- link.setAttribute('aria-label', job.status === 'awaiting-input' ? 'Reply to request' : 'Open request');
74
+ const link = node('a', job.status === 'awaiting-input' ? 'Open change' : 'Open', 'button request-open');
75
+ link.setAttribute('aria-label', job.status === 'awaiting-input' ? 'Open this change’s conversation' : 'Open request');
56
76
  link.append(requestIcon('open')); link.href = '/?' + new URLSearchParams(query); return link;
57
77
  }
58
78
  function button(text, action, id) {
@@ -83,7 +103,7 @@
83
103
  state.append(action);
84
104
  return state;
85
105
  }
86
- function requestRow(job, history, expanded) {
106
+ function requestRow(job, history, expanded, replies = new Map()) {
87
107
  const row = node('section', undefined, 'request-row'), heading = node('div', undefined, 'request-heading');
88
108
  row.dataset.requestId = job.id; row.dataset.requestKey = job.groupKey || job.id;
89
109
  const status = node('span', labels[job.stalled ? 'stalled' : job.status] || job.status, 'request-state'); status.dataset.state = job.stalled ? 'stalled' : job.status;
@@ -92,13 +112,13 @@
92
112
  if (job.groupCount > 1) heading.append(node('small', `${job.groupCount} actions`, 'request-group-count'));
93
113
  heading.append(status);
94
114
  row.append(heading);
115
+ const question = job.status === 'awaiting-input' ? job.questions?.at(-1) : null;
116
+ if (question && !question.answeredAt) row.append(replies.get(`${job.id}:${question.id}`) || window.spequiQuestionForm(job, question, 'inbox'));
95
117
  const detail = node('details'); detail.open = expanded.has(job.groupKey || job.id);
96
118
  const summary = node('summary'); summary.append(node('span', job.message || 'View request details', 'request-summary-text'), requestIcon('chevron')); detail.append(summary);
97
- const body = node('div', undefined, 'request-detail-body'), log = node('ol');
98
- for (const item of job.logs?.slice(-30) || []) log.append(node('li', item.message));
99
- if (log.children.length) body.append(node('h3', 'Activity'), log);
119
+ const body = node('div', undefined, 'request-detail-body');
100
120
  if (job.result) body.append(node('h3', 'Result'), node('p', job.result, 'request-result'));
101
- if (job.stalled) body.prepend(node('p', 'The agent may still be working. You can check back later.', 'request-status-note'));
121
+ if (job.stalled) body.prepend(node('p', 'This can take a few minutes. The result will appear here when ready. Your CLI may be waiting for a permission or another action.', 'request-status-note'));
102
122
  detail.append(body); row.append(detail);
103
123
  const footer = node('div', undefined, 'request-footer'), meta = node('div', undefined, 'request-meta');
104
124
  const kind = node('span', actions[job.action] || job.action, 'request-kind'); kind.title = kind.textContent;
@@ -129,6 +149,7 @@
129
149
  const expanded = new Set([...list.querySelectorAll('.request-row details[open]')].map(detail => detail.closest('.request-row').dataset.requestKey));
130
150
  const focused = list.contains(document.activeElement) ? document.activeElement : null;
131
151
  const focus = focused ? { id: focused.closest('.request-row')?.dataset.requestKey, recent: focused.hasAttribute('data-request-recent-toggle'), action: focused.dataset.requestAction, tag: focused.tagName.toLowerCase(), empty: focused.hasAttribute('data-request-empty-action') } : null;
152
+ const replies = new Map([...list.querySelectorAll('[data-question-key]')].map(item => [item.dataset.questionKey, item]));
132
153
  list.replaceChildren();
133
154
  const inbox = status === 'inbox';
134
155
  if (!result.items.length) list.append(emptyRequests(status, Boolean(result.historyTotal)));
@@ -138,21 +159,21 @@
138
159
  section = Boolean(job.needsAttention);
139
160
  list.append(node('h3', section ? 'Needs attention' : 'In progress', 'requests-section-title'));
140
161
  }
141
- list.append(requestRow(job, !inbox, expanded));
162
+ list.append(requestRow(job, !inbox, expanded, replies));
142
163
  }
143
164
  if (inbox && result.recent?.length) {
144
165
  const recent = node('details', undefined, 'requests-recent'); recent.id = 'requests-recent'; recent.open = recentOpen;
145
166
  const summary = node('summary'); summary.setAttribute('data-request-recent-toggle', '');
146
167
  summary.append(node('span', 'Recent'), node('small', String(result.recent.length)), requestIcon('chevron'));
147
168
  recent.append(summary);
148
- for (const job of result.recent) recent.append(requestRow(job, false, expanded));
169
+ for (const job of result.recent) recent.append(requestRow(job, false, expanded, replies));
149
170
  list.append(recent);
150
171
  }
151
172
  list.scrollTop = scroll;
152
173
  if (focus) {
153
174
  const row = [...list.querySelectorAll('.request-row')].find(row => row.dataset.requestKey === focus.id);
154
175
  const control = focus.recent ? list.querySelector('[data-request-recent-toggle]') : focus.empty ? list.querySelector('[data-request-empty-action]') : focus.action ? [...(row?.querySelectorAll('[data-request-action]') || [])].find(control => control.dataset.requestAction === focus.action) : ['summary', 'a'].includes(focus.tag) ? row?.querySelector(focus.tag) : null;
155
- (control || row?.querySelector('summary') || panel().querySelector('[data-request-filter]')).focus({ preventScroll: true });
176
+ (focused?.isConnected ? focused : control || row?.querySelector('summary') || panel().querySelector('[data-request-filter]')).focus({ preventScroll: true });
156
177
  }
157
178
  panel().querySelector('[data-request-pagination]').textContent = `${result.total} ${inbox ? 'in inbox' : result.total === 1 ? 'request' : 'requests'}${pages > 1 ? ` · ${page} of ${pages}` : ''}`;
158
179
  panel().querySelector('footer').hidden = result.total === 0;
@@ -191,12 +212,17 @@
191
212
  const query = new URL(current.dataset.refreshUrl || location.href, location.href);
192
213
  activityPending = (async () => {
193
214
  const result = await api('/api/activity?' + new URLSearchParams({ change: current.dataset.change || '', creation: query.searchParams.get('creation') || '' }));
215
+ notifyTransitions(result.notifications);
216
+ if (agent.observedAt && result.agent.observedAt && result.agent.observedAt < agent.observedAt) { activityAgain = true; return; }
194
217
  agent = result.agent; document.dispatchEvent(new window.CustomEvent('agent-status', { detail: agent }));
195
218
  const attention = result.attention || 0, inboxCount = result.inboxCount ?? attention;
219
+ const answers = result.active.filter(job => job.status === 'awaiting-input').length;
220
+ for (const marker of document.querySelectorAll('[data-request-answer]')) { marker.hidden = !answers; marker.textContent = `${answers} ${answers === 1 ? 'answer needed' : 'answers needed'}`; }
196
221
  const markerLabel = inboxCount ? `${inboxCount} ${inboxCount === 1 ? 'item' : 'items'} in your inbox${attention ? `; ${attention} ${attention === 1 ? 'needs' : 'need'} your attention` : ''}` : 'No pending requests';
197
- for (const count of document.querySelectorAll('[data-request-count]')) { count.textContent = inboxCount; count.hidden = !inboxCount; count.title = markerLabel; }
222
+ for (const count of document.querySelectorAll('[data-request-count]')) { count.textContent = inboxCount; count.hidden = !inboxCount || Boolean(answers); count.title = markerLabel; }
198
223
  for (const toggle of document.querySelectorAll('.topbar [data-requests-toggle]')) {
199
- toggle.title = markerLabel; toggle.setAttribute('aria-label', `Requests. ${markerLabel}`);
224
+ toggle.dataset.answerNeeded = String(Boolean(answers));
225
+ toggle.title = answers ? `${answers} unanswered ${answers === 1 ? 'question' : 'questions'} — open Requests to reply` : markerLabel; toggle.setAttribute('aria-label', `Requests. ${answers ? `${answers} answers needed.` : markerLabel}`);
200
226
  }
201
227
  renderDrafts(result.drafts);
202
228
  for (const status of document.querySelectorAll('[data-job-state]')) status.textContent = labels[result.active.find(job => job.change === status.dataset.jobState)?.status] || '';
@@ -224,7 +250,7 @@
224
250
  const id = form.querySelector('[name="draftId"]')?.value;
225
251
  const stopped = () => deletedDrafts.has(id) || form.dataset.draftSubmitting === 'true' || Boolean(form.dataset.draftSubmitted);
226
252
  if (!id || stopped()) return Promise.resolve();
227
- const payload = { id, change: form.querySelector('[name="change"]').value, message: form.querySelector('[name="message"]').value, planMode: form.querySelector('[name="planMode"]:checked')?.value || 'next' };
253
+ const payload = { id, change: form.querySelector('[name="change"]').value, message: form.querySelector('[name="message"]').value, branch: form.querySelector('[name="branch"]')?.value || '', planMode: form.querySelector('[name="planMode"]:checked')?.value || 'next' };
228
254
  if (!payload.change.trim() && !payload.message.trim()) return Promise.resolve();
229
255
  const signature = JSON.stringify(payload), info = form.querySelector('[data-draft-save-state]');
230
256
  const save = (saves.get(id) || Promise.resolve()).catch(() => {}).then(async () => {
@@ -274,7 +300,7 @@
274
300
  await api(`/api/jobs/${encodeURIComponent(id)}/${action}`, payload);
275
301
  if (action === 'retry' || action === 'dismiss') { feedback(''); document.dispatchEvent(new window.CustomEvent('spequi-toast', { detail: { message: action === 'dismiss' ? 'Dismissed from inbox. History kept.' : 'Retry queued.' } })); }
276
302
  else feedback(action === 'delete' ? 'Request removed.' : 'Request cancelled.');
277
- await Promise.all([activity(), loadRequests()]);
303
+ await Promise.all([activity(), loadRequests(), window.spequiRefreshAgent?.()]);
278
304
  }
279
305
  catch (error) { feedback(error.message, true); }
280
306
  finally { control.disabled = false; }
@@ -283,7 +309,7 @@
283
309
  const toggle = event.target.closest('[data-requests-toggle]');
284
310
  if (toggle) {
285
311
  const visible = panel().hidden; close(); panel().hidden = !visible;
286
- if (visible) { opener = toggle; toggle.setAttribute('aria-expanded', 'true'); positionPanel(); panel().querySelector('[data-requests-close]').focus(); void loadRequests(); }
312
+ if (visible) { if (toggle.dataset.answerNeeded === 'true') { panel().querySelector('[data-request-filter]').value = 'inbox'; page = 1; } opener = toggle; toggle.setAttribute('aria-expanded', 'true'); positionPanel(); panel().querySelector('[data-requests-close]').focus(); void loadRequests(); }
287
313
  return;
288
314
  }
289
315
  if (event.target.closest('[data-requests-close]')) { close(); opener?.focus(); return; }
@@ -318,6 +344,7 @@
318
344
  document.addEventListener('requests-updated', () => { void activity(); void loadRequests(); });
319
345
  document.addEventListener('agent-status', event => {
320
346
  const next = event.detail;
347
+ if (agent.observedAt && next.observedAt && next.observedAt < agent.observedAt) return;
321
348
  const changed = agent.status !== next.status || agent.queue?.active?.id !== next.queue?.active?.id || agent.queue?.active?.ownerConnected !== next.queue?.active?.ownerConnected;
322
349
  agent = next;
323
350
  if (changed) { void activity(); void loadRequests(); }
package/public/review.css CHANGED
@@ -271,9 +271,6 @@
271
271
  @media(max-width:760px){.review-comment-form textarea,.document-discussion textarea,.document-inline-thread textarea,.diff-inline-thread textarea{font-size:16px}.comment-composer-actions button{min-height:36px}}
272
272
 
273
273
  /* Review feedback stays inline; the attached agent is the primary path. */
274
- .review-feedback-actions .review-export{width:32px;min-height:32px;padding:6px;border-color:transparent;background:transparent;color:var(--muted)}
275
- .review-feedback-actions .review-export:hover{background:var(--rail);color:var(--text)}
276
- .review-export-label{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
277
274
  .review-update-hint{margin:0 0 12px;font-size:10px;line-height:1.6;color:var(--muted)}
278
275
  .comment-group-path>small{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;overflow-wrap:normal}
279
276
  .comment-group-count{background:transparent;padding:0;font-size:10px}
@@ -283,4 +280,24 @@
283
280
  .review-comment .comment-source-link{background:transparent;padding:0;border-radius:0;font-size:10px;gap:5px}
284
281
  .review-comment .comment-source-link svg{width:11px;height:11px}
285
282
  .review-comment .saved-comment-thread>.comment-source-context{padding:0 0 8px 18px}
286
- @media(pointer:coarse){.review-feedback-actions .button,.comment-view-filter>button,.review-comment .saved-comment-thread>summary{min-height:44px}.review-feedback-actions .review-export{width:44px}.review-comment .comment-delete{min-height:32px;width:32px}}
283
+ @media(pointer:coarse){.review-feedback-actions .button,.comment-view-filter>button,.review-comment .saved-comment-thread>summary{min-height:44px}.review-comment .comment-delete{min-height:32px;width:32px}}
284
+
285
+ .comment-image-toolbar{display:flex;align-items:center;gap:8px;margin:7px 0 10px;font-size:10px;color:var(--muted)}
286
+ .comment-image-add{display:inline-flex;align-items:center;gap:5px;padding:4px 7px;border:1px solid var(--line);border-radius:var(--radius);background:var(--surface);color:var(--text);font-size:11px;cursor:pointer}
287
+ .comment-image-add svg{width:14px;height:14px}
288
+ .comment-image-drafts{display:flex;flex-wrap:wrap;gap:8px}
289
+ .comment-image-draft{display:flex;flex-direction:column;gap:4px;width:80px}
290
+ .comment-image-draft img{width:80px;height:64px;object-fit:contain;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius)}
291
+ .comment-image-draft button{font-size:10px;padding:2px;border:0;background:transparent;color:var(--muted);cursor:pointer}
292
+ .comment-image{display:inline-flex;flex-direction:column;gap:4px;max-width:240px;margin:8px 8px 8px 0;vertical-align:top;font-size:10px;overflow-wrap:anywhere;color:var(--accent-text)}
293
+ .comment-image img{max-width:100%;max-height:180px;object-fit:contain;border:1px solid var(--line);border-radius:var(--radius)}
294
+ @media(max-width:760px){.comment-image-add,.comment-image-draft button{min-height:36px}.comment-image-toolbar>span{display:none}}
295
+
296
+ .comment-attachment-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-right:auto}
297
+ .comment-attachment-actions>.comment-image-add{min-height:32px}
298
+ .attachment-paste-hint{font-size:11px;color:var(--muted);line-height:1.5}
299
+ .comment-composer-actions{flex-wrap:wrap}
300
+ .comment-image-drafts:empty{display:none}
301
+ .comment-image-draft{width:auto;max-width:160px;padding:6px;border:1px solid var(--line);border-radius:var(--radius)}
302
+ .comment-image-draft>span{font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
303
+ .comment-image>svg{width:24px;height:24px}
package/public/review.js CHANGED
@@ -1,9 +1,9 @@
1
1
  (() => {
2
2
  const drafts = new Map();
3
+ const imageDrafts = new Map(), imageUploads = new Set();
3
4
  const saving = new Set();
4
5
  const deleting = new Set();
5
6
  const deleteMessages = new Map();
6
- const exporting = new Set(), exportMessages = new Map();
7
7
  const updating = new Set(), updateMessages = new Map();
8
8
  const commentViews = new Map(), composerStates = new Map();
9
9
  const inlineTargets = new Map();
@@ -13,6 +13,74 @@
13
13
  const form = () => document.getElementById('review-comment-form');
14
14
  const field = (node, name) => node.querySelector(`[name="${name}"]`);
15
15
  const key = node => `${node.dataset.preview}:${node.dataset.file}`;
16
+ const attachmentForms = () => [...document.querySelectorAll('form[data-attachment-scope]')];
17
+ function renderImageDraft(node) {
18
+ const host = node.querySelector('[data-comment-images]'); if (!host) return;
19
+ const images = imageDrafts.get(key(node)) || [];
20
+ host.replaceChildren();
21
+ for (const image of images) {
22
+ const tile = document.createElement('div'), remove = document.createElement('button');
23
+ tile.className = 'comment-image-draft';
24
+ if (/^image\/(png|jpeg|webp)$/.test(image.type)) {
25
+ const picture = document.createElement('img'); picture.src = image.url; picture.alt = image.name; tile.append(picture);
26
+ }
27
+ const name = document.createElement('span'); name.textContent = image.name; name.title = image.name; tile.append(name);
28
+ remove.type = 'button'; remove.dataset.commentImageRemove = image.id; remove.textContent = 'Remove'; remove.setAttribute('aria-label', `Remove ${image.name}`);
29
+ tile.append(remove); host.append(tile);
30
+ }
31
+ const textarea = node.querySelector('textarea[name=body],textarea[name=message]');
32
+ if (textarea) textarea.required = !images.length;
33
+ node.querySelector('[type=submit]').disabled = saving.has(key(node)) || imageUploads.has(key(node)) || node.getAttribute('aria-busy') === 'true' || node.dataset.attachmentBlocked === 'true';
34
+ }
35
+ window.spequiAttachments = {
36
+ ids: node => (imageDrafts.get(key(node)) || []).map(image => image.id),
37
+ busy: node => imageUploads.has(key(node)),
38
+ clear: node => { imageDrafts.delete(key(node)); renderImageDraft(node); }
39
+ };
40
+ async function uploadImages(node, files) {
41
+ const id = key(node), selected = [...files];
42
+ if (imageUploads.has(id) || saving.has(id) || node.getAttribute('aria-busy') === 'true') return;
43
+ const report = node.querySelector('[data-composer-feedback]');
44
+ if ((imageDrafts.get(id)?.length || 0) + selected.length > 4) { report.textContent = 'Attach up to four files.'; return; }
45
+ imageUploads.add(id); renderImageDraft(node); report.textContent = 'Adding attachments…';
46
+ try {
47
+ for (const file of selected) {
48
+ if (file.size > 5 * 1024 * 1024) throw new Error('Choose files up to 5 MiB each.');
49
+ if (['image/png', 'image/jpeg', 'image/webp'].includes(file.type)) {
50
+ const image = await createImageBitmap(file), pixels = image.width * image.height; image.close();
51
+ if (pixels > 40000000) throw new Error('Choose an image smaller than 40 megapixels.');
52
+ }
53
+ const data = await new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => resolve(reader.result.split(',')[1]); reader.onerror = () => reject(new Error('Could not read this file.')); reader.readAsDataURL(file); });
54
+ const response = await fetch(`/api/reviews/${encodeURIComponent(node.dataset.attachmentScope)}/attachments`, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json', 'X-CSRF-Token': document.querySelector('meta[name=csrf-token]').content }, body: JSON.stringify({ name: file.name, data }) });
55
+ const result = await response.json();
56
+ if (!response.ok || !result.image) throw new Error(result.error || 'Could not upload this file.');
57
+ imageDrafts.set(id, [...imageDrafts.get(id) || [], result.image]);
58
+ }
59
+ report.textContent = '';
60
+ } catch (error) { report.textContent = error.message; }
61
+ finally { imageUploads.delete(id); for (const active of attachmentForms().filter(form => key(form) === id)) { renderImageDraft(active); if (active.id === 'review-comment-form') showSelection(active); } }
62
+ }
63
+ document.addEventListener('paste', event => {
64
+ const node = event.target.closest('form[data-attachment-scope]'); if (!node) return;
65
+ const files = [...event.clipboardData?.files || []];
66
+ if (!files.length) return;
67
+ event.preventDefault();
68
+ const text = event.clipboardData.getData('text/plain'), textarea = event.target.closest('textarea');
69
+ if (text && textarea) { textarea.setRangeText(text.slice(0, Math.max(0, textarea.maxLength - textarea.value.length + textarea.selectionEnd - textarea.selectionStart)), textarea.selectionStart, textarea.selectionEnd, 'end'); textarea.dispatchEvent(new Event('input', { bubbles: true })); }
70
+ void uploadImages(node, files);
71
+ });
72
+ document.addEventListener('change', event => {
73
+ if (!event.target.matches('[data-comment-image-input]')) return;
74
+ const files = [...event.target.files]; event.target.value = '';
75
+ void uploadImages(event.target.closest('form'), files);
76
+ });
77
+ document.addEventListener('click', event => {
78
+ const choose = event.target.closest('[data-comment-image-choose]');
79
+ if (choose) choose.closest('form').querySelector('[data-comment-image-input]').click();
80
+ const remove = event.target.closest('[data-comment-image-remove]');
81
+ if (remove) { const node = remove.closest('form'), id = key(node); imageDrafts.set(id, (imageDrafts.get(id) || []).filter(image => image.id !== remove.dataset.commentImageRemove)); renderImageDraft(node); if (node.id === 'review-comment-form') showSelection(node); }
82
+ });
83
+ document.addEventListener('htmx:afterSwap', () => attachmentForms().forEach(renderImageDraft));
16
84
  function remember() {
17
85
  const node = form(); if (!node) return;
18
86
  drafts.set(key(node), { ...Object.fromEntries(['body', 'side', 'start', 'end'].map(name => [name, field(node, name).value])), ...(node.dataset.sourceHash ? { sourceHash: node.dataset.sourceHash } : {}) });
@@ -34,7 +102,7 @@
34
102
  if (contextRow) contextRow.hidden = Boolean(node.dataset.sourceHash && side === 'file' && !stale && node.closest('[data-document-composer-home]'));
35
103
  const general = document.querySelector('[data-general-document-comment]');
36
104
  if (general) general.hidden = !node.closest('.document-inline-thread') && side === 'file' && !stale;
37
- const draft = field(node, 'body').value.trim().length > 0;
105
+ const draft = field(node, 'body').value.trim().length > 0 || Boolean(imageDrafts.get(key(node))?.length);
38
106
  const label = document.querySelector('[data-composer-label]'), marker = document.querySelector('[data-comment-draft]');
39
107
  if (label) label.textContent = draft ? 'Continue comment' : 'Add a comment';
40
108
  if (marker) marker.hidden = !draft;
@@ -69,7 +137,6 @@
69
137
  function initialize() {
70
138
  restoreDeleteMessages();
71
139
  updateCommentView();
72
- restoreExportState();
73
140
  restoreUpdateState();
74
141
  for (const node of document.querySelectorAll('[data-delete-comment]')) if (deleting.has(`${node.dataset.reviewScope}:${node.dataset.commentId}`)) setDeleteBusy(node.dataset.reviewScope, node.dataset.commentId, true);
75
142
  const node = form(); if (!node) return;
@@ -79,11 +146,12 @@
79
146
  for (const name of ['body', 'side', 'start', 'end']) field(node, name).value = saved[name];
80
147
  if (saved.sourceHash) node.dataset.sourceHash = saved.sourceHash;
81
148
  }
149
+ renderImageDraft(node);
82
150
  placeDocumentComposer(inlineTargets.get(key(node)));
83
151
  placeDiffComposer(diffTargets.get(key(node)));
84
152
  showSelection(node);
85
153
  setComposer(node, composerStates.get(key(node)) ?? (Boolean(saved?.body) || document.getElementById('review-comment-composer').hasAttribute('data-default-open')));
86
- node.querySelector('[type="submit"]').disabled = saving.has(key(node));
154
+ node.querySelector('[type="submit"]').disabled = saving.has(key(node)) || imageUploads.has(key(node));
87
155
  const query = new URLSearchParams(location.search);
88
156
  const line = Number(query.get('line')), side = query.get('side'), commentID = query.get('comment');
89
157
  const locationKey = `${key(node)}:${side}:${line}:${commentID || ''}`;
@@ -149,28 +217,14 @@
149
217
  document.addEventListener('htmx:beforeRequest', remember);
150
218
  document.addEventListener('htmx:afterSwap', initialize);
151
219
  document.addEventListener('toggle', event => { if (event.target.id === 'review-comment-composer' && form()) composerStates.set(key(form()), event.target.hasAttribute('open')); }, true);
152
- function feedback(message, error = false, downloadUrl = '') {
220
+ function feedback(message, error = false) {
153
221
  const target = document.getElementById('review-feedback'); if (!target) return;
154
222
  const paragraph = document.createElement('p');
155
223
  paragraph.className = error ? 'error-message' : 'success-message'; paragraph.textContent = message;
156
- if (downloadUrl) {
157
- const link = document.createElement('a'); link.href = downloadUrl; link.download = 'openspec-review-feedback.md'; link.textContent = 'Download Markdown';
158
- paragraph.append(' ', link);
159
- }
160
224
  target.replaceChildren(paragraph);
161
225
  const local = form()?.querySelector('[data-composer-feedback]');
162
226
  if (local) local.replaceChildren(paragraph.cloneNode(true));
163
227
  }
164
- function restoreExportState() {
165
- const section = document.getElementById('review-comments'); if (!section) return;
166
- const node = section.querySelector('[data-feedback-export]'); if (!node) return;
167
- const busy = exporting.has(section.dataset.preview);
168
- if (busy) node.setAttribute('aria-busy', 'true'); else node.removeAttribute('aria-busy');
169
- node.querySelector('[type="submit"]').disabled = busy || !section.querySelector('.review-comment');
170
- node.querySelector('[data-export-label]').textContent = busy ? 'Exporting…' : 'Export .md';
171
- const state = exportMessages.get(section.dataset.preview);
172
- if (state) feedback(state.message, state.error, state.downloadUrl);
173
- }
174
228
  function restoreUpdateState() {
175
229
  const node = document.querySelector('[data-spec-update]'); if (!node) return;
176
230
  const busy = updating.has(node.dataset.change);
@@ -178,7 +232,7 @@
178
232
  node.querySelector('button').disabled = busy || node.dataset.blocked === 'true';
179
233
  node.querySelector('[data-update-label]').textContent = busy ? 'Queuing…' : node.dataset.pendingStatus === 'awaiting-input' ? 'Reply in Build' : node.dataset.pendingStatus === 'running' ? 'Updating…' : node.dataset.pendingStatus === 'queued' ? 'Queued' : 'Update spec';
180
234
  const state = updateMessages.get(node.dataset.change);
181
- if (state) feedback(state.message, state.error, state.downloadUrl);
235
+ if (state) feedback(state.message, state.error);
182
236
  }
183
237
  document.addEventListener('submit', async event => {
184
238
  const node = event.target.closest('[data-spec-update]'); if (!node) return;
@@ -194,12 +248,12 @@
194
248
  const response = await fetch(node.getAttribute('action'), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json', 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content }, body: '' });
195
249
  const result = response.headers.get('content-type')?.includes('application/json') ? await response.json() : {};
196
250
  if (!response.ok) throw new Error(result.error || (response.status === 403 ? 'Local session expired. Reload the viewer and retry the update.' : 'Could not queue the planning update. Retry Update spec.'));
197
- const { update, exported } = result;
198
- if (!update || update.change !== change || update.reviewPreview !== preview || update.feedbackId !== exported?.id || exported.preview !== preview || update.status !== 'queued' || exported.downloadUrl !== `/api/reviews/${preview}/feedback/${exported.id}`) throw new Error('Could not confirm the planning update. Reload to check its status before retrying.');
251
+ const { update, feedback: snapshot } = result;
252
+ if (!update || update.change !== change || update.reviewPreview !== preview || update.feedbackId !== snapshot?.id || snapshot.preview !== preview || update.status !== 'queued') throw new Error('Could not confirm the planning update. Reload to check its status before retrying.');
199
253
  // Preserve the accepted request if a subsequent workspace refresh fails.
200
254
  node.dataset.blocked = 'true';
201
255
  node.dataset.pendingStatus = 'queued';
202
- updateMessages.delete(change); exportMessages.delete(preview);
256
+ updateMessages.delete(change);
203
257
  await refreshComments(preview, '', { change, outcome: 'Planning update queued' });
204
258
  document.dispatchEvent(new window.CustomEvent('spequi-toast', { detail: { message: 'Spec update queued for your agent.' } }));
205
259
  } catch (error) {
@@ -212,27 +266,6 @@
212
266
  }
213
267
  }
214
268
  }, true);
215
- // Export owns its POST and download. An HTMX swap/live refresh must not
216
- // consume the response or discard the only link before it can be used.
217
- document.addEventListener('submit', async event => {
218
- const node = event.target.closest('[data-feedback-export]'); if (!node) return;
219
- event.preventDefault(); event.stopImmediatePropagation();
220
- const preview = node.dataset.preview; if (exporting.has(preview)) return;
221
- exporting.add(preview);
222
- exportMessages.set(preview, { message: 'Preparing feedback document…' }); restoreExportState();
223
- try {
224
- const response = await fetch(node.getAttribute('action'), { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json', 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content }, body: '' });
225
- const result = response.headers.get('content-type')?.includes('application/json') ? await response.json() : {};
226
- if (!response.ok) throw new Error(result.error || (response.status === 403 ? 'Local session expired. Reload the viewer and retry the export.' : 'Could not export feedback. Check the server connection and retry.'));
227
- const exported = result.exported;
228
- if (!exported || exported.preview !== preview || typeof exported.id !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,100}$/.test(exported.id) || exported.downloadUrl !== `/api/reviews/${preview}/feedback/${exported.id}`) throw new Error('Could not confirm the exported document. Retry the export.');
229
- exportMessages.set(preview, { message: 'Feedback exported. If the download did not start, use this link.', downloadUrl: exported.downloadUrl });
230
- const download = document.createElement('a'); download.href = exported.downloadUrl; download.download = 'openspec-review-feedback.md'; download.hidden = true;
231
- document.body.append(download); download.click(); download.remove();
232
- } catch (error) {
233
- exportMessages.set(preview, { message: error instanceof TypeError ? 'Could not reach the viewer. Check that the server is running and retry the export.' : error.message, error: true });
234
- } finally { exporting.delete(preview); restoreExportState(); }
235
- }, true);
236
269
  async function refreshComments(preview, savedFile, { change = '', outcome = 'Comment saved', revealComment = '' } = {}) {
237
270
  const current = form(), workspace = document.getElementById('workspace');
238
271
  if (!workspace?.dataset.refreshUrl || (change ? workspace.dataset.change !== change : !current || current.dataset.preview !== preview)) return;
@@ -244,8 +277,8 @@
244
277
  if (generation !== refreshGeneration || document.getElementById('workspace') !== workspace || workspace.dataset.refreshUrl !== url) return;
245
278
  const updated = html.getElementById('review-comments');
246
279
  if (!updated) throw new Error(`${outcome}. Reload this view to refresh the comment list.`);
247
- const inspector = document.getElementById('review-details'), top = inspector.scrollTop;
248
- const reader = document.querySelector('.reader'), readerTop = reader.scrollTop, readerLeft = reader.scrollLeft;
280
+ const inspector = document.getElementById('review-details') || document.querySelector('.studio-review'), top = inspector?.scrollTop || 0;
281
+ const reader = document.getElementById('studio-canvas-body') || document.querySelector('.reader'), readerTop = reader.scrollTop, readerLeft = reader.scrollLeft;
249
282
  const code = document.querySelector('.diff-code-scroll'), codeTop = code?.scrollTop, codeLeft = code?.scrollLeft;
250
283
  const active = current?.contains(document.activeElement) ? { name: document.activeElement.name, start: document.activeElement.selectionStart, end: document.activeElement.selectionEnd } : null;
251
284
  const disclosures = [...document.querySelectorAll('#workspace details[id]')].filter(node => node.id !== 'review-comment-composer').map(node => ({ id: node.id, open: node.hasAttribute('open') }));
@@ -266,7 +299,7 @@
266
299
  if (window.htmx && document.querySelector('.file-diff')) window.htmx.process(document.querySelector('.file-diff'));
267
300
  document.dispatchEvent(new CustomEvent('htmx:afterSwap', { detail: { target: imported } }));
268
301
  if (active) { const input = form()?.querySelector(`[name="${active.name}"]`); input?.focus({ preventScroll: true }); if (typeof input?.setSelectionRange === 'function' && Number.isInteger(active.start)) input.setSelectionRange(active.start, active.end); }
269
- inspector.scrollTop = top;
302
+ if (inspector) inspector.scrollTop = top;
270
303
  reader.scrollTop = readerTop; reader.scrollLeft = readerLeft;
271
304
  const updatedCode = document.querySelector('.diff-code-scroll');
272
305
  if (updatedCode && code) { updatedCode.scrollTop = codeTop; updatedCode.scrollLeft = codeLeft; }
@@ -305,7 +338,6 @@
305
338
  const refreshURL = document.getElementById('workspace')?.dataset.refreshUrl;
306
339
  const viewport = ['.reader', '.diff-code-scroll'].map(selector => { const target = document.querySelector(selector); return target ? { selector, top: target.scrollTop, left: target.scrollLeft } : null; }).filter(Boolean);
307
340
  remember();
308
- exportMessages.delete(scope); exportMessages.delete(document.getElementById('review-comments')?.dataset.preview);
309
341
  for (const prefix of ['comment-', 'inline-diff-comment-', 'inline-document-comment-', 'document-comment-']) document.getElementById(prefix + id)?.remove();
310
342
  await refreshComments(scope, removed.file, { change: viewChange, outcome: 'Comment removed' });
311
343
  if (document.getElementById('workspace')?.dataset.refreshUrl === refreshURL) {
@@ -324,8 +356,9 @@
324
356
  document.addEventListener('submit', async event => {
325
357
  const node = event.target.closest('#review-comment-form'); if (!node) return;
326
358
  event.preventDefault(); event.stopImmediatePropagation();
327
- const submittedKey = key(node); if (saving.has(submittedKey)) return;
359
+ const submittedKey = key(node); if (saving.has(submittedKey) || imageUploads.has(submittedKey)) return;
328
360
  const payload = new URLSearchParams({ file: node.dataset.file, body: field(node, 'body').value, side: field(node, 'side').value });
361
+ payload.set('attachments', JSON.stringify((imageDrafts.get(submittedKey) || []).map(image => image.id)));
329
362
  if (node.dataset.sourceHash) payload.set('sourceHash', node.dataset.sourceHash);
330
363
  if (payload.get('side') !== 'file') for (const name of ['start', 'end']) payload.set(name, field(node, name).value);
331
364
  remember(); setComposer(node, true); saving.add(submittedKey); node.setAttribute('aria-busy', 'true'); node.querySelector('[type="submit"]').disabled = true;
@@ -348,14 +381,16 @@
348
381
  document.addEventListener('review-saved', event => {
349
382
  const savedKey = `${event.detail.preview}:${event.detail.file}`;
350
383
  if (event.detail.body !== undefined && drafts.get(savedKey)?.body !== event.detail.body) return;
351
- drafts.delete(savedKey);
384
+ drafts.delete(savedKey); imageDrafts.delete(savedKey);
352
385
  const node = form(); if (!node || key(node) !== savedKey) return;
353
386
  anchor = null;
354
387
  inlineTargets.delete(savedKey); diffTargets.delete(savedKey); placeDocumentComposer(); placeDiffComposer();
388
+ renderImageDraft(node);
355
389
  field(node, 'body').value = ''; field(node, 'side').value = 'file'; field(node, 'start').value = ''; field(node, 'end').value = '';
356
390
  showSelection(node);
357
391
  setComposer(node, Boolean(document.getElementById('document-discussion')));
358
392
  if (document.activeElement === field(node, 'body')) field(node, 'body').blur();
359
393
  });
360
394
  initialize();
395
+ attachmentForms().forEach(renderImageDraft);
361
396
  })();
package/public/session.js CHANGED
@@ -3,14 +3,7 @@
3
3
  const panels = () => document.querySelectorAll('#agent-connections, #mcp-connections');
4
4
  function close() { for(const panel of panels()) panel.hidden = true; for(const button of document.querySelectorAll('[data-session-toggle]')) button.setAttribute('aria-expanded','false'); }
5
5
  function positionMCP() {
6
- const panel = document.getElementById('mcp-connections'), button = document.querySelector('.session-mcp-button');
7
- if (!panel || panel.hidden || !button?.getBoundingClientRect || !window.innerWidth) return;
8
- const anchor = button.getBoundingClientRect(), header = button.closest('.topbar')?.getBoundingClientRect();
9
- const gutter = window.innerWidth <= 520 ? 8 : 16, width = panel.getBoundingClientRect().width;
10
- const top = Math.max(gutter, Math.max(anchor.bottom, header?.bottom || 0) + 8);
11
- panel.style.left = `${Math.round(Math.max(gutter, Math.min(anchor.right - width, window.innerWidth - width - gutter)))}px`;
12
- panel.style.right = 'auto'; panel.style.top = `${Math.round(top)}px`;
13
- panel.style.maxHeight = `${Math.max(0, window.innerHeight - top - gutter)}px`;
6
+ for (const panel of panels()) if (!panel.hidden) window.spequiPositionDropdown?.(panel, document.querySelector(`[data-session-toggle][aria-controls="${panel.id}"]`));
14
7
  }
15
8
  function text(id, value) { const node = document.getElementById(id); if (node) node.textContent = value; return node; }
16
9
  function lastSeen(at) {
@@ -22,27 +15,31 @@
22
15
  return new Date(at).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
23
16
  }
24
17
  function render(agent) {
18
+ if (current?.observedAt && agent.observedAt && agent.observedAt < current.observedAt) return;
25
19
  if (current && (current.status !== agent.status || current.connected !== agent.connected || current.agent !== agent.agent)) {
26
20
  const result = document.querySelector('[data-session-check-result]'); if (result) result.textContent = '';
27
21
  }
28
22
  current = agent;
29
23
  const labels = { live:'Agent ready', connected:'Agent connected', blocked:'Queue blocked', working:'Agent working', waiting:'Awaiting your answer', unresponsive:'No recent update', unattached:'No agent connected', unavailable:'Status unavailable' };
30
- const label = labels[agent.status] || 'Status unavailable';
24
+ const running = agent.queue?.active?.status === 'running';
25
+ const waiting = agent.queue?.active?.status === 'awaiting-input';
26
+ const label = waiting ? 'Answer needed' : (running && agent.status === 'unresponsive' ? 'Request in progress' : labels[agent.status]) || 'Status unavailable';
31
27
  const indicator = document.getElementById('agent-indicator');
32
28
  const nameLabel = typeof agent.agent === 'string' ? agent.agent.trim() : '';
33
- const stateLabel = { live:'Ready', connected:'Connected', blocked:'Queue blocked', working:'Working', waiting:'Answer needed' }[agent.status];
29
+ const stateLabel = waiting ? 'Answer needed' : { live:'Ready', connected:'Connected', blocked:'Queue blocked', working:'Working', waiting:'Answer needed' }[agent.status];
34
30
  for(const node of document.querySelectorAll('[data-session-label]')) node.textContent = indicator?.contains(node) && agent.connected && nameLabel && stateLabel ? `${nameLabel} · ${stateLabel}` : label;
35
31
  indicator?.classList.toggle('session-online',Boolean(agent.connected));
36
- if (indicator) indicator.dataset.sessionState = agent.status;
32
+ if (indicator) indicator.dataset.sessionState = waiting ? 'waiting' : agent.status;
37
33
  const heartbeatStopped = agent.status === 'unresponsive';
38
- const hint = heartbeatStopped ? 'No recent update. The agent may still be working in the same coding session. You can check back later.' : agent.at ? `${agent.agent || 'Agent'} · Last heartbeat ${new Date(agent.at).toLocaleTimeString()}` : 'Attach the spequi skill in your coding agent';
34
+ const hint = heartbeatStopped ? 'Longer requests can take a few minutes. The result will appear here when ready. Check your CLI for permissions or other actions waiting for you.' : agent.at ? `${agent.agent || 'Agent'} · Last heartbeat ${new Date(agent.at).toLocaleTimeString()}` : 'Attach the spequi skill in your coding agent';
39
35
  indicator?.setAttribute('title', hint);
40
36
  indicator?.setAttribute('aria-description', heartbeatStopped ? hint : 'Open agent status and recovery details.');
41
37
  const status = agent.status || 'unavailable';
42
- const badge = text('session-state', { live:'Ready', connected:'Connected', blocked:'Blocked', working:'Working', waiting:'Answer needed', unresponsive:'No recent update', unattached:'Not attached', unavailable:'Unknown' }[status] || 'Unknown');
43
- if (badge) badge.dataset.state = status;
38
+ const displayStatus = waiting ? 'waiting' : status;
39
+ const badge = text('session-state', { live:'Ready', connected:'Connected', blocked:'Blocked', working:'Working', waiting:'Answer needed', unresponsive:running ? 'In progress' : 'No recent update', unattached:'Not attached', unavailable:'Unknown' }[displayStatus] || 'Unknown');
40
+ if (badge) badge.dataset.state = displayStatus;
44
41
  text('session-agent-name', nameLabel || 'Spequi Agent');
45
- text('session-agent-caption', { live:'Listening for your next request', connected:'Not listening for new requests', blocked:'A request needs attention', working:'Processing your request', waiting:'Waiting for your answer', unresponsive:'The agent may still be working', unattached:'No coding session connected', unavailable:'Connection status unavailable' }[status] || 'Connection status unavailable');
42
+ text('session-agent-caption', { live:'Listening for your next request', connected:'Not listening for new requests', blocked:'A request needs attention', working:'Processing your request', waiting:'Waiting for your answer', unresponsive:running ? 'Request in progress; check your CLI if it pauses' : 'No recent agent heartbeat', unattached:'No coding session connected', unavailable:'Connection status unavailable' }[status] || 'Connection status unavailable');
46
43
  const timestamp = Number(agent.at), validTime = Number.isFinite(timestamp) && timestamp > 0 && !Number.isNaN(new Date(timestamp).getTime());
47
44
  const seen = text('session-last-seen', validTime ? lastSeen(timestamp) : 'Not yet');
48
45
  if (seen) { seen.title = validTime ? new Date(timestamp).toLocaleString() : 'No activity reported'; if (validTime) seen.setAttribute('datetime', new Date(timestamp).toISOString()); else seen.removeAttribute('datetime'); }
@@ -78,12 +75,28 @@
78
75
  text('session-queue-state', status === 'unavailable' || !queue ? 'Unknown' : queue.queued ? `${queue.queued} waiting` : 'Empty');
79
76
  const request = document.querySelector('[data-session-current]'); if (request) request.hidden = !active;
80
77
  text('session-current-change', active?.change || 'Project question');
81
- text('session-current-state', active?.status === 'awaiting-input' ? 'Answer needed' : stalled ? 'No recent update' : active?.preparing ? 'Preparing' : 'Working');
82
- text('session-current-hint', active?.status === 'awaiting-input' ? 'Open Requests to answer the question.' : stalled ? 'The agent may still be working. You can check back later.' : active?.origin ? 'A local preview is running. Follow progress in Requests.' : 'Follow progress in Requests.');
78
+ text('session-current-state', active?.status === 'awaiting-input' ? 'Answer needed' : stalled ? 'In progress · check CLI' : active?.preparing ? 'Preparing' : 'Working');
79
+ text('session-current-hint', active?.status === 'awaiting-input' ? active.question ? 'Answer below to continue this request.' : 'The saved question is unavailable. Open the request, or cancel it to free the queue.' : stalled ? 'This can take a few minutes. Results appear here when ready. Check your CLI for permissions or other actions waiting for you.' : active?.origin ? 'A local preview is running. Follow progress in Requests.' : 'Follow progress in Requests.');
80
+ const questionHost = document.getElementById('session-question');
81
+ const question = active?.question;
82
+ if (questionHost) {
83
+ questionHost.hidden = !question || !waiting;
84
+ const key = question ? `${active.id}:${question.id}` : '';
85
+ if (key !== questionHost.dataset.questionKey) {
86
+ questionHost.dataset.questionKey = key;
87
+ questionHost.replaceChildren();
88
+ if (question && waiting) questionHost.append(window.spequiQuestionForm(active, question, 'agent'));
89
+ }
90
+ }
91
+ const cancel = document.getElementById('session-cancel-request');
92
+ if (cancel) {
93
+ cancel.hidden = !waiting;
94
+ if (waiting) cancel.setAttribute('action', `/api/jobs/${encodeURIComponent(active.id)}/cancel`);
95
+ }
83
96
  const needsHelp = !agent.connected || status === 'blocked' || status === 'connected' && !active && !agent.ready;
84
97
  const recovery = document.getElementById('session-recovery'); if (recovery) recovery.hidden = !needsHelp;
85
- text('session-recovery-message', status === 'unavailable' ? 'Could not read the connection status. Check the local server, then refresh.'
86
- : stalled ? 'The agent may still be working. You can check back later.'
98
+ text('session-recovery-message', waiting && !active?.ownerConnected ? 'Your reply will be saved. Resume the same coding session to continue, or cancel this request to free the queue.' : status === 'unavailable' ? 'Could not read the connection status. Check the local server, then refresh.'
99
+ : stalled ? 'This can take a few minutes. Results appear here when ready. Check your CLI for permissions or other actions waiting for you.'
87
100
  : status === 'blocked' ? 'Open Requests to review the queue, then resume Spequi.'
88
101
  : status === 'unattached' ? 'Start the spequi skill in your coding session to attach an agent.'
89
102
  : status === 'connected' ? 'Resume the spequi skill in your coding session to receive requests.'
@@ -120,7 +133,7 @@
120
133
  const agent = await refresh();
121
134
  const name = agent?.agent || 'Spequi Agent';
122
135
  const message = !agent ? 'Could not refresh status. Check that the local server is running and try again.'
123
- : !agent.connected ? agent.status === 'unattached' ? 'No agent attached. Start the Spequi skill in your coding session.' : 'No recent update. The agent may still be working. Check back later.'
136
+ : !agent.connected ? agent.status === 'unattached' ? 'No agent attached. Start the Spequi skill in your coding session.' : 'Check your coding session for permissions or other actions waiting for you.'
124
137
  : agent.ready ? `${name} is connected and ready.`
125
138
  : agent.status === 'working' ? `${name} is connected and working.`
126
139
  : agent.status === 'waiting' ? `${name} is connected and waiting for your answer.`
@@ -133,6 +146,7 @@
133
146
  }
134
147
  }
135
148
  document.addEventListener('agent-status',event => render(event.detail));
149
+ document.addEventListener('requests-updated', () => { void refresh(); });
136
150
  document.addEventListener('click',event => {
137
151
  const toggle = event.target.closest('[data-session-toggle]');
138
152
  const target = toggle && document.getElementById(toggle.getAttribute('aria-controls'));