spequi 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/public/app.js CHANGED
@@ -1,4 +1,62 @@
1
1
  (() => {
2
+ const dropdownTriggers = panel => [...document.querySelectorAll('[aria-controls]')].filter(button => button.getAttribute('aria-controls') === panel.id);
3
+ function closeDropdowns(target = null, restoreFocus = false) {
4
+ for (const detail of document.querySelectorAll('details[data-dropdown][open]')) {
5
+ if (target && detail.contains(target)) continue;
6
+ detail.open = false;
7
+ if (restoreFocus && detail.contains(document.activeElement)) detail.querySelector('summary')?.focus();
8
+ }
9
+ for (const panel of document.querySelectorAll('.session-panel:not([hidden]), #requests-panel:not([hidden]), [data-dropdown-panel]:popover-open')) {
10
+ const triggers = dropdownTriggers(panel);
11
+ if (target && (panel.contains(target) || triggers.some(button => button.contains(target)))) continue;
12
+ if (restoreFocus && panel.contains(document.activeElement)) triggers[0]?.focus();
13
+ if (panel.hasAttribute('popover')) panel.hidePopover(); else panel.hidden = true;
14
+ for (const button of triggers) button.setAttribute('aria-expanded', 'false');
15
+ }
16
+ }
17
+ document.addEventListener('pointerdown', event => closeDropdowns(event.target), true);
18
+ document.addEventListener('keydown', event => { if (event.key === 'Escape') closeDropdowns(null, true); }, true);
19
+ function positionDropdown(panel) {
20
+ const trigger = dropdownTriggers(panel)[0];
21
+ if (!trigger) return;
22
+ const anchor = trigger.getBoundingClientRect(), width = Math.min(Number(panel.dataset.dropdownWidth) || 380, window.innerWidth - 24);
23
+ const below = window.innerHeight - anchor.bottom - 20, above = anchor.top - 20;
24
+ const opensBelow = below >= Math.min(220, Math.max(below, above));
25
+ panel.style.left = `${Math.max(12, Math.min(anchor.right - width, window.innerWidth - width - 12))}px`;
26
+ panel.style.top = opensBelow ? `${anchor.bottom + 8}px` : 'auto';
27
+ panel.style.bottom = opensBelow ? 'auto' : `${window.innerHeight - anchor.top + 8}px`;
28
+ panel.style.maxHeight = `${Math.max(0, Math.min(420, opensBelow ? below : above))}px`;
29
+ }
30
+ document.addEventListener('beforetoggle', event => {
31
+ if (!event.target.matches('[data-dropdown-panel]')) return;
32
+ const open = event.newState === 'open';
33
+ for (const trigger of dropdownTriggers(event.target)) trigger.setAttribute('aria-expanded', String(open));
34
+ if (open) { closeDropdowns(event.target); positionDropdown(event.target); }
35
+ }, true);
36
+ document.addEventListener('click', event => {
37
+ const panel = event.target.closest('[data-dropdown-choice]')?.closest('[data-dropdown-panel]');
38
+ if (panel?.matches(':popover-open')) panel.hidePopover();
39
+ }, true);
40
+ window.addEventListener('resize', () => { for (const panel of document.querySelectorAll('[data-dropdown-panel]:popover-open')) positionDropdown(panel); });
41
+ let analyticsDay;
42
+ const viewedPreviews = new Set();
43
+ function recordUsage() {
44
+ if (document.visibilityState !== 'visible') return;
45
+ const send = payload => {
46
+ void fetch('/api/analytics', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').content }, body: JSON.stringify(payload), signal: AbortSignal.timeout(5000) }).catch(() => {});
47
+ };
48
+ const day = new Date().toISOString().slice(0, 10);
49
+ if (analyticsDay !== day) { analyticsDay = day; send({ event: 'project_used' }); }
50
+ const diff = document.querySelector('[data-diff-preview]');
51
+ if (!diff?.getClientRects().length) return;
52
+ const preview = diff.dataset.diffPreview, key = `spequi-diff-viewed:${preview}`;
53
+ if (viewedPreviews.has(preview)) return;
54
+ viewedPreviews.add(preview);
55
+ try { if (sessionStorage.getItem(key)) return; sessionStorage.setItem(key, '1'); } catch {}
56
+ send({ event: 'file_diff_viewed', preview_id: preview, changed_file_count: Number(diff.dataset.diffCount), layout: diff.dataset.diffLayout });
57
+ }
58
+ for (const event of ['htmx:afterSettle', 'visibilitychange', 'click', 'keydown']) document.addEventListener(event, () => requestAnimationFrame(recordUsage));
59
+ requestAnimationFrame(recordUsage);
2
60
  const themeToggle = document.getElementById('theme-toggle');
3
61
  function applyTheme(theme) {
4
62
  const dark = theme === 'dark' || theme === 'developer';
@@ -12,13 +70,33 @@
12
70
  applyTheme(document.documentElement.dataset.theme === 'dark' ? 'enterprise' : 'dark');
13
71
  try { localStorage.setItem('spequi-theme', document.documentElement.dataset.theme); } catch {}
14
72
  });
15
- let pendingRefresh = false, refreshing = false, followUpRefresh = false;
73
+ let pendingRefresh = false, refreshing = false, followUpRefresh = false, navigationRequests = 0, navigationGeneration = 0, backgroundXHR = null;
16
74
  const drafts = {};
17
75
  const specDisclosures = new Map();
18
76
  const sourceDrafts = new Map(), sourcePending = new Set(), sourceMessages = new Map();
19
77
  const initialDetailsToggle = document.getElementById('toggle-review-details');
20
78
  let reviewDetailsOpen = initialDetailsToggle ? initialDetailsToggle.getAttribute('aria-expanded') === 'true' : undefined, preserveReader = null;
21
- function toast(message) { const node = document.getElementById('toast'); node.textContent = message; node.classList.add('visible'); clearTimeout(node.hideTimer); node.hideTimer = setTimeout(() => node.classList.remove('visible'), 4500); }
79
+ function toast(message, downloadUrl = '') {
80
+ const node = document.getElementById('toast'); if (!node) return;
81
+ node.textContent = message;
82
+ if (/^\/api\/reviews\/[a-zA-Z0-9_-]+\/feedback\/[a-zA-Z0-9_-]+$/.test(downloadUrl)) {
83
+ const link = document.createElement('a'); link.href = downloadUrl; link.download = 'openspec-review-feedback.md'; link.textContent = 'Download Markdown'; node.append(link);
84
+ }
85
+ node.classList.add('visible'); clearTimeout(node.hideTimer);
86
+ const dismiss = () => { node.hideTimer = setTimeout(() => node.classList.remove('visible'), downloadUrl ? 9000 : 4500); };
87
+ node.onpointerenter = node.onfocusin = () => clearTimeout(node.hideTimer);
88
+ node.onpointerleave = node.onfocusout = dismiss; dismiss();
89
+ }
90
+ document.addEventListener('spequi-toast', event => {
91
+ const { message, downloadUrl = '', persist = false } = event.detail || {};
92
+ if (typeof message !== 'string' || !message) return;
93
+ if (persist) try { sessionStorage.setItem('spequi-toast', JSON.stringify({ message, at: Date.now() })); } catch {}
94
+ toast(message, downloadUrl);
95
+ });
96
+ try {
97
+ const saved = JSON.parse(sessionStorage.getItem('spequi-toast')); sessionStorage.removeItem('spequi-toast');
98
+ if (saved && typeof saved.message === 'string' && Date.now() - saved.at < 10000) toast(saved.message);
99
+ } catch {}
22
100
  function remember() {
23
101
  for (const node of document.querySelectorAll('.spec-context-quote[id]')) specDisclosures.set(node.id, node.open);
24
102
  for (const name of ['instructions', 'workflow-action', 'file-filter']) { const input = document.getElementById(name); if (input) drafts[name] = input.value; }
@@ -41,10 +119,10 @@
41
119
  }
42
120
  function readingViewport() { return document.querySelector('.diff-code-scroll') || document.querySelector('.reader'); }
43
121
  function refresh() {
44
- if (sourcePending.size) { pendingRefresh = true; return; }
122
+ if (sourcePending.size || navigationRequests) { pendingRefresh = true; return; }
45
123
  if (refreshing) { pendingRefresh = true; followUpRefresh = true; return; }
46
124
  if (!window.htmx) { pendingRefresh = true; return; }
47
- if (document.activeElement?.matches('input,textarea,select') || document.getElementById('apply-dialog').open) { pendingRefresh = true; return; }
125
+ if (document.activeElement?.matches('input,textarea,select') || document.getElementById('apply-dialog')?.open || document.querySelector('dialog[open]')) { pendingRefresh = true; return; }
48
126
  refreshing = true; pendingRefresh = false; remember();
49
127
  const reader = readingViewport(), top = reader?.scrollTop || 0, left = reader?.scrollLeft || 0;
50
128
  const disclosures = [...document.querySelectorAll('#workspace details[id]')].filter(node => node.id !== 'review-comment-composer').map(node => ({ id: node.id, open: node.hasAttribute('open') }));
@@ -54,23 +132,42 @@
54
132
  const focusDetails = focused?.matches('summary') ? focused.closest('details')?.id : null;
55
133
  const menuOpen = document.getElementById('workspace').classList.contains('navigation-open');
56
134
  const refreshURL = document.getElementById('workspace').dataset.refreshUrl || location.pathname + location.search;
57
- window.htmx.ajax('GET', refreshURL, { target: '#workspace', swap: 'outerHTML' }).then(() => {
135
+ const generation = navigationGeneration;
136
+ window.htmx.ajax('GET', refreshURL, { target: '#workspace', swap: 'outerHTML', headers: { 'X-Spequi-Refresh': '1' } }).then(() => {
137
+ if (generation !== navigationGeneration) return;
58
138
  restore(); const updated = readingViewport(); if (updated) { updated.scrollTop = top; updated.scrollLeft = left; }
59
- for (const state of disclosures) { const node = document.getElementById(state.id); if (node) node.toggleAttribute('open', state.open || node.hasAttribute('data-lifecycle-waiting') || node.hasAttribute('data-lifecycle-failed')); }
139
+ for (const state of disclosures) { const node = document.getElementById(state.id); if (node) node.toggleAttribute('open', state.open); }
60
140
  if (menuOpen) { document.getElementById('workspace').classList.add('navigation-open'); document.querySelector('.mobile-menu')?.setAttribute('aria-expanded', 'true'); }
61
141
  const target = focusID ? document.getElementById(focusID) : focusHref ? [...document.querySelectorAll('#workspace a')].find(node => node.getAttribute('href') === focusHref) : focusDetails ? document.getElementById(focusDetails)?.querySelector('summary') : null;
62
142
  if (target && !target.disabled) target.focus({ preventScroll: true });
63
143
  else if (focused?.closest('#workspace')) document.getElementById('document')?.focus({ preventScroll: true });
64
- }).catch(() => { pendingRefresh = true; }).finally(() => {
144
+ }).catch(() => { if (generation === navigationGeneration) pendingRefresh = true; }).finally(() => {
65
145
  refreshing = false;
66
146
  if (followUpRefresh) { followUpRefresh = false; setTimeout(refresh, 100); }
67
147
  });
68
148
  }
69
149
  document.addEventListener('htmx:configRequest', event => { event.detail.headers['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').content; });
70
150
  document.addEventListener('htmx:beforeRequest', event => {
151
+ const xhr = event.detail?.xhr;
152
+ if (event.detail?.requestConfig?.headers?.['X-Spequi-Refresh'] === '1' && xhr) {
153
+ xhr.spequiGeneration = navigationGeneration; backgroundXHR = xhr;
154
+ } else if (event.detail?.target?.id === 'workspace' && event.detail?.elt?.matches('a,form,input')) {
155
+ navigationGeneration++; navigationRequests++;
156
+ if (xhr) xhr.spequiNavigation = true;
157
+ backgroundXHR?.abort(); backgroundXHR = null;
158
+ }
71
159
  remember();
72
160
  if (event.detail.elt?.closest('[data-preserve-reader]')) { const reader = readingViewport(); preserveReader = reader ? { top: reader.scrollTop, left: reader.scrollLeft } : null; }
73
161
  });
162
+ document.addEventListener('htmx:afterRequest', event => {
163
+ if (!event.detail?.xhr?.spequiNavigation) return;
164
+ navigationRequests = Math.max(0, navigationRequests - 1);
165
+ if (!navigationRequests && pendingRefresh) setTimeout(refresh, 100);
166
+ });
167
+ document.addEventListener('htmx:beforeSwap', event => {
168
+ const generation = event.detail?.xhr?.spequiGeneration;
169
+ if (generation !== undefined && generation !== navigationGeneration) event.detail.shouldSwap = false;
170
+ });
74
171
  document.addEventListener('htmx:afterSwap', () => {
75
172
  restore(); initializeDiff();
76
173
  if (preserveReader) { const reader = readingViewport(); if (reader) { reader.scrollTop = preserveReader.top; reader.scrollLeft = preserveReader.left; } preserveReader = null; }
@@ -187,30 +284,33 @@
187
284
  dialog.addEventListener('close', () => { if (dialog.returnValue === 'confirm') { form.dataset.confirmed = 'true'; form.requestSubmit(); } }, { once: true });
188
285
  }, true);
189
286
  let retry = 1000, hasConnected = false;
287
+ let agentRequest;
190
288
  async function updateAgent() {
289
+ if (agentRequest) return agentRequest;
290
+ agentRequest = (async () => {
191
291
  try {
192
- const response = await fetch('/api/agent-status');
193
- if (!response.ok) return;
292
+ const response = await fetch('/api/agent-status', { signal: globalThis.AbortSignal?.timeout?.(10000) });
293
+ if (!response.ok) return null;
194
294
  const agent = await response.json(); document.dispatchEvent(new window.CustomEvent('agent-status', {detail:agent})); const node = document.querySelector('.agent-state');
195
295
  if (node) { node.classList.toggle('online', agent.connected); node.querySelector('span').textContent = agent.connected ? agent.agent || 'Agent attached' : 'Waiting for your agent'; }
196
- for (const note of document.querySelectorAll('[data-lifecycle-agent-note]')) {
197
- note.textContent = agent.connected ? `${agent.agent || 'Agent'} is attached. Ready to update the spec and preview code.` : agent.status === 'unresponsive' ? 'Agent heartbeat stopped. Resume the spequi skill in the same coding session. Open the agent indicator for recovery steps.' : 'No agent attached. Run the spequi skill in your coding agent to process requests.';
198
- note.hidden = Boolean(agent.connected) || note.closest('[data-awaiting-input=true]') !== null;
199
- }
200
- for (const form of document.querySelectorAll('[data-studio-stalled-action]')) form.hidden = Boolean(agent.connected);
296
+
297
+ for (const form of document.querySelectorAll('[data-studio-stalled-action]')) form.hidden = agent.queue?.active?.id === form.dataset.requestOwner ? Boolean(agent.queue.active.ownerConnected) : Boolean(agent.connected);
201
298
  for (const caption of document.querySelectorAll('[data-lifecycle-agent-caption]')) caption.textContent = agent.connected ? 'Same agent session' : 'Requests wait until your agent is attached';
202
- } catch {}
299
+ return agent;
300
+ } catch { return null; }
301
+ })();
302
+ try { return await agentRequest; } finally { agentRequest = null; }
203
303
  }
304
+ window.spequiRefreshAgent = updateAgent;
204
305
  function connect() {
205
306
  const socket = new WebSocket(`${location.protocol === 'https:' ? 'wss' : 'ws'}://${location.host}/live`);
206
- const status = document.getElementById('connection');
207
307
  socket.addEventListener('open', () => {
208
- retry = 1000; status.textContent = 'Local workspace'; status.classList.add('online');
308
+ retry = 1000;
209
309
  if (hasConnected) { pendingRefresh = true; refresh(); }
210
310
  hasConnected = true;
211
311
  });
212
- socket.addEventListener('message', event => { try { const message = JSON.parse(event.data); if (message.type === 'changed') refresh(); if (['agent', 'heartbeat', 'connected'].includes(message.type)) updateAgent(); } catch {} });
213
- socket.addEventListener('close', () => { status.textContent = 'Reconnecting to server'; status.classList.remove('online'); setTimeout(connect, retry); retry = Math.min(retry * 2, 15000); });
312
+ socket.addEventListener('message', event => { try { const message = JSON.parse(event.data); if (message.type === 'changed' && (!message.change || message.change === document.getElementById('workspace')?.dataset.change)) refresh(); if (message.type === 'requests') document.dispatchEvent(new window.CustomEvent('requests-updated')); if (message.type === 'readiness' && message.change === document.getElementById('workspace')?.dataset.change) refresh(); if (['agent', 'heartbeat', 'connected'].includes(message.type)) updateAgent(); } catch {} });
313
+ socket.addEventListener('close', () => { setTimeout(connect, retry); retry = Math.min(retry * 2, 15000); });
214
314
  socket.addEventListener('error', () => socket.close());
215
315
  }
216
316
  function loadHTMX() {
package/public/diff.css CHANGED
@@ -210,7 +210,7 @@
210
210
  /* Completed work keeps review actions available without implying new work. */
211
211
  .change-link.tasks-complete .nav-icon{color:var(--green)}
212
212
  .completed-change-state .empty-state>svg{color:var(--green)}
213
- .completed-change-actions{display:flex;flex-wrap:wrap;justify-content:center;gap:8px}
213
+ .completed-change-actions{display:flex;flex-wrap:wrap;justify-content:center;gap:8px;margin-top:20px}
214
214
  .completed-diff-option{max-width:46ch;margin-top:24px;font-size:11px;color:var(--muted)}
215
215
  .completed-diff-option>summary{cursor:pointer;min-height:32px;padding:7px;color:var(--accent-text)}
216
216
  .completed-diff-option>p{margin:6px 0 12px;font-size:11px;line-height:1.7}
@@ -0,0 +1,328 @@
1
+ (() => {
2
+ const panel = () => document.getElementById('requests-panel');
3
+ const workspace = () => document.getElementById('workspace');
4
+ const labels = { stalled: 'Stalled', 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' };
6
+ let page = 1, pages = 1, opener, activityPending, activityAgain = false, agent = {}, listGeneration = 0;
7
+ const saves = new Map(), saved = new Map(), saveFailures = new Map(), deletedDrafts = new Set();
8
+ async function api(url, payload) {
9
+ 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
+ const result = await response.json();
11
+ if (!response.ok) throw new Error(result.error || 'The request could not be completed. Retry with the project server running.');
12
+ return result;
13
+ }
14
+ function node(tag, text, className) {
15
+ const element = document.createElement(tag); if (text !== undefined) element.textContent = text; if (className) element.className = className; return element;
16
+ }
17
+ function requestIcon(name) {
18
+ const paths = { open: '<path d="M7 17 17 7M7 7h10v10"/>', delete: '<path d="M3 6h18M9 6V4h6v2M5 6l1 14h12l1-14M10 10v6m4-6v6"/>', dismiss: '<path d="m6 6 12 12M6 18 18 6"/>', chevron: '<path d="m9 5 7 7-7 7"/>' };
19
+ const icon = node('span', undefined, 'request-action-icon'); icon.setAttribute('aria-hidden', 'true');
20
+ icon.innerHTML = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round">${paths[name]}</svg>`;
21
+ return icon;
22
+ }
23
+ function requestTime(value) {
24
+ const date = new Date(value), today = date.toDateString() === new Date().toDateString();
25
+ const time = node('time', today ? date.toLocaleTimeString(undefined, { hour: 'numeric', minute: '2-digit' }) : date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', ...(date.getFullYear() !== new Date().getFullYear() ? { year: 'numeric' } : {}) }));
26
+ time.setAttribute('datetime', date.toISOString()); time.title = date.toLocaleString(); return time;
27
+ }
28
+ function feedback(text, error = false) {
29
+ const target = panel()?.querySelector('[data-requests-feedback]');
30
+ if (target) { target.textContent = text; target.className = error ? 'error-message' : 'success-message'; }
31
+ }
32
+ function close() {
33
+ if (panel()) panel().hidden = true;
34
+ for (const toggle of document.querySelectorAll('[data-requests-toggle]')) toggle.setAttribute('aria-expanded', 'false');
35
+ }
36
+ 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`;
45
+ }
46
+ function openLink(job) {
47
+ const stage = ['preview', 'impact'].includes(job.action) ? 'implement' : ['verify', 'sync-specs', 'archive'].includes(job.action) ? 'finish' : 'shape';
48
+ const query = job.action === 'start-plan' ? { view: 'studio', new: '1', creation: job.id } : {
49
+ change: job.change || '', view: 'studio', stage,
50
+ ...(job.status === 'awaiting-input' ? { pane: 'conversation' } : {}),
51
+ ...(job.action === 'preview' ? { job: job.id } : {}),
52
+ ...(job.action === 'impact' ? { job: job.reviewPreview, file: job.reviewFile } : {})
53
+ };
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');
56
+ link.append(requestIcon('open')); link.href = '/?' + new URLSearchParams(query); return link;
57
+ }
58
+ function button(text, action, id) {
59
+ const iconAction = ['delete', 'dismiss'].includes(action);
60
+ const control = node('button', iconAction ? undefined : text, iconAction ? `button request-${action}` : 'button');
61
+ if (iconAction) { const label = action === 'dismiss' ? 'Dismiss from inbox' : 'Delete request'; control.append(requestIcon(action)); control.setAttribute('aria-label', label); control.title = label; }
62
+ control.type = 'button'; control.dataset.requestAction = action; control.dataset.requestId = id; return control;
63
+ }
64
+ function emptyRequests(status, hasHistory = false) {
65
+ const copy = {
66
+ inbox: ['You’re all caught up', 'Ongoing work and requests needing your attention appear here.'],
67
+ all: ['No requests yet', 'Start a new spec or work on an existing change. Follow your agent’s progress and reply to questions here.'],
68
+ active: ['No active requests', 'When you send a request, follow its progress and reply to your agent here.'],
69
+ completed: ['No completed requests', 'Requests appear here once your agent finishes the work.'],
70
+ failed: ['No failed requests', 'Requests that need a retry will appear here if something goes wrong.'],
71
+ cancelled: ['No cancelled requests', 'Requests you cancel will appear here.']
72
+ }[status];
73
+ const state = node('div', undefined, 'requests-empty');
74
+ const icon = node('span', undefined, 'requests-empty-icon');
75
+ icon.setAttribute('aria-hidden', 'true');
76
+ icon.innerHTML = '<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"><path d="M22 12h-6l-2 3h-4l-2-3H2"/><path d="M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11Z"/></svg>';
77
+ state.append(icon, node('h3', copy[0]), node('p', copy[1]));
78
+ const newSpec = status === 'all' || status === 'inbox' && !hasHistory;
79
+ const action = node(newSpec ? 'a' : 'button', newSpec ? 'New spec' : 'View history', 'button');
80
+ action.setAttribute('data-request-empty-action', '');
81
+ if (newSpec) action.href = '/?view=studio&new=1';
82
+ else { action.type = 'button'; action.setAttribute('data-request-show-all', ''); }
83
+ state.append(action);
84
+ return state;
85
+ }
86
+ function requestRow(job, history, expanded) {
87
+ const row = node('section', undefined, 'request-row'), heading = node('div', undefined, 'request-heading');
88
+ row.dataset.requestId = job.id; row.dataset.requestKey = job.groupKey || job.id;
89
+ const status = node('span', labels[job.stalled ? 'stalled' : job.status] || job.status, 'request-state'); status.dataset.state = job.stalled ? 'stalled' : job.status;
90
+ const name = node('strong', job.change || 'Project question'); name.title = name.textContent;
91
+ heading.append(name);
92
+ if (job.groupCount > 1) heading.append(node('small', `${job.groupCount} actions`, 'request-group-count'));
93
+ heading.append(status);
94
+ row.append(heading);
95
+ const detail = node('details'); detail.open = expanded.has(job.groupKey || job.id);
96
+ 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);
100
+ if (job.result) body.append(node('h3', 'Result'), node('p', job.result, 'request-result'));
101
+ detail.append(body); row.append(detail);
102
+ const footer = node('div', undefined, 'request-footer'), meta = node('div', undefined, 'request-meta');
103
+ const kind = node('span', actions[job.action] || job.action, 'request-kind'); kind.title = kind.textContent;
104
+ meta.append(kind, requestTime(job.updatedAt));
105
+ const controls = node('div', undefined, 'request-controls'); controls.append(openLink(job));
106
+ if (['queued', 'awaiting-input'].includes(job.status) || job.status === 'running' && !job.origin && agent.queue?.active?.id === job.id && !agent.queue.active.ownerConnected) controls.append(button(job.status === 'running' ? 'End stalled request' : 'Cancel request', 'cancel', job.id));
107
+ if (['failed', 'cancelled'].includes(job.status) && ['explore', 'preview', 'verify', 'impact'].includes(job.action)) controls.append(button('Retry', 'retry', job.id));
108
+ if (!['queued', 'running', 'awaiting-input'].includes(job.status)) {
109
+ const control = button(history ? 'Delete…' : 'Dismiss', history ? 'delete' : 'dismiss', job.id);
110
+ if (!history) control.dataset.requestThrough = job.dismissThrough || job.updatedAt;
111
+ controls.append(control);
112
+ }
113
+ footer.append(meta, controls); row.append(footer); return row;
114
+ }
115
+ async function loadRequests() {
116
+ if (!panel() || panel().hidden) return;
117
+ const generation = ++listGeneration;
118
+ const list = panel().querySelector('[data-request-list]');
119
+ list.setAttribute('aria-busy', 'true');
120
+ if (!list.children.length) list.append(node('p', 'Loading requests…', 'requests-loading'));
121
+ try {
122
+ const status = panel().querySelector('[data-request-filter]').value;
123
+ const result = await api('/api/requests?' + new URLSearchParams({ status, page }));
124
+ if (generation !== listGeneration) return;
125
+ page = result.page; pages = result.pages;
126
+ const scroll = list.scrollTop;
127
+ const recentOpen = list.querySelector('#requests-recent')?.open || false;
128
+ const expanded = new Set([...list.querySelectorAll('.request-row details[open]')].map(detail => detail.closest('.request-row').dataset.requestKey));
129
+ const focused = list.contains(document.activeElement) ? document.activeElement : null;
130
+ 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;
131
+ list.replaceChildren();
132
+ const inbox = status === 'inbox';
133
+ if (!result.items.length) list.append(emptyRequests(status, Boolean(result.historyTotal)));
134
+ let section;
135
+ for (const job of result.items) {
136
+ if (inbox && section !== Boolean(job.needsAttention)) {
137
+ section = Boolean(job.needsAttention);
138
+ list.append(node('h3', section ? 'Needs attention' : 'In progress', 'requests-section-title'));
139
+ }
140
+ list.append(requestRow(job, !inbox, expanded));
141
+ }
142
+ if (inbox && result.recent?.length) {
143
+ const recent = node('details', undefined, 'requests-recent'); recent.id = 'requests-recent'; recent.open = recentOpen;
144
+ const summary = node('summary'); summary.setAttribute('data-request-recent-toggle', '');
145
+ summary.append(node('span', 'Recent'), node('small', String(result.recent.length)), requestIcon('chevron'));
146
+ recent.append(summary);
147
+ for (const job of result.recent) recent.append(requestRow(job, false, expanded));
148
+ list.append(recent);
149
+ }
150
+ list.scrollTop = scroll;
151
+ if (focus) {
152
+ const row = [...list.querySelectorAll('.request-row')].find(row => row.dataset.requestKey === focus.id);
153
+ 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;
154
+ (control || row?.querySelector('summary') || panel().querySelector('[data-request-filter]')).focus({ preventScroll: true });
155
+ }
156
+ panel().querySelector('[data-request-pagination]').textContent = `${result.total} ${inbox ? 'in inbox' : result.total === 1 ? 'request' : 'requests'}${pages > 1 ? ` · ${page} of ${pages}` : ''}`;
157
+ panel().querySelector('footer').hidden = result.total === 0;
158
+ const paging = panel().querySelector('[data-request-pages]'); if (paging) paging.hidden = pages <= 1;
159
+ panel().querySelector('[data-request-page="previous"]').disabled = page <= 1;
160
+ panel().querySelector('[data-request-page="next"]').disabled = page >= pages;
161
+ } catch (error) {
162
+ if (generation !== listGeneration) return;
163
+ list.querySelector('.requests-loading')?.remove(); feedback(error.message, true);
164
+ } finally { if (generation === listGeneration) list.removeAttribute('aria-busy'); }
165
+ }
166
+ function renderDrafts(drafts) {
167
+ const section = document.querySelector('[data-drafts-navigation]'); if (!section) return;
168
+ const signature = JSON.stringify(drafts); if (section.dataset.signature === signature) return;
169
+ const previous = JSON.parse(section.dataset.signature || '[]');
170
+ if (previous.some(item => item.hasPlan && !drafts.some(draft => draft.id === item.id))) document.dispatchEvent(new window.CustomEvent('workspace-updated'));
171
+ section.dataset.signature = signature; section.hidden = !drafts.length;
172
+ section.querySelector('[data-draft-count]').textContent = drafts.length;
173
+ const list = section.querySelector('[data-draft-links]'); list.replaceChildren();
174
+ const current = new URL(workspace()?.dataset.refreshUrl || location.href, location.href);
175
+ for (const draft of drafts) {
176
+ const href = '/?' + new URLSearchParams(draft.hasPlan ? { change: draft.change, view: 'studio', draft: draft.id } : draft.creationId ? { view: 'studio', new: '1', creation: draft.creationId, draft: draft.id } : { view: 'studio', new: '1', draft: draft.id });
177
+ const link = node('a', undefined, 'change-link draft-link'); link.href = href;
178
+ for (const [key, value] of Object.entries({ 'hx-get': href, 'hx-target': '#workspace', 'hx-swap': 'outerHTML', 'hx-push-url': 'true' })) link.setAttribute(key, value);
179
+ if (current.searchParams.get('draft') === draft.id || draft.creationId && workspace()?.dataset.change === draft.change) link.classList.add('selected');
180
+ const icon = node('span', undefined, 'nav-icon');
181
+ icon.innerHTML = '<svg aria-hidden="true" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.65" stroke-linecap="round" stroke-linejoin="round"><path d="M10 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8l6 6v4"/><path d="M14 2v6h6"/><path d="m16 22 6-6a2.12 2.12 0 0 0-3-3l-6 6-1 4Z"/><path d="m18 14 3 3"/></svg>';
182
+ const copy = node('span', undefined, 'nav-change'); copy.append(node('span', draft.change || 'Untitled idea'), node('small', (['queued', 'running', 'awaiting-input'].includes(draft.status) ? labels[draft.status] : draft.hasPlan ? 'Continue planning' : 'Saved idea')));
183
+ link.append(icon, copy); list.append(link);
184
+ }
185
+ window.htmx?.process(section);
186
+ }
187
+ async function activity() {
188
+ if (activityPending) { activityAgain = true; return activityPending; }
189
+ const current = workspace(); if (!current) return;
190
+ const query = new URL(current.dataset.refreshUrl || location.href, location.href);
191
+ activityPending = (async () => {
192
+ const result = await api('/api/activity?' + new URLSearchParams({ change: current.dataset.change || '', creation: query.searchParams.get('creation') || '' }));
193
+ agent = result.agent; document.dispatchEvent(new window.CustomEvent('agent-status', { detail: agent }));
194
+ const attention = result.attention || 0, inboxCount = result.inboxCount ?? attention;
195
+ const markerLabel = inboxCount ? `${inboxCount} ${inboxCount === 1 ? 'item' : 'items'} in your inbox${attention ? `; ${attention} ${attention === 1 ? 'needs' : 'need'} your attention` : ''}` : 'No pending requests';
196
+ for (const count of document.querySelectorAll('[data-request-count]')) { count.textContent = inboxCount; count.hidden = !inboxCount; count.title = markerLabel; }
197
+ for (const toggle of document.querySelectorAll('.topbar [data-requests-toggle]')) {
198
+ toggle.title = markerLabel; toggle.setAttribute('aria-label', `Requests. ${markerLabel}`);
199
+ }
200
+ renderDrafts(result.drafts);
201
+ for (const status of document.querySelectorAll('[data-job-state]')) status.textContent = labels[result.active.find(job => job.change === status.dataset.jobState)?.status] || '';
202
+ if (current !== workspace()) return;
203
+ if (current.dataset.requestState !== result.revision) {
204
+ current.dataset.requestState = result.revision;
205
+ document.dispatchEvent(new window.CustomEvent('workspace-updated'));
206
+ return;
207
+ }
208
+ const thread = document.getElementById('studio-thread');
209
+ if (thread && !thread.contains(document.activeElement)) {
210
+ const scroll = thread.scrollTop, nearBottom = thread.scrollHeight - thread.clientHeight - scroll < 32;
211
+ const open = [...thread.querySelectorAll('details[open][id]')].map(item => item.id);
212
+ thread.innerHTML = result.thread;
213
+ for (const id of open) document.getElementById(id)?.setAttribute('open', '');
214
+ thread.scrollTop = nearBottom ? thread.scrollHeight : scroll;
215
+ }
216
+ })().catch(error => { if (panel() && !panel().hidden) feedback(error.message, true); }).finally(() => {
217
+ activityPending = null;
218
+ if (activityAgain) { activityAgain = false; void activity(); }
219
+ });
220
+ return activityPending;
221
+ }
222
+ window.spequiSaveDraft = function (form) {
223
+ const id = form.querySelector('[name="draftId"]')?.value;
224
+ const stopped = () => deletedDrafts.has(id) || form.dataset.draftSubmitting === 'true' || Boolean(form.dataset.draftSubmitted);
225
+ if (!id || stopped()) return Promise.resolve();
226
+ const payload = { id, change: form.querySelector('[name="change"]').value, message: form.querySelector('[name="message"]').value, planMode: form.querySelector('[name="planMode"]:checked')?.value || 'next' };
227
+ if (!payload.change.trim() && !payload.message.trim()) return Promise.resolve();
228
+ const signature = JSON.stringify(payload), info = form.querySelector('[data-draft-save-state]');
229
+ const save = (saves.get(id) || Promise.resolve()).catch(() => {}).then(async () => {
230
+ if (stopped() || saved.get(id) === signature) return;
231
+ if (info?.isConnected) info.textContent = 'Saving draft…';
232
+ await api('/api/drafts', payload); saved.set(id, signature); saveFailures.delete(id);
233
+ if (form.isConnected) {
234
+ if (info) info.textContent = 'Draft saved';
235
+ const remove = form.querySelector('[data-draft-delete]'); if (remove) remove.hidden = false;
236
+ const url = new URL(workspace().dataset.refreshUrl || location.href, location.href); url.searchParams.set('draft', id);
237
+ workspace().dataset.refreshUrl = url.pathname + url.search;
238
+ history.replaceState(history.state, '', url.pathname + url.search);
239
+ }
240
+ void activity();
241
+ }).catch(error => {
242
+ if (info?.isConnected && !stopped()) {
243
+ info.textContent = 'Draft not saved';
244
+ const failure = signature + error.message;
245
+ if (saveFailures.get(id) !== failure) {
246
+ saveFailures.set(id, failure);
247
+ document.dispatchEvent(new window.CustomEvent('spequi-toast', { detail: { message: `Draft could not be saved. ${error.message}` } }));
248
+ }
249
+ }
250
+ error.draftNotification = true;
251
+ throw error;
252
+ });
253
+ saves.set(id, save); return save;
254
+ };
255
+ let saveTimer;
256
+ function scheduleSave(event) {
257
+ const form = event.target.closest('[data-create-spec]'); if (!form || form.dataset.draftSubmitting || form.dataset.draftSubmitted) return;
258
+ clearTimeout(saveTimer); saveTimer = setTimeout(() => { void window.spequiSaveDraft(form).catch(() => {}); }, 500);
259
+ }
260
+ document.addEventListener('input', scheduleSave); document.addEventListener('change', scheduleSave);
261
+ document.addEventListener('htmx:beforeRequest', event => {
262
+ if (!event.detail?.elt?.matches('a,form,input')) return;
263
+ const form = document.querySelector('[data-create-spec]');
264
+ if (form) { clearTimeout(saveTimer); void window.spequiSaveDraft(form).catch(() => {}); }
265
+ });
266
+ window.addEventListener('pagehide', () => {
267
+ const form = document.querySelector('[data-create-spec]');
268
+ if (form) { clearTimeout(saveTimer); void window.spequiSaveDraft(form).catch(() => {}); }
269
+ });
270
+ async function perform(control, action, id, payload = {}) {
271
+ control.disabled = true;
272
+ try {
273
+ await api(`/api/jobs/${encodeURIComponent(id)}/${action}`, payload);
274
+ if (action === 'retry' || action === 'dismiss') { feedback(''); document.dispatchEvent(new window.CustomEvent('spequi-toast', { detail: { message: action === 'dismiss' ? 'Dismissed from inbox. History kept.' : 'Retry queued.' } })); }
275
+ else feedback(action === 'delete' ? 'Request removed.' : 'Request cancelled.');
276
+ await Promise.all([activity(), loadRequests()]);
277
+ }
278
+ catch (error) { feedback(error.message, true); }
279
+ finally { control.disabled = false; }
280
+ }
281
+ document.addEventListener('click', event => {
282
+ const toggle = event.target.closest('[data-requests-toggle]');
283
+ if (toggle) {
284
+ const visible = panel().hidden; close(); panel().hidden = !visible;
285
+ if (visible) { opener = toggle; toggle.setAttribute('aria-expanded', 'true'); positionPanel(); panel().querySelector('[data-requests-close]').focus(); void loadRequests(); }
286
+ return;
287
+ }
288
+ if (event.target.closest('[data-requests-close]')) { close(); opener?.focus(); return; }
289
+ if (event.target.closest('a[data-request-empty-action]') && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey) { close(); return; }
290
+ if (event.target.closest('[data-request-show-all]')) {
291
+ const filter = panel().querySelector('[data-request-filter]');
292
+ filter.value = 'all'; filter.focus(); page = 1; void loadRequests(); return;
293
+ }
294
+ const paging = event.target.closest('[data-request-page]');
295
+ if (paging) { page += paging.dataset.requestPage === 'next' ? 1 : -1; void loadRequests(); return; }
296
+ const draftDelete = event.target.closest('[data-draft-delete]');
297
+ if (draftDelete) {
298
+ const dialog = document.getElementById('draft-delete-dialog'), id = draftDelete.dataset.draftDelete;
299
+ dialog.querySelector('[data-delete-plan-choice]').hidden = draftDelete.dataset.hasPlan !== 'true';
300
+ dialog.querySelector('[name=deletePlan]').checked = false; dialog.returnValue = ''; dialog.showModal();
301
+ dialog.addEventListener('close', async () => {
302
+ if (dialog.returnValue !== 'confirm') return;
303
+ clearTimeout(saveTimer); deletedDrafts.add(id);
304
+ try { await saves.get(id)?.catch(() => {}); await api(`/api/drafts/${encodeURIComponent(id)}/delete`, { deletePlan: draftDelete.dataset.hasPlan === 'true' && dialog.querySelector('[name=deletePlan]').checked }); location.assign('/?view=studio&new=1'); }
305
+ catch (error) { deletedDrafts.delete(id); const info = document.querySelector('[data-draft-save-state]') || document.getElementById('studio-action-feedback'); if (info) info.textContent = error.message; }
306
+ }, { once: true });
307
+ return;
308
+ }
309
+ const control = event.target.closest('[data-request-action]'); if (!control) return;
310
+ const { requestAction: action, requestId: id } = control.dataset;
311
+ if (action !== 'delete') { void perform(control, action, id, action === 'dismiss' ? { through: control.dataset.requestThrough } : {}); return; }
312
+ const dialog = document.getElementById('request-delete-dialog'); dialog.querySelector('[name=reviewData]').checked = true; dialog.returnValue = ''; dialog.showModal();
313
+ dialog.addEventListener('close', () => { if (dialog.returnValue === 'confirm') void perform(control, action, id, { reviewData: dialog.querySelector('[name=reviewData]').checked }); }, { once: true });
314
+ });
315
+ document.addEventListener('change', event => { if (event.target.matches('[data-request-filter]')) { page = 1; void loadRequests(); } });
316
+ document.addEventListener('keydown', event => { if (event.key === 'Escape' && panel() && !panel().hidden && !document.querySelector('dialog[open]')) { close(); opener?.focus(); } });
317
+ document.addEventListener('requests-updated', () => { void activity(); void loadRequests(); });
318
+ document.addEventListener('agent-status', event => {
319
+ const next = event.detail;
320
+ const changed = agent.status !== next.status || agent.queue?.active?.id !== next.queue?.active?.id || agent.queue?.active?.ownerConnected !== next.queue?.active?.ownerConnected;
321
+ agent = next;
322
+ if (changed) { void activity(); void loadRequests(); }
323
+ });
324
+ document.addEventListener('htmx:afterSwap', () => { void activity(); });
325
+ window.addEventListener('resize', positionPanel);
326
+ window.addEventListener('scroll', positionPanel, { passive: true });
327
+ void activity();
328
+ })();