openprototype 1.7.0 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openprototype",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "本地原型工作台:左侧树形导航 + 中间原型预览 + 右侧 AI Agent(OpenCode)。PRD 与 HTML/JS 原型协作,含自动化检查。",
5
5
  "keywords": [
6
6
  "prototype",
@@ -48,6 +48,7 @@
48
48
  .agent-panel.is-collapsed .agent-resizer,
49
49
  .agent-panel.is-collapsed .agent-header-main,
50
50
  .agent-panel.is-collapsed .agent-new-chat,
51
+ .agent-panel.is-collapsed .agent-thread-bar,
51
52
  .agent-panel.is-collapsed .agent-context,
52
53
  .agent-panel.is-collapsed .agent-messages,
53
54
  .agent-panel.is-collapsed .agent-composer {
@@ -138,6 +139,48 @@
138
139
  writing-mode: vertical-rl;
139
140
  }
140
141
 
142
+ .agent-thread-bar {
143
+ min-height: 38px;
144
+ flex: 0 0 auto;
145
+ display: flex;
146
+ align-items: center;
147
+ gap: 7px;
148
+ padding: 6px 12px;
149
+ border-bottom: 1px solid #edf0f5;
150
+ background: #fff;
151
+ }
152
+
153
+ .agent-thread-label,
154
+ .agent-thread-count {
155
+ flex: 0 0 auto;
156
+ color: #7b8495;
157
+ font-size: 10px;
158
+ }
159
+
160
+ .agent-thread-select {
161
+ min-width: 0;
162
+ height: 26px;
163
+ flex: 1;
164
+ padding: 0 24px 0 7px;
165
+ border: 1px solid #dfe5ee;
166
+ border-radius: 5px;
167
+ outline: 0;
168
+ background: #fafbfc;
169
+ color: #3f4754;
170
+ font: inherit;
171
+ font-size: 11px;
172
+ }
173
+
174
+ .agent-thread-select:hover,
175
+ .agent-thread-select:focus {
176
+ border-color: #91caff;
177
+ }
178
+
179
+ .agent-thread-select:disabled {
180
+ cursor: wait;
181
+ opacity: .65;
182
+ }
183
+
141
184
  .agent-context {
142
185
  flex: 0 0 auto;
143
186
  padding: 10px 12px;
@@ -263,12 +306,8 @@
263
306
  white-space: nowrap;
264
307
  }
265
308
 
266
- .agent-tool {
267
- display: flex;
268
- align-items: center;
269
- gap: 7px;
309
+ .agent-tool-group {
270
310
  margin-top: 5px;
271
- padding: 5px 7px;
272
311
  border: 1px solid #e4e9f0;
273
312
  border-radius: 5px;
274
313
  background: #fafbfc;
@@ -276,6 +315,56 @@
276
315
  font-size: 10px;
277
316
  }
278
317
 
318
+ .agent-tool-summary {
319
+ display: flex;
320
+ align-items: center;
321
+ gap: 7px;
322
+ min-height: 28px;
323
+ padding: 5px 7px;
324
+ cursor: pointer;
325
+ list-style: none;
326
+ user-select: none;
327
+ }
328
+
329
+ .agent-tool-summary::-webkit-details-marker { display: none; }
330
+ .agent-tool-summary::marker { content: ""; }
331
+
332
+ .agent-tool-summary-label {
333
+ flex: 1;
334
+ min-width: 0;
335
+ }
336
+
337
+ .agent-tool-summary-hint {
338
+ flex: 0 0 auto;
339
+ color: #8a94a5;
340
+ }
341
+
342
+ .agent-tool-summary-hint::after {
343
+ content: "›";
344
+ display: inline-block;
345
+ margin-left: 4px;
346
+ transition: transform .15s ease;
347
+ }
348
+
349
+ .agent-tool-group[open] .agent-tool-summary-hint::after {
350
+ transform: rotate(90deg);
351
+ }
352
+
353
+ .agent-tool-list {
354
+ padding: 0 7px 7px 20px;
355
+ border-top: 1px solid #edf0f4;
356
+ }
357
+
358
+ .agent-tool {
359
+ display: flex;
360
+ align-items: center;
361
+ gap: 7px;
362
+ padding: 5px 0;
363
+ color: #687386;
364
+ font-size: 10px;
365
+ overflow-wrap: anywhere;
366
+ }
367
+
279
368
  .agent-tool-status {
280
369
  width: 6px;
281
370
  height: 6px;
@@ -287,6 +376,9 @@
287
376
  .agent-tool.is-running .agent-tool-status { background: #1677ff; }
288
377
  .agent-tool.is-complete .agent-tool-status { background: #18b54a; }
289
378
  .agent-tool.is-error .agent-tool-status { background: #d91f2f; }
379
+ .agent-tool-summary.is-running .agent-tool-status { background: #1677ff; }
380
+ .agent-tool-summary.is-complete .agent-tool-status { background: #18b54a; }
381
+ .agent-tool-summary.is-error .agent-tool-status { background: #d91f2f; }
290
382
 
291
383
  .agent-request-card,
292
384
  .agent-diff-card {
@@ -2,16 +2,55 @@
2
2
  const KIT = window.PROTO_KIT || {};
3
3
  const NS = (KIT.productId || 'proto') + '-navigator';
4
4
  const SESSION_KEY = NS + '-agent-session';
5
+ const THREADS_KEY = NS + '-agent-threads';
5
6
  const WIDTH_KEY = NS + '-agent-width';
6
7
  const COLLAPSED_KEY = NS + '-agent-collapsed';
7
8
  const DEFAULT_WIDTH = 380;
8
9
  const MIN_WIDTH = 320;
9
10
  const MAX_WIDTH = 600;
10
11
  const HISTORY_REFRESH_DELAY = 180;
12
+ const BACKGROUND_STATUS_DELAY = 1600;
11
13
  const agentStorage = window['localStorage'];
12
14
 
15
+ function loadStoredThreads() {
16
+ let threads = [];
17
+ try {
18
+ const stored = JSON.parse(agentStorage.getItem(THREADS_KEY) || '[]');
19
+ if (Array.isArray(stored)) {
20
+ threads = stored.filter(item => item && item.id).map((item, index) => ({
21
+ id: String(item.id),
22
+ title: String(item.title || `对话 ${index + 1}`),
23
+ createdAt: Number(item.createdAt || Date.now()),
24
+ running: false,
25
+ unread: false,
26
+ taskContext: null
27
+ }));
28
+ }
29
+ } catch (err) {
30
+ threads = [];
31
+ }
32
+ const legacyId = agentStorage.getItem(SESSION_KEY) || '';
33
+ if (legacyId && !threads.some(item => item.id === legacyId)) {
34
+ threads.push({
35
+ id: legacyId,
36
+ title: `对话 ${threads.length + 1}`,
37
+ createdAt: Date.now(),
38
+ running: false,
39
+ unread: false,
40
+ taskContext: null
41
+ });
42
+ }
43
+ return threads;
44
+ }
45
+
46
+ const storedThreads = loadStoredThreads();
47
+ const storedSessionId = agentStorage.getItem(SESSION_KEY) || '';
48
+
13
49
  const state = {
14
- sessionId: agentStorage.getItem(SESSION_KEY) || '',
50
+ sessionId: storedThreads.some(item => item.id === storedSessionId)
51
+ ? storedSessionId
52
+ : (storedThreads[storedThreads.length - 1] || {}).id || '',
53
+ threads: storedThreads,
15
54
  currentContext: { htmlPath: '', prdPath: '', title: '' },
16
55
  taskContext: null,
17
56
  eventSource: null,
@@ -23,8 +62,10 @@
23
62
  statusText: '正在连接 OpenCode…',
24
63
  refreshTimer: null,
25
64
  statusPollTimer: null,
65
+ backgroundStatusTimer: null,
26
66
  taskStartedAt: 0,
27
- optimisticMessage: ''
67
+ optimisticMessage: '',
68
+ expandedToolGroups: new Set()
28
69
  };
29
70
 
30
71
  let refs = {};
@@ -56,6 +97,11 @@
56
97
  ' <button class="agent-header-btn agent-new-chat" id="agentNewChatBtn" type="button">新对话</button>',
57
98
  ' <button class="agent-header-btn agent-toggle" id="agentToggleBtn" type="button">收起</button>',
58
99
  '</div>',
100
+ '<div class="agent-thread-bar">',
101
+ ' <span class="agent-thread-label">对话</span>',
102
+ ' <select class="agent-thread-select" id="agentThreadSelect" aria-label="切换 Agent 对话"></select>',
103
+ ' <span class="agent-thread-count" id="agentThreadCount"></span>',
104
+ '</div>',
59
105
  '<div class="agent-context">',
60
106
  ' <div class="agent-context-label">本条消息将携带</div>',
61
107
  ' <div class="agent-context-chip"><span class="agent-context-kind">页面</span><span class="agent-context-value" id="agentHtmlContext">请先从左侧选择页面</span></div>',
@@ -82,6 +128,8 @@
82
128
  statusText: document.getElementById('agentStatusText'),
83
129
  newChat: document.getElementById('agentNewChatBtn'),
84
130
  toggle: document.getElementById('agentToggleBtn'),
131
+ threadSelect: document.getElementById('agentThreadSelect'),
132
+ threadCount: document.getElementById('agentThreadCount'),
85
133
  htmlContext: document.getElementById('agentHtmlContext'),
86
134
  prdContext: document.getElementById('agentPrdContext'),
87
135
  quickAction: document.getElementById('agentPrdUpdateBtn'),
@@ -98,6 +146,106 @@
98
146
  refs.statusText.textContent = text;
99
147
  }
100
148
 
149
+ function currentThread() {
150
+ return state.threads.find(item => item.id === state.sessionId) || null;
151
+ }
152
+
153
+ function persistThreads() {
154
+ const stored = state.threads.map(item => ({
155
+ id: item.id,
156
+ title: item.title,
157
+ createdAt: item.createdAt
158
+ }));
159
+ agentStorage.setItem(THREADS_KEY, JSON.stringify(stored));
160
+ if (state.sessionId) agentStorage.setItem(SESSION_KEY, state.sessionId);
161
+ }
162
+
163
+ function renderThreadSwitcher() {
164
+ if (!refs.threadSelect) return;
165
+ refs.threadSelect.replaceChildren();
166
+ state.threads.forEach((thread, index) => {
167
+ const option = document.createElement('option');
168
+ option.value = thread.id;
169
+ const status = thread.running ? ' · 处理中' : thread.unread ? ' · 已完成' : '';
170
+ option.textContent = `${thread.title || `对话 ${index + 1}`}${status}`;
171
+ refs.threadSelect.appendChild(option);
172
+ });
173
+ refs.threadSelect.value = state.sessionId;
174
+ refs.threadCount.textContent = state.threads.length ? `${state.threads.length} 个` : '';
175
+ }
176
+
177
+ function detachActiveSession() {
178
+ clearTimeout(state.refreshTimer);
179
+ clearTimeout(state.statusPollTimer);
180
+ state.refreshTimer = null;
181
+ state.statusPollTimer = null;
182
+ if (state.eventSource) state.eventSource.close();
183
+ state.eventSource = null;
184
+ }
185
+
186
+ function activateThread(thread) {
187
+ state.sessionId = thread.id;
188
+ thread.unread = false;
189
+ state.taskContext = thread.taskContext || null;
190
+ state.messages = [];
191
+ state.pending = { permissions: [], questions: [] };
192
+ state.diff = [];
193
+ state.optimisticMessage = '';
194
+ state.expandedToolGroups.clear();
195
+ state.running = Boolean(thread.running);
196
+ state.taskStartedAt = state.running ? Date.now() : 0;
197
+ refs.stop.hidden = !state.running;
198
+ refs.send.hidden = state.running;
199
+ persistThreads();
200
+ renderThreadSwitcher();
201
+ renderMessages();
202
+ updateContextDisplay();
203
+ }
204
+
205
+ function nextThreadTitle() {
206
+ return `对话 ${state.threads.length + 1}`;
207
+ }
208
+
209
+ function scheduleBackgroundStatusPoll() {
210
+ if (state.backgroundStatusTimer || !state.connected) return;
211
+ const hasBackgroundWork = state.threads.some(thread => thread.id !== state.sessionId && thread.running);
212
+ if (!hasBackgroundWork) return;
213
+ state.backgroundStatusTimer = setTimeout(async () => {
214
+ state.backgroundStatusTimer = null;
215
+ const activeId = state.sessionId;
216
+ const backgroundThreads = state.threads.filter(thread => thread.id !== activeId && thread.running);
217
+ await Promise.all(backgroundThreads.map(async thread => {
218
+ try {
219
+ const data = await api(`/api/agent/sessions/${thread.id}/status`);
220
+ if (thread.id !== state.sessionId && data.status && data.status.type === 'idle') {
221
+ thread.running = false;
222
+ thread.unread = true;
223
+ reloadTaskPreview(thread.taskContext);
224
+ }
225
+ } catch (err) {
226
+ // A background thread can be checked again after the next foreground action.
227
+ }
228
+ }));
229
+ persistThreads();
230
+ renderThreadSwitcher();
231
+ scheduleBackgroundStatusPoll();
232
+ }, BACKGROUND_STATUS_DELAY);
233
+ }
234
+
235
+ async function restoreBackgroundThreadStatuses() {
236
+ const backgroundThreads = state.threads.filter(thread => thread.id !== state.sessionId);
237
+ await Promise.all(backgroundThreads.map(async thread => {
238
+ try {
239
+ const data = await api(`/api/agent/sessions/${thread.id}/status`);
240
+ thread.running = Boolean(data.status && data.status.type !== 'idle');
241
+ } catch (err) {
242
+ thread.running = false;
243
+ }
244
+ }));
245
+ renderThreadSwitcher();
246
+ scheduleBackgroundStatusPoll();
247
+ }
248
+
101
249
  function applyPanelWidth(width, persist) {
102
250
  const viewportLimit = Math.max(MIN_WIDTH, window.innerWidth - 290 - 560);
103
251
  const nextWidth = Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, viewportLimit, Number(width) || DEFAULT_WIDTH));
@@ -170,7 +318,56 @@
170
318
  return element;
171
319
  }
172
320
 
173
- function renderMessage(item) {
321
+ function renderToolGroup(toolParts, groupKey) {
322
+ const details = document.createElement('details');
323
+ details.className = 'agent-tool-group';
324
+ details.open = state.expandedToolGroups.has(groupKey);
325
+
326
+ const statuses = toolParts.map(part => part.state && part.state.status ? part.state.status : 'pending');
327
+ const hasError = statuses.includes('error');
328
+ const isRunning = statuses.some(status => status !== 'completed' && status !== 'error');
329
+ const summary = document.createElement('summary');
330
+ summary.className = `agent-tool-summary is-${hasError ? 'error' : isRunning ? 'running' : 'complete'}`;
331
+ const summaryDot = document.createElement('span');
332
+ summaryDot.className = 'agent-tool-status';
333
+ summary.appendChild(summaryDot);
334
+ appendText(
335
+ summary,
336
+ 'agent-tool-summary-label',
337
+ hasError ? `${toolParts.length} 个操作中有失败` : isRunning ? `正在执行 ${toolParts.length} 个操作…` : `已执行 ${toolParts.length} 个操作`
338
+ );
339
+ const hint = document.createElement('span');
340
+ hint.className = 'agent-tool-summary-hint';
341
+ hint.textContent = details.open ? '收起明细' : '查看明细';
342
+ summary.appendChild(hint);
343
+ details.appendChild(summary);
344
+ details.addEventListener('toggle', () => {
345
+ hint.textContent = details.open ? '收起明细' : '查看明细';
346
+ if (details.open) state.expandedToolGroups.add(groupKey);
347
+ else state.expandedToolGroups.delete(groupKey);
348
+ });
349
+
350
+ const list = document.createElement('div');
351
+ list.className = 'agent-tool-list';
352
+ toolParts.forEach(part => {
353
+ const status = part.state && part.state.status ? part.state.status : 'pending';
354
+ const tool = document.createElement('div');
355
+ const statusClass = status === 'completed' ? 'complete' : status === 'error' ? 'error' : 'running';
356
+ tool.className = `agent-tool is-${statusClass}`;
357
+ const dot = document.createElement('span');
358
+ dot.className = 'agent-tool-status';
359
+ tool.appendChild(dot);
360
+ const fallbackTitle = part.tool === 'question'
361
+ ? (status === 'completed' ? '已收到回答' : status === 'error' ? '提问失败' : '等待你的回答')
362
+ : (part.tool || '执行工具');
363
+ appendText(tool, '', (part.state && part.state.title) || fallbackTitle);
364
+ list.appendChild(tool);
365
+ });
366
+ details.appendChild(list);
367
+ return details;
368
+ }
369
+
370
+ function renderMessage(item, fallbackKey) {
174
371
  const info = item.info || item;
175
372
  const role = info.role || 'assistant';
176
373
  const parts = Array.isArray(item.parts) ? item.parts : [];
@@ -192,20 +389,23 @@
192
389
  }
193
390
  if (parsed.text) appendText(wrapper, 'agent-message-body', parsed.text);
194
391
 
195
- toolParts.forEach(part => {
196
- const status = part.state && part.state.status ? part.state.status : 'pending';
197
- const tool = document.createElement('div');
198
- const statusClass = status === 'completed' ? 'complete' : status === 'error' ? 'error' : 'running';
199
- tool.className = `agent-tool is-${statusClass}`;
200
- const dot = document.createElement('span');
201
- dot.className = 'agent-tool-status';
202
- tool.appendChild(dot);
203
- const fallbackTitle = part.tool === 'question'
204
- ? (status === 'completed' ? '已收到回答' : status === 'error' ? '提问失败' : '等待你的回答')
205
- : (part.tool || '执行工具');
206
- appendText(tool, '', (part.state && part.state.title) || fallbackTitle);
207
- wrapper.appendChild(tool);
208
- });
392
+ if (toolParts.length) {
393
+ const groupKey = String(info.id || item.id || fallbackKey || 'tool-group');
394
+ wrapper.appendChild(renderToolGroup(toolParts, groupKey));
395
+ }
396
+ return wrapper;
397
+ }
398
+
399
+ function renderToolMessageBatch(items, fallbackKey) {
400
+ const first = items[0] || {};
401
+ const firstInfo = first.info || first;
402
+ const toolParts = items.flatMap(item => (item.parts || []).filter(part => part.type === 'tool'));
403
+ if (!toolParts.length) return null;
404
+ const wrapper = document.createElement('div');
405
+ wrapper.className = 'agent-message is-assistant';
406
+ appendText(wrapper, 'agent-message-role', 'OpenCode');
407
+ const groupKey = String(firstInfo.id || first.id || fallbackKey || 'tool-batch');
408
+ wrapper.appendChild(renderToolGroup(toolParts, groupKey));
209
409
  return wrapper;
210
410
  }
211
411
 
@@ -325,10 +525,32 @@
325
525
  const diffCard = renderDiff();
326
526
  if (diffCard) refs.messages.appendChild(diffCard);
327
527
 
328
- state.messages.forEach(item => {
329
- const message = renderMessage(item);
528
+ let toolBatch = [];
529
+ let toolBatchStart = 0;
530
+ const flushToolBatch = () => {
531
+ if (!toolBatch.length) return;
532
+ const message = renderToolMessageBatch(toolBatch, `tool-batch-${toolBatchStart}`);
533
+ if (message) refs.messages.appendChild(message);
534
+ toolBatch = [];
535
+ };
536
+
537
+ state.messages.forEach((item, index) => {
538
+ const info = item.info || item;
539
+ const parts = Array.isArray(item.parts) ? item.parts : [];
540
+ const hasText = parts.some(part => part.type === 'text' && part.text);
541
+ const hasTools = parts.some(part => part.type === 'tool');
542
+ const isAssistant = (info.role || 'assistant') === 'assistant';
543
+ if (isAssistant && !hasText && !hasTools) return;
544
+ if (isAssistant && !hasText && hasTools) {
545
+ if (!toolBatch.length) toolBatchStart = index;
546
+ toolBatch.push(item);
547
+ return;
548
+ }
549
+ flushToolBatch();
550
+ const message = renderMessage(item, `message-${index}`);
330
551
  if (message) refs.messages.appendChild(message);
331
552
  });
553
+ flushToolBatch();
332
554
 
333
555
  if (state.optimisticMessage) {
334
556
  const message = renderMessage({
@@ -354,14 +576,18 @@
354
576
  function setRunning(running) {
355
577
  if (running && !state.running) state.taskStartedAt = Date.now();
356
578
  state.running = running;
579
+ const thread = currentThread();
580
+ if (thread) thread.running = running;
357
581
  refs.stop.hidden = !running;
358
582
  refs.send.hidden = running;
359
- refs.newChat.disabled = running;
360
583
  if (running) {
361
584
  setStatus('running', 'OpenCode 正在处理…');
362
585
  scheduleStatusPoll();
586
+ scheduleBackgroundStatusPoll();
363
587
  }
364
588
  else if (state.connected) setStatus('ready', state.statusText.includes('失败') ? state.statusText : 'OpenCode 已连接');
589
+ persistThreads();
590
+ renderThreadSwitcher();
365
591
  updateContextDisplay();
366
592
  }
367
593
 
@@ -437,11 +663,12 @@
437
663
  }
438
664
  }
439
665
 
440
- function reloadTaskPreview() {
441
- if (!state.taskContext || state.currentContext.htmlPath !== state.taskContext.htmlPath) return;
666
+ function reloadTaskPreview(taskContext) {
667
+ const context = taskContext || state.taskContext;
668
+ if (!context || state.currentContext.htmlPath !== context.htmlPath) return;
442
669
  const frame = document.getElementById('previewFrame');
443
670
  if (!frame) return;
444
- const baseUrl = state.taskContext.htmlPath;
671
+ const baseUrl = context.htmlPath;
445
672
  frame.src = baseUrl + (baseUrl.includes('?') ? '&' : '?') + `_agentReload=${Date.now()}`;
446
673
  }
447
674
 
@@ -490,19 +717,56 @@
490
717
  }
491
718
 
492
719
  async function createSession() {
720
+ const threadTitle = nextThreadTitle();
493
721
  const data = await api('/api/agent/sessions', {
494
722
  method: 'POST',
495
723
  headers: { 'Content-Type': 'application/json' },
496
- body: JSON.stringify({ title: (KIT.productTitle || '原型') + ' Agent' })
724
+ body: JSON.stringify({ title: `${KIT.productTitle || '原型'} · ${threadTitle}` })
497
725
  });
498
- state.sessionId = data.session.id;
499
- agentStorage.setItem(SESSION_KEY, state.sessionId);
500
- state.messages = [];
501
- state.pending = { permissions: [], questions: [] };
502
- state.diff = [];
503
- state.optimisticMessage = '';
726
+ detachActiveSession();
727
+ const thread = {
728
+ id: data.session.id,
729
+ title: threadTitle,
730
+ createdAt: Date.now(),
731
+ running: false,
732
+ unread: false,
733
+ taskContext: null
734
+ };
735
+ state.threads.push(thread);
736
+ activateThread(thread);
504
737
  connectEvents();
505
- renderMessages();
738
+ setStatus('ready', '已开始新对话');
739
+ scheduleBackgroundStatusPoll();
740
+ return thread;
741
+ }
742
+
743
+ async function switchSession(sessionId) {
744
+ const thread = state.threads.find(item => item.id === sessionId);
745
+ if (!thread || thread.id === state.sessionId) return;
746
+ refs.threadSelect.disabled = true;
747
+ detachActiveSession();
748
+ activateThread(thread);
749
+ setStatus(thread.running ? 'running' : 'ready', thread.running ? '正在恢复任务状态…' : '正在载入对话…');
750
+ try {
751
+ const restored = await refreshHistory();
752
+ if (!restored) {
753
+ state.threads = state.threads.filter(item => item.id !== thread.id);
754
+ persistThreads();
755
+ await createSession();
756
+ setStatus('ready', '原对话已失效,已新建对话');
757
+ return;
758
+ }
759
+ connectEvents();
760
+ const data = await api(`/api/agent/sessions/${state.sessionId}/status`);
761
+ setRunning(data.status && data.status.type !== 'idle');
762
+ await Promise.all([refreshPending(), refreshDiff()]);
763
+ } catch (err) {
764
+ setStatus('error', `切换对话失败:${err.message}`);
765
+ } finally {
766
+ refs.threadSelect.disabled = false;
767
+ renderThreadSwitcher();
768
+ scheduleBackgroundStatusPoll();
769
+ }
506
770
  }
507
771
 
508
772
  async function ensureSession() {
@@ -512,12 +776,15 @@
512
776
  }
513
777
  const restored = await refreshHistory();
514
778
  if (!restored) {
779
+ state.threads = state.threads.filter(item => item.id !== state.sessionId);
780
+ persistThreads();
515
781
  await createSession();
516
782
  return;
517
783
  }
518
784
  connectEvents();
519
785
  const data = await api(`/api/agent/sessions/${state.sessionId}/status`);
520
786
  setRunning(data.status && data.status.type !== 'idle');
787
+ scheduleBackgroundStatusPoll();
521
788
  }
522
789
 
523
790
  async function sendMessage(message) {
@@ -526,6 +793,16 @@
526
793
  try {
527
794
  if (!state.sessionId) await createSession();
528
795
  state.taskContext = { ...state.currentContext };
796
+ const thread = currentThread();
797
+ if (thread) {
798
+ thread.taskContext = { ...state.taskContext };
799
+ if (/^对话 \d+$/.test(thread.title)) {
800
+ const conciseTitle = text.replace(/\s+/g, ' ').slice(0, 18);
801
+ if (conciseTitle) thread.title = conciseTitle;
802
+ }
803
+ }
804
+ persistThreads();
805
+ renderThreadSwitcher();
529
806
  state.optimisticMessage = [
530
807
  '[导航器上下文]',
531
808
  `页面:${state.taskContext.htmlPath}`,
@@ -597,13 +874,16 @@
597
874
  setCollapsed(!refs.panel.classList.contains('is-collapsed'), true);
598
875
  });
599
876
  refs.newChat.addEventListener('click', async () => {
877
+ refs.newChat.disabled = true;
600
878
  try {
601
879
  await createSession();
602
- setStatus('ready', '已开始新对话');
603
880
  } catch (err) {
604
881
  setStatus('error', `新建对话失败:${err.message}`);
882
+ } finally {
883
+ refs.newChat.disabled = false;
605
884
  }
606
885
  });
886
+ refs.threadSelect.addEventListener('change', () => switchSession(refs.threadSelect.value));
607
887
  refs.send.addEventListener('click', () => sendMessage(refs.input.value));
608
888
  refs.stop.addEventListener('click', abortTask);
609
889
  refs.quickAction.addEventListener('click', () => sendMessage('请只根据当前 PRD 中所有红色标记的内容更新当前 HTML/JS 原型及必要的 mock/constants;不要修改 PRD 本身,也不要处理未标红的历史内容。'));
@@ -646,6 +926,7 @@
646
926
  bindEvents();
647
927
  applyPanelWidth(agentStorage.getItem(WIDTH_KEY) || DEFAULT_WIDTH, false);
648
928
  setCollapsed(agentStorage.getItem(COLLAPSED_KEY) === '1', false);
929
+ renderThreadSwitcher();
649
930
  renderMessages();
650
931
  updateContextDisplay();
651
932
 
@@ -655,6 +936,7 @@
655
936
  setStatus('ready', `OpenCode ${status.version} · ${status.model}`);
656
937
  updateContextDisplay();
657
938
  await ensureSession();
939
+ await restoreBackgroundThreadStatuses();
658
940
  await refreshPending();
659
941
  } catch (err) {
660
942
  state.connected = false;