dsh-netchat 0.0.0-stage → 0.3.19

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.
@@ -0,0 +1,2652 @@
1
+ <!doctype html>
2
+ <html lang="zh-CN">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width,initial-scale=1" />
6
+ <title>NetChat</title>
7
+ <style>
8
+ * { box-sizing: border-box; }
9
+ html, body { margin: 0; height: 100%; }
10
+ :root {
11
+ --fb-bg: #ffffff; --fb-bg-2: #f5f5f7; --fb-bg-3: #ececf0; --fb-fg: #1c1c21; --fb-fg-2: #5c5c68; --fb-fg-3: #8b8b96;
12
+ --fb-border: #e3e3e8; --fb-hover: rgba(0, 0, 0, 0.05); --fb-accent: #2f6fed; --fb-accent-fg: #ffffff;
13
+ }
14
+ @media (prefers-color-scheme: dark) {
15
+ :root {
16
+ --fb-bg: #1d1d21; --fb-bg-2: #26262b; --fb-bg-3: #303036; --fb-fg: #ededf0; --fb-fg-2: #a3a3ad; --fb-fg-3: #77777f;
17
+ --fb-border: #34343b; --fb-hover: rgba(255, 255, 255, 0.07); --fb-accent: #4b84f5; --fb-accent-fg: #ffffff;
18
+ }
19
+ }
20
+ :root {
21
+ color-scheme: light dark;
22
+ --bg: var(--color-background-primary, var(--fb-bg));
23
+ --bg-2: var(--color-background-secondary, var(--fb-bg-2));
24
+ --bg-3: var(--color-background-tertiary, var(--fb-bg-3));
25
+ --fg: var(--color-text-primary, var(--fb-fg));
26
+ --fg-2: var(--color-text-secondary, var(--fb-fg-2));
27
+ --fg-3: var(--color-text-tertiary, var(--fb-fg-3));
28
+ --border: var(--color-border-primary, var(--fb-border));
29
+ --hover: var(--color-background-ghost, var(--fb-hover));
30
+ --accent: var(--color-background-info, var(--fb-accent));
31
+ --accent-fg: var(--color-text-inverse, var(--fb-accent-fg));
32
+ --ok: var(--color-background-success, #2e9e5b);
33
+ --warn: var(--color-background-warning, #c98a06);
34
+ --danger: var(--color-background-danger, #d64545);
35
+ }
36
+ body {
37
+ font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif;
38
+ color: var(--fg); background: var(--bg); -webkit-font-smoothing: antialiased;
39
+ }
40
+ button, input, select, textarea { font: inherit; color: inherit; }
41
+ button { cursor: pointer; }
42
+ .app { display: flex; flex-direction: column; height: 100%; min-width: 260px; }
43
+ .bar { display: flex; align-items: center; gap: 8px; padding: 10px 12px 8px; border-bottom: 1px solid var(--border); flex: none; }
44
+ .brand { display: flex; align-items: center; gap: 6px; font-weight: 600; font-size: 14px; flex: none; white-space: nowrap; }
45
+ .brand .sub { color: var(--fg-3); font-weight: 400; font-size: 12px; }
46
+ .spacer { flex: 1; }
47
+ .me {
48
+ display: flex; align-items: center; gap: 6px; min-width: 0; max-width: 50%; padding: 3px 9px; border-radius: 999px;
49
+ background: var(--bg-2); border: 1px solid transparent; white-space: nowrap; overflow: hidden; font-size: 12px; flex: 0 1 auto;
50
+ }
51
+ .me:hover { border-color: var(--border); }
52
+ .me span { overflow: hidden; text-overflow: ellipsis; }
53
+ .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--fg-3); flex: none; }
54
+ .dot.on { background: var(--ok); }
55
+ .dot.busy { background: var(--warn); }
56
+ .icon-btn {
57
+ appearance: none; border: 0; background: transparent; color: var(--fg-2); width: 28px; height: 28px;
58
+ border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; flex: none;
59
+ }
60
+ .icon-btn:hover { background: var(--hover); color: var(--fg); }
61
+ .icon-btn.spin svg { animation: spin 0.8s linear infinite; }
62
+ @keyframes spin { to { transform: rotate(360deg); } }
63
+ .pill {
64
+ min-width: 18px; height: 18px; padding: 0 5px; border-radius: 9px; background: var(--bg-3); color: var(--fg-2);
65
+ font-size: 11px; display: inline-flex; align-items: center; justify-content: center; font-weight: 500;
66
+ }
67
+ .pill.hot { background: var(--accent); color: var(--accent-fg); }
68
+ .view { flex: 1; min-height: 0; overflow: auto; padding: 10px 12px 18px; }
69
+ .center { height: 100%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 8px; text-align: center; color: var(--fg-2); padding: 20px; }
70
+ .center h3 { margin: 4px 0 0; font-size: 14px; color: var(--fg); }
71
+ .center p { margin: 0; max-width: 340px; font-size: 12px; }
72
+ .center code { background: var(--bg-2); padding: 1px 5px; border-radius: 4px; font-size: 11px; }
73
+ .toolbar { display: flex; gap: 6px; align-items: center; margin-bottom: 8px; flex-wrap: wrap; }
74
+ .search {
75
+ flex: 1; min-width: 120px; display: flex; align-items: center; gap: 6px; padding: 4px 8px; border-radius: 8px;
76
+ background: var(--bg-2); border: 1px solid var(--border); color: var(--fg-2);
77
+ }
78
+ .search input { flex: 1; min-width: 0; border: 0; background: transparent; outline: none; color: var(--fg); }
79
+ .chips { display: flex; gap: 4px; flex-wrap: wrap; margin-bottom: 8px; }
80
+ .chip {
81
+ appearance: none; border: 1px solid var(--border); background: transparent; color: var(--fg-2); border-radius: 999px;
82
+ padding: 1px 9px; font-size: 12px;
83
+ }
84
+ .chip[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-fg); }
85
+ .row { display: flex; align-items: center; gap: 10px; padding: 9px 10px; }
86
+ .row.click { cursor: pointer; }
87
+ .row.click:hover { background: var(--hover); }
88
+ .avatar {
89
+ width: 32px; height: 32px; border-radius: 50%; flex: none; display: inline-flex; align-items: center; justify-content: center;
90
+ color: #fff; font-weight: 600; font-size: 14px;
91
+ }
92
+ .avatar.sm { width: 24px; height: 24px; font-size: 11px; }
93
+ .main { flex: 1; min-width: 0; }
94
+ .title { display: flex; align-items: center; gap: 6px; font-weight: 600; white-space: nowrap; overflow: hidden; }
95
+ .title .name { overflow: hidden; text-overflow: ellipsis; }
96
+ .meta { color: var(--fg-3); font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
97
+ .tag {
98
+ font-size: 10px; padding: 0 6px; border-radius: 4px; background: var(--bg-3); color: var(--fg-2); flex: none;
99
+ line-height: 16px;
100
+ }
101
+ .tag.role { background: color-mix(in srgb, var(--accent) 14%, transparent); color: var(--accent); }
102
+ .tag.ok { background: color-mix(in srgb, var(--ok) 16%, transparent); color: var(--ok); }
103
+ .tag.warn { background: color-mix(in srgb, var(--warn) 18%, transparent); color: var(--warn); }
104
+ .tag.danger { background: color-mix(in srgb, var(--danger) 16%, transparent); color: var(--danger); }
105
+ .tag.accent { background: color-mix(in srgb, var(--accent) 16%, transparent); color: var(--accent); }
106
+ /* The project a task belongs to, in one colour for them all: the names tell the projects
107
+ apart, and the colour only has to keep clear of the ones the status tags use (grey, blue,
108
+ green, amber, red). */
109
+ .tag.project {
110
+ max-width: 45%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
111
+ color: hsl(255 55% 36%); background: color-mix(in srgb, hsl(255 55% 36%) 15%, transparent);
112
+ }
113
+ @media (prefers-color-scheme: dark) {
114
+ .tag.project { color: hsl(255 65% 76%); background: color-mix(in srgb, hsl(255 65% 76%) 17%, transparent); }
115
+ }
116
+ .body { padding: 4px 12px 12px 52px; border-top: 1px solid var(--border); }
117
+ .body.wide { padding-left: 12px; }
118
+ .pre { white-space: pre-wrap; word-break: break-word; margin: 8px 0; }
119
+ .muted { color: var(--fg-2); }
120
+ .small { font-size: 11px; }
121
+ .mono { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; font-size: 11px; }
122
+ .actions { display: flex; gap: 6px; flex-wrap: wrap; align-items: center; margin-top: 10px; }
123
+ details { margin: 6px 0; border: 1px solid var(--border); border-radius: 8px; background: var(--bg-2); }
124
+ details summary { cursor: pointer; padding: 6px 9px; color: var(--fg-2); font-size: 12px; }
125
+ details > div { padding: 0 9px 8px; }
126
+ .transcript { max-height: 260px; overflow: auto; border: 1px solid var(--border); border-radius: 8px; padding: 8px; background: var(--bg); white-space: pre-wrap; word-break: break-word; font-size: 12px; }
127
+ .btn {
128
+ appearance: none; border: 1px solid var(--border); background: var(--bg); color: var(--fg); border-radius: 8px;
129
+ padding: 5px 12px; display: inline-flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 500;
130
+ }
131
+ .btn:hover { background: var(--hover); }
132
+ .btn:disabled { opacity: 0.5; cursor: not-allowed; }
133
+ .btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-fg); }
134
+ .btn.primary:hover { filter: brightness(1.08); background: var(--accent); }
135
+ .btn.danger { color: var(--danger); }
136
+ .btn.sm { padding: 2px 8px; font-size: 11px; }
137
+ .field { display: flex; flex-direction: column; gap: 4px; margin-bottom: 10px; }
138
+ .field label { color: var(--fg-2); font-size: 12px; }
139
+ .input, .textarea, .select {
140
+ width: 100%; border: 1px solid var(--border); border-radius: 8px; background: var(--bg); padding: 6px 8px; outline: none;
141
+ }
142
+ .input:focus, .textarea:focus, .select:focus { border-color: var(--accent); }
143
+ .textarea { resize: vertical; min-height: 92px; line-height: 1.55; }
144
+ .check { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--fg-2); margin: 6px 0; }
145
+ .inline { display: inline-flex; align-items: center; gap: 6px; }
146
+ .select.inline { width: auto; }
147
+ .notice { border: 1px solid var(--border); border-radius: 8px; background: var(--bg-2); padding: 8px 10px; font-size: 12px; color: var(--fg-2); margin: 8px 0; word-break: break-word; }
148
+ .notice.danger { border-color: color-mix(in srgb, var(--danger) 50%, transparent); color: var(--danger); }
149
+ .notice.warn { border-color: color-mix(in srgb, var(--warn) 50%, transparent); }
150
+ .sheet { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.35); display: flex; justify-content: flex-end; z-index: 20; }
151
+ /* A small dialog in the middle, for a choice that has to be made before something happens
152
+ (which project to run a task in). The backdrop closes it, as does Escape. */
153
+ .dialog { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.35); display: flex; align-items: center; justify-content: center; z-index: 22; padding: 16px; }
154
+ .dialog-box { width: min(380px, 100%); max-height: 100%; overflow: auto; background: var(--bg); border: 1px solid var(--border); border-radius: 12px; padding: 14px 16px 16px; box-shadow: 0 10px 36px rgba(0, 0, 0, 0.22); }
155
+ .dialog-box h2 { margin: 0 0 4px; font-size: 14px; }
156
+ .dialog-box .task-name { color: var(--fg-2); font-size: 12px; margin-bottom: 10px; word-break: break-word; }
157
+ .dialog-box .actions { margin-top: 12px; justify-content: flex-end; }
158
+ .sheet .panel {
159
+ width: min(420px, 100%); height: 100%; overflow: auto; background: var(--bg); border-left: 1px solid var(--border);
160
+ padding: 12px 14px 20px; box-shadow: 0 8px 30px rgba(0, 0, 0, 0.18);
161
+ }
162
+ .sheet h2 { margin: 0 0 4px; font-size: 15px; }
163
+ .sheet section { border-top: 1px solid var(--border); padding: 10px 0; }
164
+ .sheet h3 { margin: 0 0 8px; font-size: 12px; color: var(--fg-2); font-weight: 600; letter-spacing: 0.02em; }
165
+ .kv { display: grid; grid-template-columns: auto 1fr; gap: 2px 10px; font-size: 12px; }
166
+ .kv dt { color: var(--fg-3); } .kv dd { margin: 0; word-break: break-all; }
167
+ .toast {
168
+ position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); z-index: 30; background: var(--fg); color: var(--bg);
169
+ padding: 7px 14px; border-radius: 8px; font-size: 12px; max-width: 86%; box-shadow: 0 6px 20px rgba(0, 0, 0, 0.2);
170
+ }
171
+ .toast.danger { background: var(--danger); color: #fff; }
172
+ .empty { color: var(--fg-3); text-align: center; padding: 28px 10px; font-size: 12px; }
173
+ .timeline { display: grid; gap: 4px; font-size: 12px; margin: 8px 0; }
174
+ .timeline div { display: flex; gap: 8px; }
175
+ .timeline time { color: var(--fg-3); flex: none; font-size: 11px; padding-top: 1px; }
176
+ .stack { display: flex; flex-direction: column; gap: 4px; margin-top: 8px; }
177
+ .chip.chosen { background: color-mix(in srgb, var(--ok) 16%, transparent); border-color: var(--ok); color: var(--ok); }
178
+ /* ---- chat ----
179
+ The panel's width is whatever the host gives the sidebar, so the switch between the
180
+ one-column (list, then conversation) and two-column layout is a container query on the
181
+ panel itself, not a media query on the window. */
182
+ #app { container-type: inline-size; container-name: panel; }
183
+ .chat { display: flex; flex: 1; min-height: 0; }
184
+ .chat-list {
185
+ flex: none; display: flex; flex-direction: column; min-height: 0; border-right: 1px solid var(--border);
186
+ background: var(--bg-2);
187
+ }
188
+ .chat-list .toolbar { padding: 8px 10px 0; margin-bottom: 4px; }
189
+ .chat-list .chips { padding: 0 10px; }
190
+ .chat-items { overflow: auto; min-height: 0; }
191
+ .conv {
192
+ display: flex; flex-direction: column; flex: 1; min-width: 0; min-height: 0;
193
+ }
194
+ .conv-head {
195
+ display: flex; align-items: center; gap: 8px; padding: 8px 12px; border-bottom: 1px solid var(--border); flex: none;
196
+ background: var(--bg);
197
+ }
198
+ .conv-head .title { flex: 1; min-width: 0; }
199
+ .conv-head .name-row { display: flex; align-items: center; gap: 6px; min-width: 0; }
200
+ .conv-head .meta { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; }
201
+ .conv-head .dot.inline { width: 6px; height: 6px; margin: 0; }
202
+ .conv-head .icon-btn.active { background: var(--hover); color: var(--fg); }
203
+ .conv-menu-wrap { position: relative; flex: none; }
204
+ .menu {
205
+ position: absolute; top: calc(100% + 4px); right: 0; min-width: 190px; z-index: 16; padding: 4px;
206
+ background: var(--bg); border: 1px solid var(--border); border-radius: 10px; box-shadow: 0 8px 30px rgba(0, 0, 0, 0.18);
207
+ }
208
+ .menu-item {
209
+ appearance: none; border: 0; background: transparent; color: var(--fg); width: 100%; text-align: left; border-radius: 7px;
210
+ padding: 7px 9px; display: flex; align-items: center; gap: 8px; font-size: 12px;
211
+ }
212
+ .menu-item:hover { background: var(--hover); }
213
+ .menu-item:disabled { opacity: 0.45; cursor: not-allowed; }
214
+ .menu-item.danger { color: var(--danger); }
215
+ .menu-note { padding: 7px 9px; font-size: 12px; color: var(--fg-2); white-space: nowrap; }
216
+ .conv-empty { padding: 40px 16px; }
217
+ .conv-empty .small { margin-top: 4px; max-width: 300px; }
218
+ .conv-body { flex: 1; min-height: 0; overflow: auto; padding: 12px; display: flex; flex-direction: column; gap: 10px; }
219
+ /* A row stacks: a line with the avatar, the name and the time, then the bubble under it. */
220
+ .msg { display: flex; flex-direction: column; gap: 4px; max-width: 92%; min-width: 0; }
221
+ .msg.mine { align-self: flex-end; }
222
+ .msg.theirs { align-self: flex-start; }
223
+ .msg-col { display: flex; flex-direction: column; gap: 3px; min-width: 0; max-width: 100%; }
224
+ .msg.mine .msg-col { align-items: flex-end; }
225
+ /* The avatar comes first on that line, to the left of the name, whichever side the row is on. */
226
+ .msg-meta { display: flex; align-items: center; gap: 6px; font-size: 11px; color: var(--fg-3); white-space: nowrap; max-width: 100%; min-width: 0; }
227
+ .msg-meta .avatar { flex: none; }
228
+ .msg-meta .who { color: var(--fg-2); overflow: hidden; text-overflow: ellipsis; }
229
+ .bubble {
230
+ padding: 7px 11px; border-radius: 12px; background: var(--bg-2); border: 1px solid var(--border);
231
+ white-space: pre-wrap; word-break: break-word; font-size: 13px; line-height: 1.5;
232
+ }
233
+ /* A bubble this machine sent looks the same as one it received; only its side of the row
234
+ tells them apart. (It used to be blue with white text; that was asked to be removed.) */
235
+ .bubble.task { background: var(--bg); cursor: pointer; max-width: 100%; min-width: 200px; }
236
+ .bubble.task:hover { border-color: var(--accent); }
237
+ .bubble .task-title { font-weight: 600; display: flex; align-items: center; gap: 6px; }
238
+ .bubble .task-title .name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
239
+ .bubble .task-teaser { color: var(--fg-2); font-size: 12px; margin-top: 3px; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
240
+ .bubble .task-foot { display: flex; align-items: center; gap: 6px; margin-top: 5px; flex-wrap: wrap; }
241
+ .bubble .task-open { color: var(--fg-3); font-size: 11px; }
242
+ .bubble .task-marks { display: inline-flex; gap: 4px; align-items: center; margin-left: auto; }
243
+ .bubble.task.has-news { border-color: var(--accent); }
244
+ .msg .chips { margin: 2px 0 0; }
245
+ .msg .chips .chip { cursor: pointer; }
246
+ .msg.mine .chips { justify-content: flex-end; }
247
+ .msg .small.muted { margin-top: 2px; }
248
+ .msg .notice { margin: 4px 0 0; }
249
+ .day { align-self: center; font-size: 11px; color: var(--fg-3); padding: 2px 8px; border-radius: 999px; background: var(--bg-2); }
250
+ .conv-input { flex: none; border-top: 1px solid var(--border); padding: 8px 10px; display: flex; flex-direction: column; gap: 6px; background: var(--bg); }
251
+ .conv-input .row { padding: 0; gap: 6px; }
252
+ .conv-input .select { font-size: 12px; padding: 3px 6px; max-width: 100%; }
253
+ /* The box's height is the user's choice (dragged on the bar above it, kept in state.inputHeights)
254
+ and is given as a fixed height rather than a minimum: typing past the bottom scrolls inside it
255
+ instead of stretching the box up into the conversation. */
256
+ .conv-input textarea.textarea { height: 66px; min-height: 66px; max-height: none; resize: none; overflow: auto; }
257
+ .conv-input.drawer-input textarea.textarea { height: 78px; min-height: 78px; }
258
+ /* One line, never wrapped: the two mode buttons, then the task selector filling what is left. */
259
+ .conv-input .input-modes { display: flex; align-items: center; gap: 6px; flex-wrap: nowrap; }
260
+ .conv-input .input-modes .btn { flex: none; }
261
+ .conv-input .input-modes .btn[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-fg); }
262
+ .conv-input .reply-to { flex: 1 1 0; min-width: 0; width: 0; text-overflow: ellipsis; }
263
+ /* The bar above the box that sets how tall it is: the box's top edge moves, its bottom stays
264
+ put. It is a real control: keyboard and pointer both work. */
265
+ .box-resizer { align-self: stretch; height: 12px; margin: -8px -10px -6px; display: flex; align-items: flex-end; justify-content: center; cursor: ns-resize; touch-action: none; }
266
+ .box-resizer::after { content: ""; width: 36px; height: 3px; margin-bottom: 3px; border-radius: 2px; background: var(--border); transition: background 0.15s; }
267
+ .box-resizer:hover::after, .box-resizer:focus-visible::after, .box-resizer.dragging::after { background: var(--fg-3); }
268
+ .box-resizer:focus-visible { outline: none; }
269
+ .chat.resizing, .chat.resizing * { cursor: ns-resize !important; user-select: none !important; }
270
+ .chat.resizing iframe, .chat.resizing textarea { pointer-events: none; }
271
+ .chat.resizing .conv-body, .chat.resizing .thread-body { overscroll-behavior: contain; }
272
+ .task-form { gap: 8px; max-height: min(58vh, 420px); overflow: auto; padding-right: 2px; }
273
+ .task-form .textarea { min-height: 84px; }
274
+ .conv-input .spacer { flex: 1; }
275
+ .drawer-backdrop { position: absolute; inset: 0; z-index: 14; background: rgba(0, 0, 0, 0.28); outline: none; }
276
+ /* The list has one width on a wide panel and another (all of it) on a narrow one. The drawer
277
+ is as wide as the conversation beside the list, so it starts where the list ends. */
278
+ .chat { --list-width: 232px; }
279
+ .drawer {
280
+ position: absolute; top: 0; right: 0; bottom: 0; left: var(--list-width); display: flex; flex-direction: column;
281
+ background: var(--bg); border-left: 1px solid var(--border); box-shadow: -8px 0 30px rgba(0, 0, 0, 0.18); z-index: 15;
282
+ }
283
+ .drawer > .toolbar { flex: none; padding: 10px 10px 8px 14px; border-bottom: 1px solid var(--border); }
284
+ /* The task's details and the thread share the height, each scrolling on its own, so that the
285
+ task stays in view while reading a long thread and the reply box is never scrolled away.
286
+ The task's part may take up to 40% of the drawer: a long request then scrolls inside that
287
+ part instead of squeezing the thread and the reply box. */
288
+ .drawer-task { flex: 0 1 auto; min-height: 0; max-height: 40%; overflow: auto; padding: 10px 14px 12px; border-bottom: 1px solid var(--border); }
289
+ /* The buttons sit above the text here, so their usual gap above is not wanted. */
290
+ .drawer-task > .stack > .actions:first-child { margin-top: 0; }
291
+ /* The one line that stays when the request is folded: who it is between, and the fold. */
292
+ .task-head { display: flex; align-items: center; gap: 8px; justify-content: space-between; }
293
+ .task-head .meta { flex: 1; min-width: 0; }
294
+ .task-toggle { flex: none; }
295
+ .drawer-thread { flex: 1 1 0; min-height: 120px; display: flex; flex-direction: column; }
296
+ .thread-head { flex: none; padding: 6px 14px; font-size: 11px; color: var(--fg-3); letter-spacing: 0.02em; }
297
+ .thread-body { flex: 1 1 0; min-height: 0; overflow: auto; padding: 2px 12px 10px; display: flex; flex-direction: column; gap: 10px; }
298
+ .drawer-input { border-top: 1px solid var(--border); }
299
+ /* A receipt is the other side's progress: one quiet line, not a bubble. */
300
+ /* A receipt is a line of small grey text in the middle, with no pill behind it: a filled
301
+ capsule read as a white dot next to the last message, and said nothing the text does not. */
302
+ .thread-event { align-self: center; display: flex; gap: 8px; align-items: baseline; font-size: 11px; color: var(--fg-3); padding: 1px 0; }
303
+ .thread-event + .thread-event { margin-top: -6px; }
304
+ /* Narrow: one column at a time. The list shows until a conversation is opened, then the
305
+ conversation takes its place; the back button returns to the list. */
306
+ @container panel (max-width: 639px) {
307
+ .chat { --list-width: 0px; }
308
+ .chat-list { width: 100%; }
309
+ .chat.in-conv .chat-list { display: none; }
310
+ .chat:not(.in-conv) .conv { display: none; }
311
+ }
312
+ /* Wide enough for both. */
313
+ @container panel (min-width: 640px) {
314
+ .chat-list { width: var(--list-width); }
315
+ .chat .back-btn { display: none; }
316
+ }
317
+ #view { position: relative; display: flex; flex-direction: column; }
318
+ /* The chat view manages its own scrolling: the message list scrolls, the header and the
319
+ input stay put. Other views (agents, settings) keep .view's padding and scrolling. */
320
+ #view.view-chat { padding: 0; overflow: hidden; }
321
+ #view > .center { flex: none; }
322
+ svg.i { width: 15px; height: 15px; flex: none; }
323
+ </style>
324
+ </head>
325
+ <body>
326
+ <div id="app" class="app"><div id="view" class="view"><div class="center" id="boot"></div></div></div>
327
+ <div id="toast" class="toast" hidden></div>
328
+ <script>
329
+ (() => {
330
+ "use strict";
331
+ // Everything below is defined in one closure: the panel is a single self-contained page
332
+ // (the plugin sandbox allows no external resources and no network access of its own).
333
+ const APP = { name: "net-chat", version: "0.3.19" };
334
+ const PROTOCOL = "2026-01-26";
335
+ const CALL_TIMEOUT_MS = 90_000;
336
+ const POLL_TIMEOUT_MS = 60_000;
337
+
338
+ // ---- text ---------------------------------------------------------------------------------
339
+ const STRINGS = {
340
+ zh: {
341
+ appName: "NetChat", tagline: "局域网 Agent",
342
+ booting: "正在连接 NetChat…",
343
+ noHostTitle: "无法连接 {host} 宿主", noHostBody: "这个页面需要作为 NetChat 插件面板在 {host} 中打开。",
344
+ fatalTitle: "NetChat 服务没有启动", retry: "重试", refresh: "刷新",
345
+ online: "在线", offline: "离线", never: "从未上线", loading: "加载中…",
346
+ verified: "已验证", unverified: "未验证", noKey: "未设密钥",
347
+ projectHint: "相关项目",
348
+ needText: "请输入内容",
349
+ cancel: "取消",
350
+ sentOk: "已送达 {name}", sentFail: "未能送达 {name}",
351
+ noMatchConversation: "没有匹配的会话", lastMessage: "任务",
352
+ execute: "开始执行", executing: "正在启动会话…", startedToast: "已在本机新建会话:{title}",
353
+ decline: "拒绝", confirmDecline: "确认拒绝", declinePh: "拒绝的原因(可选)",
354
+ threadPh: "输入消息,回车发送",
355
+ resizeBox: "拖动上方的横条或按上下方向键调整高度,双击恢复",
356
+ awaitingAnswer: "等待对方选择", pleaseChoose: "请选择", answered: "已选",
357
+ backToList: "返回会话列表", searchConversation: "搜索",
358
+ taskDetails: "任务详情", close: "关闭", taskOf: "任务", taskUnfold: "展开任务", taskFold: "收起",
359
+ taskTextPh: "要请对方做什么?写清要改什么、怎么算完成。第一行会作为标题。回车发送,Shift+回车换行。",
360
+ threadTitle: "往来", threadEmpty: "还没有往来消息。执行任务时有疑问会出现在这里,可以直接回复。",
361
+ firstTaskHint: "这是你们之间的第一项任务。写清要改什么、怎么算完成。",
362
+ unreadTitle: "条未读", convMenu: "更多", removeAgent: "移除这个 Agent", notDiscovered: "不在局域网内,或已离线较久",
363
+ noTaskYetShort: "还没有发过任务", emptyConversation: "还没有和 TA 往来过", emptyConversationHint: "在下面发第一项任务,之后的消息都会跟在这条任务下面。",
364
+ confirmForgetShort: "确认移除", forgetOnlineHint: "TA 现在在线:移除后要等 TA 下线再上线才会重新出现。",
365
+ confirmForget: "从列表移除这个 Agent?与 TA 的往来记录保留;TA 下次上线时会重新出现。",
366
+ removedToast: "已移除 {name};TA 下次上线时会重新出现",
367
+ noOneTitle: "还没有发现局域网里的同事", noOneBody: "请确认同事的 {host} 也安装并启用了 NetChat,并且两台机器在同一网络。Windows 防火墙提示时,请允许 {host} 访问“专用网络”。",
368
+ openDrawer: "查看详情",
369
+ openSession: "打开会话", runningHint: "执行中。做完后对方会自己报告结果,不用手动标记。", resultDone: "结果", resultFailed: "失败原因",
370
+ runNoProject: "不在项目中执行", runNoProjectHint: "由 ZCode 在 NetChat 插件自己的项目里开一个会话执行。",
371
+ executeTitle: "开始执行", executeWhichProject: "在哪个本地项目中执行?", chooseProject: "请选择项目…",
372
+ projectName: "所属项目", projectNameHint: "选填。属于同一个项目的目录填同一个名字,之后这类任务会自动选中它。",
373
+ projectNameChanges: "确认后,{project} 的所属项目会由 {old} 改为 {new}。",
374
+ executeWhichSession: "在哪个会话里执行?", newSession: "新建会话", newSessionHint: "新建一个会话来执行这项任务。",
375
+ reuseSessionHint: "放进已有的会话执行:会话保留自己的标题和模型,任务作为一项新工作排进去;它正忙时会等到下一轮。",
376
+ sessionRunning: "运行中", sessionIdle: "空闲", sessionListFailed: "会话列表没有加载出来,只能新建会话。",
377
+ reusedToast: "已放进已有会话执行:{session}",
378
+ ranInSession: "已有会话",
379
+ resend: "重新发送",
380
+ attachedSession: "附带的会话记录", loadMore: "加载更多", truncated: "(已截断)",
381
+ self: "我",
382
+ stNew: "待处理", stAccepted: "已接手", stStarting: "启动中", stRunning: "执行中", stDone: "已完成", stFailed: "失败", stDeclined: "已拒绝",
383
+ stSending: "发送中", stDelivered: "已送达", stSendFailed: "发送失败",
384
+ theirAccepted: "对方已接手", theirRunning: "对方执行中", theirDone: "对方已完成", theirDeclined: "对方已拒绝", theirFailed: "对方未能完成",
385
+ settings: "设置", displayName: "显示名称", roleLabel: "角色标签", rolePh: "例如:前端 / 后端 / 测试", save: "保存", saved: "已保存",
386
+ teamKey: "团队共享密钥", teamKeyPh: "留空表示不验证",
387
+ teamKeyHint: "与同事设置相同的密钥后,彼此显示为“已验证”,并且只有已验证的发件人才能触发自动执行。密钥本身不会发出,只传它的短指纹。",
388
+ autoExecute: "自动执行", autoOff: "关闭(收到后等我确认)", autoTrusted: "仅限已验证的发件人",
389
+ autoWarn: "开启后,已验证发件人发来的任务会立即在本机新建会话并开始执行,不再等待确认。",
390
+ autoAnswer: "Agent 自动回答", autoAnswerOff: "关闭(等我选择)", autoAnswerOn: "开启(发任务的会话自己选最优项)",
391
+ autoAnswerHint: "发出去的任务里,对方(执行方)提的问题带选项时:关闭则等你点选;开启则由发任务的会话按需求替你选。与“通知飞书”互斥。",
392
+ autoAnswerWarn: "开启后,对方一提问,发任务的会话就会立刻替你选,不会等你;想自己选就关掉它,或改用飞书提醒。",
393
+ autoAnswerBlocked: "通知飞书开着时不能开自动回答:提问由谁答只能选一边。先关掉通知飞书。",
394
+ defaultProject: "默认执行项目", defaultProjectHint: "任务带有项目提示且能匹配上时,优先使用匹配到的项目。", noDefault: "每次询问",
395
+ defaultModel: "默认执行模型", defaultModelHint: "执行任务时新建会话所用的模型。只在当前宿主能列出模型时可选;选了的模型宿主后来不再提供时,会用它自己的默认并在设置里提示。", noDefaultModel: "用 {host} 自己的默认",
396
+ defaultModelNone: "这个宿主没有列出可用模型,执行时用 {host} 自己的默认。", defaultModelStale: "设置里的默认模型「{model}」已不在 {host} 的可用模型里;执行时会用 {host} 自己的默认,请重新选择或改为“用默认”。",
397
+ ranWith: "执行环境",
398
+ announce: "在局域网中广播本机", announceHint: "关闭后其他 Agent 不会自动发现你,但已经知道地址的 Agent 仍能联系你。",
399
+ feishu: "飞书", feishuHint: "绑上你自己的飞书:发出去的任务里,对方提的问题要你选择时,会提醒到你的飞书,在飞书里回复那条提醒就能作答(回编号或选项原文);也可以回到 NetChat 面板里选。多个提问同时等着时,回复对应那条提醒即可。群聊不接收。装好即连。",
400
+ feishuStateOff: "桥接没有运行", feishuStateStopped: "已停止", feishuStateConnecting: "正在连接", feishuStateListening: "正在监听单聊消息", feishuStateReconnecting: "连接断开,正在重连", feishuStateUnconfigured: "还没有填写应用凭据",
401
+ feishuAppId: "App ID", feishuAppSecret: "App Secret", feishuSecretSaved: "已保存", feishuSecretPh: "留空保持不变",
402
+ feishuCredentialsHint: "这里已预填构建自带的应用,装好即连,不必改。要换成自己企业的应用:凭据在 开放平台 → 凭据与基础信息 里。应用要开通“读取用户发给机器人的单聊消息”“以应用身份发消息”“获取与上传图片或文件”,事件订阅选“长连接”并添加“接收消息”。Secret 只保存在这台机器的 ~/.netchat/feishu.json,不会显示回来。",
403
+ feishuSave: "保存并连接", feishuReconnect: "重新连接",
404
+ feishuConfigure: "凭据被清空了:填上 App ID 和 App Secret,点“保存并连接”。",
405
+ feishuBindHow: "绑定:在飞书里给这个机器人发一句话(比如“绑定”),它会回一个 6 位绑定码;把码贴到这里。直接把机器人那条消息整条贴过来也行,会从里面认出码。码在绑定成功前不会变。同一台机器上 ZCode 和 DeepSeek Harness 都装了 NetChat 时,机器人回复的开头写着这个码属于哪台机器的哪个宿主,要贴到它的面板里。",
406
+ feishuCodePh: "绑定码", feishuBind: "绑定", feishuUnbind: "解绑", feishuIgnore: "移除",
407
+ feishuNotify: "通知飞书:有等你选择的提问、以及你发出的任务完成时,提醒到已绑定的飞书;提问在飞书里回复即可作答", feishuNotifyHint: "提问和选项发到你的飞书,回复那条提醒作答(回编号或选项原文都行,也可以在面板里点);任务完成或失败时也会发一条简短通知(100 字内),不需要回复。与“Agent 自动回答”互斥。", feishuNotifyBlocked: "自动回答开着时不能开通知:提问由谁答只能选一边。",
408
+ feishuNotifyOn: "已开启飞书提醒", feishuNotifyOff: "已关闭飞书提醒",
409
+ feishuBound: "已绑定", feishuBoundHint: "这是这台机器主人的飞书。解绑后不再提醒。",
410
+ feishuNoBindings: "还没有绑定任何人。",
411
+ feishuLast: "最近发来:{time}", feishuNever: "还没发过消息",
412
+ permissions: "权限", grant: "授予权限", permRead: "读取会话", permWrite: "创建会话", permNotify: "通知",
413
+ yes: "已授予", no: "未授予", unknown: "未知",
414
+ diagnostics: "诊断", copy: "复制诊断信息", copied: "已复制",
415
+ service: "服务", port: "端口", addresses: "本机地址", instanceId: "实例 ID", version: "版本",
416
+ ownerExtension: "{host} 扩展", ownerMcp: "MCP 回退进程",
417
+ extensionHint: "当前由 MCP 进程托管服务:可以收发消息,但不能在本机新建会话。请在“设置 → 插件”中激活 NetChat 扩展。",
418
+ clearKey: "清除密钥",
419
+ },
420
+ en: {
421
+ appName: "NetChat", tagline: "LAN agents",
422
+ booting: "Connecting to NetChat…",
423
+ noHostTitle: "Cannot reach the {host} host", noHostBody: "This page must open as the NetChat plugin panel inside {host}.",
424
+ fatalTitle: "The NetChat service did not start", retry: "Retry", refresh: "Refresh",
425
+ online: "online", offline: "offline", never: "never seen", loading: "Loading…",
426
+ verified: "verified", unverified: "unverified", noKey: "no key",
427
+ projectHint: "Related project",
428
+ needText: "Type a message first",
429
+ cancel: "Cancel",
430
+ sentOk: "Delivered to {name}", sentFail: "Not delivered to {name}",
431
+ noMatchConversation: "No conversation matches", lastMessage: "Task",
432
+ execute: "Start", executing: "Starting a session…", startedToast: "Started a local session: {title}",
433
+ decline: "Decline", confirmDecline: "Confirm decline", declinePh: "Reason (optional)",
434
+ threadPh: "Type a message; Enter sends",
435
+ resizeBox: "Drag the bar above, or press the up and down arrows, to resize; double-click to reset",
436
+ awaitingAnswer: "Waiting for a choice", pleaseChoose: "Choose", answered: "Chosen",
437
+ backToList: "Back to conversations", searchConversation: "Search",
438
+ taskDetails: "Task details", close: "Close", taskOf: "Task", taskUnfold: "Show request", taskFold: "Fold",
439
+ taskTextPh: "What should they do? Say what to change and what counts as done. The first line becomes the title. Enter sends; Shift+Enter makes a new line.",
440
+ threadTitle: "Messages", threadEmpty: "No messages yet. Questions that come up while the task is being done appear here, and can be answered here.",
441
+ firstTaskHint: "This is the first task between you. Say what to change and what counts as done.",
442
+ unreadTitle: "unread", convMenu: "More", removeAgent: "Remove this agent", notDiscovered: "Not on the LAN, or away for a while",
443
+ noTaskYetShort: "No task sent yet", emptyConversation: "Nothing exchanged yet", emptyConversationHint: "Send the first task below; messages after that follow it.",
444
+ confirmForgetShort: "Confirm removal", forgetOnlineHint: "They are online now: they come back after they have been away and return.",
445
+ confirmForget: "Remove this agent from the list? What was exchanged with them is kept; they reappear when they next come online.",
446
+ removedToast: "Removed {name}; they reappear when they next come online",
447
+ noOneTitle: "No teammates found on the LAN yet", noOneBody: "Make sure your teammates installed and enabled NetChat in {host} and that both machines share a network. If Windows Firewall asks, allow {host} on private networks.",
448
+ openDrawer: "Details",
449
+ openSession: "Open session", runningHint: "Running. The session reports the outcome itself when it is done; nothing to mark by hand.", resultDone: "Result", resultFailed: "Why it failed",
450
+ runNoProject: "Not in a project", runNoProjectHint: "ZCode opens the session in the NetChat plugin's own project.",
451
+ executeTitle: "Start", executeWhichProject: "Which local project should it run in?", chooseProject: "Choose a project…",
452
+ projectName: "Project", projectNameHint: "Optional. Give the directories of one project the same name; tasks of that project then open on this one.",
453
+ projectNameChanges: "On start, {project} will go by {new} instead of {old}.",
454
+ executeWhichSession: "Which session should it run in?", newSession: "New session", newSessionHint: "A new session is started for this task.",
455
+ reuseSessionHint: "The task is put into the existing session, which keeps its own title and model; it is queued as a new piece of work, and waits for the next turn if the session is busy.",
456
+ sessionRunning: "running", sessionIdle: "idle", sessionListFailed: "The session list did not load; only a new session can be used.",
457
+ reusedToast: "Put into the existing session: {session}",
458
+ ranInSession: "existing session",
459
+ resend: "Send again",
460
+ attachedSession: "Attached session", loadMore: "Load more", truncated: "(truncated)",
461
+ self: "Me",
462
+ stNew: "New", stAccepted: "Accepted", stStarting: "Starting", stRunning: "Running", stDone: "Done", stFailed: "Failed", stDeclined: "Declined",
463
+ stSending: "Sending", stDelivered: "Delivered", stSendFailed: "Not delivered",
464
+ theirAccepted: "Accepted by peer", theirRunning: "Peer is working on it", theirDone: "Peer finished", theirDeclined: "Declined by peer", theirFailed: "Peer could not finish",
465
+ settings: "Settings", displayName: "Display name", roleLabel: "Role", rolePh: "e.g. frontend / backend / QA", save: "Save", saved: "Saved",
466
+ teamKey: "Team key", teamKeyPh: "Leave empty to skip verification",
467
+ teamKeyHint: "Peers with the same key show as verified, and only verified senders can trigger automatic execution. The key itself never leaves this machine; only a short fingerprint is announced.",
468
+ autoExecute: "Auto-run", autoOff: "Off (wait for me)", autoTrusted: "Verified senders only",
469
+ autoWarn: "Tasks from verified senders start a new local session immediately, without waiting for you.",
470
+ autoAnswer: "Agent answers questions", autoAnswerOff: "Off (wait for me)", autoAnswerOn: "On (the session that sent the task picks)",
471
+ autoAnswerHint: "When the side doing the work asks a question with choices about a task you sent: off waits for you to pick; on lets the session that sent the task choose for you. Exclusive with Feishu reminders.",
472
+ autoAnswerWarn: "On, a question is answered by the sending session at once, without waiting for you. Turn it off to pick yourself, or use Feishu reminders instead.",
473
+ autoAnswerBlocked: "Cannot be on while Feishu reminders are on: a question is answered by one or the other. Turn reminders off first.",
474
+ defaultProject: "Default project", defaultProjectHint: "Used when the task carries no project hint or it matches nothing.", noDefault: "Ask every time",
475
+ defaultModel: "Default model", defaultModelHint: "The model a session is started with when a task is executed. Offered only while this host lists its models; should the host stop offering the chosen one, its own default is used and the sheet says so.", noDefaultModel: "Use {host}'s own default",
476
+ defaultModelNone: "This host lists no models; sessions are started with {host}'s own default.", defaultModelStale: "The default model “{model}” is no longer offered by {host}; sessions are started with {host}'s own default. Pick another or choose “use the default”.",
477
+ ranWith: "Runs in",
478
+ announce: "Announce this machine on the LAN", announceHint: "Other agents will not discover you automatically; agents that already know your address can still reach you.",
479
+ feishu: "Feishu", feishuHint: "Bind your own Feishu: when a task you sent gets a question that waits on your choice, you are reminded on Feishu and can answer by replying to that reminder (number or option text); the panel works too. With several questions waiting, reply to the one you mean. Group chats are not received. Connects on its own.",
480
+ feishuStateOff: "Bridge not running", feishuStateStopped: "Stopped", feishuStateConnecting: "Connecting", feishuStateListening: "Listening for direct messages", feishuStateReconnecting: "Disconnected, reconnecting", feishuStateUnconfigured: "App credentials not filled in",
481
+ feishuAppId: "App ID", feishuAppSecret: "App Secret", feishuSecretSaved: "saved", feishuSecretPh: "Leave blank to keep",
482
+ feishuCredentialsHint: "Prefilled with the app this build ships, which connects on its own; no need to change it. To use your own app: credentials are found under Credentials & Basic Info in the developer console. The app needs “Read messages users send to the bot”, “Send messages as the app” and “Upload/download images and files”, with events received over the long connection and “Receive message” added. The Secret stays in this machine's ~/.netchat/feishu.json and is never shown back.",
483
+ feishuSave: "Save and connect", feishuReconnect: "Reconnect",
484
+ feishuConfigure: "Credentials were cleared: fill in the App ID and App Secret and press “Save and connect”.",
485
+ feishuBindHow: "To bind: write to the bot in Feishu (anything, e.g. “bind”); it answers with a 6-character pairing code. Paste it here — or paste the bot's whole message, the code is found in it. The code stays the same until you are bound. When this machine runs NetChat in both ZCode and DeepSeek Harness, the bot's reply opens with the machine and host its code belongs to: paste it into that one's panel.",
486
+ feishuCodePh: "Pairing code", feishuBind: "Bind", feishuUnbind: "Unbind", feishuIgnore: "Remove",
487
+ feishuNotify: "Notify on Feishu: remind the bound account when a question waits on you (answerable by replying) and when a task you sent is finished", feishuNotifyHint: "The question and its choices go to your Feishu; reply to that reminder to answer (number or option text), or pick in the panel. A task of yours that is done or failed is announced in a short notice (under 100 characters) that needs no reply. Exclusive with “Agent answers questions”.", feishuNotifyBlocked: "Cannot be on while the agent answers questions: one or the other.",
488
+ feishuNotifyOn: "Feishu reminders on", feishuNotifyOff: "Feishu reminders off",
489
+ feishuBound: "Bound", feishuBoundHint: "This is this machine owner's Feishu. Unbind to stop the reminders.",
490
+ feishuNoBindings: "Nobody is bound yet.",
491
+ feishuLast: "Last message: {time}", feishuNever: "No message yet",
492
+ permissions: "Permissions", grant: "Grant", permRead: "Read sessions", permWrite: "Create sessions", permNotify: "Notifications",
493
+ yes: "granted", no: "not granted", unknown: "unknown",
494
+ diagnostics: "Diagnostics", copy: "Copy diagnostics", copied: "Copied",
495
+ service: "Service", port: "Port", addresses: "Addresses", instanceId: "Instance ID", version: "Version",
496
+ ownerExtension: "{host} extension", ownerMcp: "MCP fallback",
497
+ extensionHint: "The service is hosted by an MCP process: messaging works, but tasks cannot start sessions here. Activate the NetChat extension under Settings → Plugins.",
498
+ clearKey: "Clear key",
499
+ },
500
+ };
501
+
502
+ let lang = "zh";
503
+ // The host the panel runs in, named by the host itself in ui/initialize (hostContext.host.label).
504
+ // ZCode's MCP Apps host sends nothing there, so its name stays the default; the DeepSeek
505
+ // Harness shell sends its own. Copy that mentions the host says `{host}`.
506
+ let hostName = "ZCode";
507
+ const fill = (text, params) => {
508
+ let out = text.split("{host}").join(hostName);
509
+ if (params) for (const [name, value] of Object.entries(params)) out = out.split(`{${name}}`).join(String(value));
510
+ return out;
511
+ };
512
+ const t = (key, params) => fill((STRINGS[lang] ?? STRINGS.zh)[key] ?? STRINGS.zh[key] ?? key, params);
513
+
514
+ // Lucide outline icons (constant markup only).
515
+ const ICONS = {
516
+ zap: '<polygon points="13 2 3 14 12 14 11 22 21 10 12 10 13 2"/>',
517
+ users: '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/>',
518
+ inbox: '<polyline points="22 12 16 12 14 15 10 15 8 12 2 12"/><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"/>',
519
+ send: '<line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>',
520
+ sliders: '<line x1="4" y1="21" x2="4" y2="14"/><line x1="4" y1="10" x2="4" y2="3"/><line x1="12" y1="21" x2="12" y2="12"/><line x1="12" y1="8" x2="12" y2="3"/><line x1="20" y1="21" x2="20" y2="16"/><line x1="20" y1="12" x2="20" y2="3"/><line x1="1" y1="14" x2="7" y2="14"/><line x1="9" y1="8" x2="15" y2="8"/><line x1="17" y1="16" x2="23" y2="16"/>',
521
+ refresh: '<polyline points="23 4 23 10 17 10"/><polyline points="1 20 1 14 7 14"/><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"/>',
522
+ back: '<line x1="19" y1="12" x2="5" y2="12"/><polyline points="12 19 5 12 12 5"/>',
523
+ play: '<polygon points="5 3 19 12 5 21 5 3"/>',
524
+ check: '<polyline points="20 6 9 17 4 12"/>',
525
+ x: '<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>',
526
+ reply: '<polyline points="9 17 4 12 9 7"/><path d="M20 18v-2a4 4 0 0 0-4-4H4"/>',
527
+ file: '<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/>',
528
+ message: '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',
529
+ search: '<circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>',
530
+ external: '<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"/><polyline points="15 3 21 3 21 9"/><line x1="10" y1="14" x2="21" y2="3"/>',
531
+ trash: '<polyline points="3 6 5 6 21 6"/><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"/>',
532
+ copy: '<rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>',
533
+ alert: '<path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/>',
534
+ more: '<circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/>',
535
+ up: '<polyline points="18 15 12 9 6 15"/>',
536
+ down: '<polyline points="6 9 12 15 18 9"/>',
537
+ };
538
+ const icon = (name) => {
539
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
540
+ for (const [key, value] of Object.entries({
541
+ class: "i", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", "stroke-width": "2",
542
+ "stroke-linecap": "round", "stroke-linejoin": "round", "aria-hidden": "true",
543
+ })) svg.setAttribute(key, value);
544
+ svg.innerHTML = ICONS[name] ?? "";
545
+ return svg;
546
+ };
547
+
548
+ // ---- DOM ----------------------------------------------------------------------------------
549
+ // A view is described as a tree of plain objects, and patch() applies that description to
550
+ // the real DOM: an element that is still there in the new description is kept, and only its
551
+ // changed parts are written. Nothing is rebuilt that did not change, so a scroll position,
552
+ // an open select, the focus and the caret survive a refresh — the panel re-renders after
553
+ // every poll, and rebuilding used to reset all of these.
554
+ // All dynamic text goes through text nodes; markup is only ever written for the icons above.
555
+ function h(tag, props, ...children) {
556
+ return { tag, props: props ?? {}, children: children.flat(Infinity).filter((child) => child != null && child !== false) };
557
+ }
558
+
559
+ const EVENT_PROPS = new Set(["onclick", "oninput", "onkeydown", "onkeyup", "onchange", "onscroll", "ondblclick", "ontoggle",
560
+ "onpointerdown", "onpointermove", "onpointerup", "onpointercancel"]);
561
+ const PROPERTY_PROPS = new Set(["value", "checked", "disabled", "selected"]);
562
+ const isText = (child) => typeof child === "string" || typeof child === "number";
563
+ const isElement = (child) => child && typeof child === "object" && "tag" in child;
564
+ /** Rows that carry a key are matched by it, so removing one does not rebuild the rest. */
565
+ const keyOf = (child) => (isElement(child) && child.props.key != null ? String(child.props.key) : null);
566
+
567
+ function make(vnode) {
568
+ if (isText(vnode)) return document.createTextNode(String(vnode));
569
+ if (vnode instanceof Node) return vnode.cloneNode(true); // a ready-made node, such as an icon
570
+ const el = document.createElement(vnode.tag);
571
+ for (const [key, value] of Object.entries(vnode.props)) setProp(el, key, value);
572
+ for (const child of vnode.children) el.append(make(child));
573
+ return el;
574
+ }
575
+
576
+ /** Applies a description to the element at that place, or makes a new one when it is a different kind. */
577
+ function patch(el, vnode) {
578
+ if (isText(vnode)) {
579
+ const text = String(vnode);
580
+ if (el?.nodeType === Node.TEXT_NODE) {
581
+ if (el.nodeValue !== text) el.nodeValue = text;
582
+ return el;
583
+ }
584
+ return document.createTextNode(text);
585
+ }
586
+ if (vnode instanceof Node) return el?.nodeType === Node.ELEMENT_NODE ? el : vnode.cloneNode(true);
587
+ if (el?.nodeType !== Node.ELEMENT_NODE || el.tagName.toLowerCase() !== vnode.tag) return make(vnode);
588
+ syncProps(el, vnode.props);
589
+ syncChildren(el, vnode.children);
590
+ return el;
591
+ }
592
+
593
+ function setProp(el, key, value) {
594
+ // The key is what keyed rows are matched by on the element; it is written as data-key.
595
+ if (key === "key") { if (value != null) el.setAttribute("data-key", String(value)); return; }
596
+ if (EVENT_PROPS.has(key)) {
597
+ const name = key.slice(2).toLowerCase();
598
+ const handlers = el._handlers ?? (el._handlers = {});
599
+ handlers[name] = typeof value === "function" ? value : null;
600
+ // One listener per event, serving whatever the current description says.
601
+ if (!el._listening?.[name]) {
602
+ (el._listening ??= {})[name] = true;
603
+ el.addEventListener(name, (event) => el._handlers[name]?.(event));
604
+ }
605
+ return;
606
+ }
607
+ if (value == null || value === false) {
608
+ if (PROPERTY_PROPS.has(key)) el[key] = key === "value" ? "" : false;
609
+ else el.removeAttribute(key);
610
+ return;
611
+ }
612
+ if (key === "class") el.className = String(value);
613
+ else if (key === "dataset") for (const [name, data] of Object.entries(value)) el.dataset[name] = data == null ? "" : String(data);
614
+ else if (PROPERTY_PROPS.has(key)) el[key] = key === "value" ? String(value) : Boolean(value);
615
+ else if (value === true) el.setAttribute(key, "");
616
+ else el.setAttribute(key, String(value));
617
+ }
618
+
619
+ /** Writes only what differs from the element's current state. */
620
+ function syncProps(el, props) {
621
+ const handlers = el._handlers ?? {};
622
+ for (const [key, value] of Object.entries(props)) {
623
+ if (key === "key") {
624
+ const next = value == null ? null : String(value);
625
+ if ((el.getAttribute("data-key")) !== next) setProp(el, key, value);
626
+ continue;
627
+ }
628
+ if (EVENT_PROPS.has(key)) {
629
+ const name = key.slice(2).toLowerCase();
630
+ const next = typeof value === "function" ? value : null;
631
+ if (handlers[name] !== next) setProp(el, key, value);
632
+ continue;
633
+ }
634
+ if (key === "dataset") {
635
+ for (const [name, data] of Object.entries(value ?? {})) {
636
+ const next = data == null ? "" : String(data);
637
+ if (el.dataset[name] !== next) el.dataset[name] = next;
638
+ }
639
+ continue;
640
+ }
641
+ if (PROPERTY_PROPS.has(key)) {
642
+ // What the user is typing is the truth; the description only lags behind it. A
643
+ // select is not skipped: its chosen option is state, and must follow the description.
644
+ if (key === "value" && document.activeElement === el && el.tagName !== "SELECT") continue;
645
+ const next = key === "value" ? String(value ?? "") : Boolean(value);
646
+ if (value == null || value === false ? el[key] !== (key === "value" ? "" : false) : el[key] !== next) setProp(el, key, value);
647
+ continue;
648
+ }
649
+ const current = key === "class" ? el.className : el.getAttribute(key);
650
+ const next = value === true ? "" : String(value);
651
+ if (current !== next) setProp(el, key, value);
652
+ }
653
+ // What the description no longer carries is cleared, so nothing lingers on a kept element.
654
+ for (const name of Object.keys(handlers)) {
655
+ const prop = `on${name}`;
656
+ if (!(prop in props)) handlers[name] = null;
657
+ }
658
+ for (const attr of [...el.attributes]) {
659
+ if (attr.name === "class" || attr.name.startsWith("data-")) continue;
660
+ if (!(attr.name in props)) el.removeAttribute(attr.name);
661
+ }
662
+ if (!("class" in props) && el.className) el.className = "";
663
+ }
664
+
665
+ function syncChildren(el, children) {
666
+ const current = [...el.childNodes];
667
+ const keyed = children.length > 0 && children.every((child) => keyOf(child) !== null);
668
+ if (keyed) {
669
+ const byKey = new Map();
670
+ for (const node of current) {
671
+ const key = node.nodeType === Node.ELEMENT_NODE ? node.getAttribute("data-key") : null;
672
+ if (key !== null && !byKey.has(key)) byKey.set(key, node);
673
+ }
674
+ // Rows that are gone go first, so that what remains is only what is wanted: then a row
675
+ // is moved only when it really is out of place. (Removing afterwards would move the
676
+ // row after a removed one on every render — and moving a node takes the focus off it.)
677
+ const wanted = new Set(children.map((child) => keyOf(child)));
678
+ for (const node of current) {
679
+ const key = node.nodeType === Node.ELEMENT_NODE ? node.getAttribute("data-key") : null;
680
+ if (!wanted.has(key)) node.remove();
681
+ }
682
+ let cursor = el.firstChild;
683
+ for (const child of children) {
684
+ const key = keyOf(child);
685
+ const node = byKey.get(key) ?? null;
686
+ const next = node ? patch(node, child) : make(child);
687
+ if (next !== cursor) el.insertBefore(next, cursor);
688
+ cursor = next.nextSibling;
689
+ }
690
+ return;
691
+ }
692
+ children.forEach((child, index) => {
693
+ const existing = el.childNodes[index] ?? null;
694
+ const next = patch(existing, child);
695
+ if (!existing) el.append(next);
696
+ else if (next !== existing) el.replaceChild(next, existing);
697
+ });
698
+ while (el.childNodes.length > children.length) el.lastChild.remove();
699
+ }
700
+
701
+ /** Applies a list of children to a container that holds nothing else. */
702
+ function renderChildren(container, children) {
703
+ syncChildren(container, children.flat(Infinity).filter((child) => child != null && child !== false));
704
+ }
705
+
706
+ /** Renders a description into a container, keeping everything that did not change. */
707
+ function render(container, vnode) {
708
+ const existing = container.firstChild ?? null;
709
+ const next = patch(existing, vnode);
710
+ if (!existing) container.append(next);
711
+ else if (next !== existing) container.replaceChild(next, existing);
712
+ }
713
+
714
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
715
+
716
+ function toast(message, danger = false) {
717
+ const el = document.getElementById("toast");
718
+ el.textContent = message;
719
+ el.className = `toast${danger ? " danger" : ""}`;
720
+ el.hidden = false;
721
+ clearTimeout(toast.timer);
722
+ toast.timer = setTimeout(() => (el.hidden = true), danger ? 7000 : 3500);
723
+ }
724
+
725
+ const pickLang = (locale) => (/^zh\b/i.test(String(locale ?? "")) ? "zh" : locale ? "en" : (/^zh/i.test(navigator.language) ? "zh" : "en"));
726
+ const pickHost = (host) => (typeof host?.label === "string" && host.label.trim() ? host.label.trim().slice(0, 40) : "ZCode");
727
+
728
+ /** Tool error codes that deserve a sentence of their own; anything else shows the server's message. */
729
+ const ERROR_HINTS = {
730
+ not_granted: ["尚未授予 NetChat 会话权限。打开右上角的设置 → 权限 → “授予权限”。", "NetChat has not been granted session access. Open Settings → Permissions → Grant."],
731
+ extension_required: ["本机的宿主没有提供会话能力,无法在这里新建会话或读取会话;收发任务和线程消息不受影响。", "This host offers no session access here, so sessions cannot be started or read from the panel; sending tasks and thread messages still works."],
732
+ // The code does not change until the person is bound, so "get a new one" would not have
733
+ // helped. With ZCode and DeepSeek Harness both running NetChat, the bot may have answered
734
+ // from the other one; its reply names the machine and host the code belongs to.
735
+ code_not_found: ["这里没有正在等待绑定的绑定码。请看机器人最新那条回复的开头写的是哪台机器、哪个宿主(如「〈机器名〉的 ZCode」),绑定码要贴到它的面板里;如果写的正是这里,把那条回复整条复制过来再贴一次(码在绑定成功前不会变);如果对方还没给机器人发过话,先发一句(比如“绑定”)。", "No one is waiting here with a code from what you pasted. The bot's latest reply opens with the machine and host its code belongs to (e.g. “〈machine〉’s ZCode”): paste the code into that one's panel. If it names this one, copy the reply whole and paste it again (a code stays the same until the person is bound); if they have not written to the bot yet, have them send it anything (e.g. “bind”)."],
736
+ // More than one waiting code is in what was pasted: the panel has no list of who is
737
+ // waiting, so it points at the agent.
738
+ ambiguous_code: ["贴过来的内容里能对上不止一个等待绑定的码,所以没有绑任何人。请让 Agent 用 net_chat_feishu 看一下等待绑定的人、确认是哪位后再绑。", "More than one waiting code is in what you pasted, so nobody was bound. Ask the agent to list who is waiting with net_chat_feishu, confirm who it is, and bind that person."],
739
+ };
740
+ const explain = (error) => {
741
+ const hint = ERROR_HINTS[error.code];
742
+ return fill(hint ? hint[lang === "zh" ? 0 : 1] : error.message);
743
+ };
744
+
745
+ function ago(iso) {
746
+ const ms = Date.now() - new Date(iso).getTime();
747
+ if (!Number.isFinite(ms)) return "";
748
+ return agoMs(ms);
749
+ }
750
+ function agoMs(ms) {
751
+ if (ms === null || ms === undefined) return t("never");
752
+ if (ms < 60_000) return lang === "zh" ? "刚刚" : "just now";
753
+ if (ms < 3_600_000) return lang === "zh" ? `${Math.round(ms / 60_000)} 分钟前` : `${Math.round(ms / 60_000)} min ago`;
754
+ if (ms < 86_400_000) return lang === "zh" ? `${Math.round(ms / 3_600_000)} 小时前` : `${Math.round(ms / 3_600_000)} h ago`;
755
+ return new Date(Date.now() - ms).toLocaleDateString();
756
+ }
757
+ function clock(iso) {
758
+ const date = new Date(iso);
759
+ return Number.isNaN(date.getTime()) ? "" : date.toLocaleString(undefined, { month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" });
760
+ }
761
+ const clipText = (text, max) => {
762
+ const value = String(text ?? "");
763
+ return value.length > max ? `${value.slice(0, max)}…` : value;
764
+ };
765
+ function avatar(name, small = false) {
766
+ let hash = 0;
767
+ for (const char of String(name)) hash = (hash * 31 + char.codePointAt(0)) >>> 0;
768
+ const el = h("span", { class: `avatar${small ? " sm" : ""}`, style: `background:hsl(${hash % 360} 58% 44%)`, "aria-hidden": "true" },
769
+ Array.from(String(name || "?"))[0]?.toUpperCase() ?? "?");
770
+ return el;
771
+ }
772
+
773
+ // ---- host bridge (MCP Apps: JSON-RPC over postMessage to the parent window) ----------------
774
+ const bridge = (() => {
775
+ const pending = new Map();
776
+ let nextId = 1;
777
+ const send = (message) => window.parent.postMessage(message, "*");
778
+ window.addEventListener("message", (event) => {
779
+ if (event.source !== window.parent) return;
780
+ const message = event.data;
781
+ if (!message || message.jsonrpc !== "2.0") return;
782
+ if (message.method && message.id !== undefined) {
783
+ // A host -> app request. We implement nothing beyond the acknowledgements below.
784
+ const known = message.method === "ping" || message.method === "ui/message";
785
+ send({ jsonrpc: "2.0", id: message.id, ...(known ? { result: {} } : { error: { code: -32601, message: `Unsupported method: ${message.method}` } }) });
786
+ return;
787
+ }
788
+ if (message.method) {
789
+ // A host -> app notification. The dsh shell sends `netchat/openTask` when a task is
790
+ // picked in the board above the panel: the conversation that holds the task is
791
+ // shown with the task's drawer open, as if its row had been clicked.
792
+ if (message.method === "netchat/openTask" && typeof message.params?.taskId === "string") {
793
+ void showTask(message.params.taskId);
794
+ }
795
+ return;
796
+ }
797
+ const entry = pending.get(message.id);
798
+ if (!entry) return;
799
+ pending.delete(message.id);
800
+ clearTimeout(entry.timer);
801
+ if (message.error) entry.reject(Object.assign(new Error(message.error.message ?? "Host error"), { code: "host_error" }));
802
+ else entry.resolve(message.result);
803
+ });
804
+ return {
805
+ request(method, params, timeoutMs) {
806
+ return new Promise((resolve, reject) => {
807
+ const id = nextId++;
808
+ const timer = setTimeout(() => {
809
+ pending.delete(id);
810
+ reject(Object.assign(new Error("timeout"), { code: "timeout" }));
811
+ }, timeoutMs);
812
+ pending.set(id, { resolve, reject, timer });
813
+ send({ jsonrpc: "2.0", id, method, params });
814
+ });
815
+ },
816
+ notify(method, params) {
817
+ send({ jsonrpc: "2.0", method, ...(params ? { params } : {}) });
818
+ },
819
+ };
820
+ })();
821
+
822
+ /** Runs one of the plugin's tools on the host side; throws an Error carrying the tool's error code. */
823
+ async function call(name, args = {}, timeoutMs = CALL_TIMEOUT_MS) {
824
+ const result = await bridge.request("tools/call", { name, arguments: args }, timeoutMs);
825
+ if (result?.isError) {
826
+ const info = result.structuredContent?.error;
827
+ const text = (result.content ?? []).filter((part) => part.type === "text").map((part) => part.text).join("\n");
828
+ throw Object.assign(new Error(info?.message ?? text ?? "error"), { code: info?.code ?? "error", extra: info });
829
+ }
830
+ return result?.structuredContent ?? {};
831
+ }
832
+
833
+ // ---- state --------------------------------------------------------------------------------
834
+ const state = {
835
+ booted: false,
836
+ busy: false,
837
+ status: null,
838
+ agents: [],
839
+ // Parties the user took off the list (see the service's forgetAgent); their records stay.
840
+ hidden: [],
841
+ inbox: [],
842
+ outbox: [],
843
+ // Which conversation is open (its key), which task the drawer shows, the search in the list,
844
+ // and which task the "start" dialog is asking a project for.
845
+ conversation: null,
846
+ drawer: null,
847
+ convQuery: "",
848
+ executeDialog: null,
849
+ // The task being drafted in each conversation.
850
+ taskDrafts: new Map(),
851
+ // How tall the user dragged each box ("task" for the task box, "thread" for the drawer's reply box).
852
+ inputHeights: new Map(),
853
+ // The focusKey of the reply box a message is being sent from, so that one box alone is locked meanwhile.
854
+ sendingThread: null,
855
+ // The conversation whose "more" menu is open (its key).
856
+ menuOpen: null,
857
+ settingsOpen: false,
858
+ form: null,
859
+ projects: null,
860
+ openDetails: new Set(),
861
+ detail: new Map(),
862
+ drafts: new Map(),
863
+ exec: new Map(),
864
+ decline: new Set(),
865
+ forgetConfirm: null,
866
+ seq: 0,
867
+ };
868
+
869
+ // ---- shell ---------------------------------------------------------------------------------
870
+ function buildShell() {
871
+ renderChildren(document.getElementById("app"), [
872
+ h("header", { class: "bar" },
873
+ h("div", { class: "brand" }, icon("zap"), t("appName"), h("span", { class: "sub" }, t("tagline"))),
874
+ h("div", { class: "spacer" }),
875
+ h("button", { class: "me", id: "me", title: t("settings"), onclick: () => void openSettings() }),
876
+ h("button", { class: "icon-btn", id: "refresh", title: t("refresh"), onclick: () => void refresh() }, icon("refresh"))),
877
+ h("div", { class: "view", id: "view" }),
878
+ ]);
879
+ renderChrome();
880
+ }
881
+
882
+ function renderChrome() {
883
+ const me = document.getElementById("me");
884
+ const status = state.status;
885
+ if (!me || !status) return;
886
+ const who = status.identity ?? {};
887
+ renderChildren(me, [
888
+ h("span", { class: `dot ${status.online ? "on" : ""}` }),
889
+ h("span", {}, `${who.name ?? ""}${who.role ? ` · ${who.role}` : ""}`),
890
+ ]);
891
+ // With a single view there is no tab to carry the unread count; it sits in the top bar.
892
+ // It is the same number as the sidebar badge: unread tasks plus questions waiting on a choice.
893
+ const count = Math.max(0, Number(status.attention) || 0);
894
+ const badge = me.parentElement.querySelector(".unread-badge");
895
+ if (count) {
896
+ const next = h("span", { class: "pill hot unread-badge", title: t("unreadTitle") }, String(count));
897
+ if (badge) patch(badge, next); else me.after(make(next));
898
+ } else badge?.remove();
899
+ document.getElementById("refresh")?.classList.toggle("spin", state.busy);
900
+ }
901
+
902
+ function renderView() {
903
+ const view = document.getElementById("view");
904
+ if (!view) return;
905
+ view.classList.add("view-chat");
906
+ render(view, renderChat());
907
+ afterRenderScroll();
908
+ }
909
+
910
+ async function refresh({ silent = false } = {}) {
911
+ if (!silent) {
912
+ state.busy = true;
913
+ renderChrome();
914
+ }
915
+ try {
916
+ const [status, agents] = await Promise.all([call("net_chat_status"), call("net_chat_list_agents")]);
917
+ // Always load both: a conversation is built from what was sent and what was received,
918
+ // and the unread badge on the tab counts the inbox even while another tab is shown.
919
+ const [inbox, outbox] = await Promise.all([
920
+ call("net_chat_inbox", { limit: 100, includeHandled: true }),
921
+ call("net_chat_outbox", { limit: 100 }),
922
+ ]);
923
+ state.inbox = inbox.items ?? [];
924
+ state.outbox = outbox.items ?? [];
925
+ state.status = status;
926
+ state.agents = agents.agents ?? [];
927
+ // Older services do not report it; nothing is hidden then.
928
+ state.hidden = Array.isArray(agents.hidden) ? agents.hidden : [];
929
+ renderView();
930
+ renderChrome();
931
+ } catch (error) {
932
+ if (error.code !== "timeout") toast(explain(error), true);
933
+ if (!state.status) fatal(t("fatalTitle"), explain(error));
934
+ } finally {
935
+ if (!silent) {
936
+ state.busy = false;
937
+ renderChrome();
938
+ }
939
+ }
940
+ }
941
+
942
+ /** Long-polls the service; every event (peer up/down, new mail, receipts) triggers one refresh. */
943
+ async function pollLoop() {
944
+ let backoff = 1000;
945
+ for (;;) {
946
+ try {
947
+ const result = await call("net_chat_poll", { since: state.seq }, POLL_TIMEOUT_MS);
948
+ state.seq = result.seq ?? state.seq;
949
+ if (result.events?.length) {
950
+ // A project's name was given, changed or taken away: the project list carries the
951
+ // names, so it is loaded afresh the next time it is needed.
952
+ if (result.events.some((event) => event.type === "projects")) state.projects = null;
953
+ await refresh({ silent: true });
954
+ }
955
+ backoff = 1000;
956
+ } catch (error) {
957
+ await sleep(backoff);
958
+ backoff = Math.min(backoff * 2, 15_000);
959
+ }
960
+ }
961
+ }
962
+
963
+ /** The conversations built from what is loaded: every party discovered or in the records, with history first. */
964
+ const conversations = () =>
965
+ buildConversations({
966
+ inbox: state.inbox,
967
+ outbox: state.outbox,
968
+ me: state.status?.identity ?? {},
969
+ agents: state.agents,
970
+ hidden: state.hidden,
971
+ });
972
+ /** The conversation to show when none is chosen: the first one the search leaves, or nothing. */
973
+ const defaultConversation = () => visibleConversations(conversations(), listOptions())[0]?.key ?? null;
974
+ // The list is never filtered: finished conversations stay beside open ones, and only the
975
+ // search narrows it.
976
+ const listOptions = () => ({ filter: "all", query: state.convQuery, direction: "all" });
977
+ const currentConversation = () => conversations().find((conversation) => conversation.key === state.conversation) ?? null;
978
+
979
+ /**
980
+ * Opens a conversation. On a wide panel the list stays beside it; on a narrow one the
981
+ * conversation replaces the list until the user goes back.
982
+ */
983
+ async function openConversation(key) {
984
+ const changed = state.conversation !== key;
985
+ state.conversation = key;
986
+ state.drawer = null;
987
+ state.menuOpen = null;
988
+ state.forgetConfirm = null;
989
+ renderView();
990
+ if (changed) scrollConversationToEnd();
991
+ await refresh();
992
+ }
993
+
994
+ const INBOX_TAG = {
995
+ new: ["stNew", "accent"], accepted: ["stAccepted", "accent"], starting: ["stStarting", "accent"], running: ["stRunning", "warn"],
996
+ done: ["stDone", "ok"], failed: ["stFailed", "danger"], declined: ["stDeclined", ""],
997
+ };
998
+ const OUTBOX_TAG = {
999
+ sending: ["stSending", ""], delivered: ["stDelivered", "ok"], accepted: ["theirAccepted", "accent"], running: ["theirRunning", "warn"],
1000
+ done: ["theirDone", "ok"], failed: ["theirFailed", "danger"], declined: ["theirDeclined", "danger"], sendFailed: ["stSendFailed", "danger"],
1001
+ };
1002
+ /** "failed" means either "never delivered" or "the peer gave up"; the receipts tell them apart. */
1003
+ const outboxStatus = (item) => (item.status === "failed" && !item.receipts?.length ? "sendFailed" : item.status);
1004
+ const statusTag = (table, status) => {
1005
+ const entry = table[status];
1006
+ return entry ? h("span", { class: `tag ${entry[1]}`.trim() }, t(entry[0])) : null;
1007
+ };
1008
+
1009
+ // Threads were once stored as plain `replies`; read either shape.
1010
+ const threadOf = (item) => (Array.isArray(item.thread) ? item.thread : (item.replies ?? []).map((entry, index) => ({ id: `legacy_${index}`, text: entry.text, from: entry.to ? "me" : "peer", fromName: entry.from ?? entry.to ?? "", ts: entry.ts })));
1011
+ const roleText = (who) => (who?.role ? `${who.name}(${who.role})` : who?.name ?? "");
1012
+
1013
+ // ---- conversations: pure logic ----------------------------------------------------------------
1014
+ // Everything between the two __CHAT_LOGIC__ marks works on plain data and touches no DOM, so
1015
+ // the tests can run it on its own. It turns the inbox and the outbox — two lists of tasks,
1016
+ // each carrying its own thread — into conversations: one per other party, holding that
1017
+ // party's tasks, newest first. What was said about a task stays with that task; it is shown
1018
+ // in the task's drawer, not beside the tasks.
1019
+ //
1020
+ // The key is `peer:<id>` rather than the bare id so that a later `group:<id>` fits the same
1021
+ // shape without changing how conversations are keyed, listed or sorted.
1022
+ // __CHAT_LOGIC_START__
1023
+ const conversationKey = (peerId) => `peer:${peerId}`;
1024
+
1025
+ /**
1026
+ * The states in which a task still counts as open. A received task runs new -> accepted ->
1027
+ * starting -> running; one sent from here runs sending -> delivered -> accepted -> running.
1028
+ * Both are open until the other side finishes, declines or fails.
1029
+ */
1030
+ const OPEN_TASK_STATUSES = new Set(["new", "accepted", "starting", "running", "sending", "delivered"]);
1031
+ const taskIsOpen = (task) => OPEN_TASK_STATUSES.has(task.status);
1032
+
1033
+ /** A message of a task's thread, with who wrote it settled: "me" is this machine, anything else the other party. */
1034
+ function threadMessage(task, entry, mine) {
1035
+ return {
1036
+ id: entry.id ?? `${task.id}:${entry.ts}`,
1037
+ ts: entry.ts,
1038
+ text: String(entry.text ?? ""),
1039
+ options: Array.isArray(entry.options) ? entry.options : [],
1040
+ answer: entry.answer ? { text: entry.answer.text, ts: entry.answer.ts } : null,
1041
+ answerOf: entry.answerOf ?? null,
1042
+ mine,
1043
+ // A message this machine wrote that never reached the other side.
1044
+ failed: mine && entry.delivery === "failed",
1045
+ error: mine ? (entry.error ?? null) : null,
1046
+ };
1047
+ }
1048
+
1049
+ /**
1050
+ * Everything that happened around one task, oldest first: the task itself, the messages
1051
+ * exchanged about it and the receipts the other side sent. This is what the drawer shows.
1052
+ */
1053
+ function taskTimeline(task, mine) {
1054
+ const items = [{ type: "task", ts: task.ts, task }];
1055
+ for (const entry of threadOf(task)) {
1056
+ items.push({ type: "message", ...threadMessage(task, entry, entry.from === "me") });
1057
+ }
1058
+ // Receipts exist only on a task this machine sent: they are the other side's progress.
1059
+ for (const receipt of task.receipts ?? []) {
1060
+ items.push({ type: "receipt", ts: receipt.ts, status: receipt.status, detail: receipt.detail ?? "" });
1061
+ }
1062
+ items.sort((a, b) => orderKey(a).localeCompare(orderKey(b)) || rankOf(a) - rankOf(b) || String(a.id ?? "").localeCompare(String(b.id ?? "")));
1063
+ return items;
1064
+ }
1065
+
1066
+ // Within one timestamp: the task, then what was said about it, then the receipts.
1067
+ const rankOf = (item) => (item.type === "task" ? 0 : item.type === "message" ? 1 : 2);
1068
+
1069
+ /**
1070
+ * What the timeline is sorted by. A real ISO timestamp compares correctly as text; a
1071
+ * missing or malformed one sorts before every real one, so one odd record cannot drag an
1072
+ * item to the wrong place the way the text "undefined" would.
1073
+ */
1074
+ const orderKey = (item) => (Number.isFinite(Date.parse(item.ts)) ? String(item.ts) : "");
1075
+
1076
+ /**
1077
+ * One task as the chat shows it: the task itself, which side it is on, and what is new in it.
1078
+ * `mine` means this machine sent it.
1079
+ */
1080
+ function taskEntry(task, mine) {
1081
+ const messages = threadOf(task).map((entry) => threadMessage(task, entry, entry.from === "me"));
1082
+ const theirs = messages.filter((message) => !message.mine);
1083
+ const openQuestions = theirs.filter((message) => message.options.length > 0 && !message.answer);
1084
+ return {
1085
+ id: task.id,
1086
+ ts: task.ts,
1087
+ task,
1088
+ mine,
1089
+ // The newest thing that happened around the task decides where it sits and how it is listed.
1090
+ lastTs: taskTimeline(task, mine).at(-1)?.ts ?? task.ts,
1091
+ // Messages from the other side that have not been looked at yet. What has been looked
1092
+ // at is kept by the service as a count on the task (seenThread), so it is still true
1093
+ // after the panel is closed and reopened. Opening the task's drawer is what looks at
1094
+ // them; a question is counted here too until it is looked at, and separately below
1095
+ // until it is answered.
1096
+ unseen: Math.max(0, theirs.length - seenThreadOf(task)),
1097
+ openQuestions: openQuestions.length,
1098
+ };
1099
+ }
1100
+
1101
+ /** How many of the other side's messages in this task's thread have been looked at. */
1102
+ function seenThreadOf(task) {
1103
+ return Math.min(Number.isInteger(task.seenThread) ? task.seenThread : 0, threadOf(task).filter((entry) => entry.from !== "me").length);
1104
+ }
1105
+
1106
+ /**
1107
+ * Builds the conversations from both lists, one per other party.
1108
+ *
1109
+ * `agents` are the parties discovered on the LAN. Each gets a conversation even before there
1110
+ * is anything in it, so that a first task can be sent to someone new. For a party that is
1111
+ * both discovered and in the records, what discovery reports wins for the name and role,
1112
+ * because it is the fresher of the two.
1113
+ *
1114
+ * `hidden` are the parties the user took off the list. Their records are kept, but not shown:
1115
+ * the party comes back by itself when it is next seen online (the service drops it from the
1116
+ * list then), which is also what brings its old tasks back into the list.
1117
+ */
1118
+ function buildConversations({ inbox, outbox, me, agents = [], hidden = [] }) {
1119
+ const byKey = new Map();
1120
+ const hiddenKeys = new Set(hidden.map((id) => conversationKey(id)));
1121
+ const conversationFor = (peer) => {
1122
+ const key = conversationKey(peer.id);
1123
+ let conversation = byKey.get(key);
1124
+ if (!conversation) {
1125
+ conversation = { key, peer: { id: peer.id, name: peer.name ?? "?", role: peer.role ?? "" }, tasks: [] };
1126
+ byKey.set(key, conversation);
1127
+ }
1128
+ return conversation;
1129
+ };
1130
+ // Discovered parties come first, so they set the name and role the list shows. One the user
1131
+ // took off the list is left out even while it is still online: it comes back when it has
1132
+ // been away and is seen again, which is when the service stops listing it as hidden.
1133
+ for (const agent of agents) {
1134
+ if (!agent?.id || hiddenKeys.has(conversationKey(agent.id))) continue;
1135
+ conversationFor(agent);
1136
+ }
1137
+ const add = (task, mine) => {
1138
+ // The other party of a task is whoever is not this machine.
1139
+ if (hiddenKeys.has(conversationKey(mine ? task.to.id : task.from.id))) return;
1140
+ const conversation = conversationFor(mine ? task.to : task.from);
1141
+ conversation.tasks.push(taskEntry(task, mine));
1142
+ };
1143
+ for (const task of outbox) if (task.kind === "task") add(task, true);
1144
+ for (const task of inbox) if (task.kind === "task") add(task, false);
1145
+ for (const conversation of byKey.values()) {
1146
+ // Oldest first, newest last, the way a chat is read: the newest task sits at the bottom.
1147
+ conversation.tasks.sort((a, b) => orderKey(a).localeCompare(orderKey(b)));
1148
+ const newest = conversation.tasks.at(-1);
1149
+ conversation.lastTs = newest?.lastTs ?? "";
1150
+ // The list row is the newest task's title; "任务:" in front tells it from a message.
1151
+ conversation.lastText = newest ? `${t("lastMessage")}:${newest.task.payload.title ?? ""}` : "";
1152
+ // A conversation with nothing in it yet: there is someone to talk to, but no task so far.
1153
+ conversation.fresh = conversation.tasks.length === 0;
1154
+ conversation.unread = conversation.tasks.reduce((sum, entry) => sum + entry.unseen + (!entry.task.readAt && !entry.mine ? 1 : 0), 0);
1155
+ conversation.openQuestions = conversation.tasks.reduce((sum, entry) => sum + entry.openQuestions, 0);
1156
+ conversation.sent = conversation.tasks.filter((entry) => entry.mine).length;
1157
+ conversation.received = conversation.tasks.length - conversation.sent;
1158
+ }
1159
+ return [...byKey.values()].sort((a, b) => String(b.lastTs).localeCompare(String(a.lastTs)));
1160
+ }
1161
+
1162
+ /** The timeline of one task of a conversation, built when its drawer is opened. */
1163
+ const timelineOf = (entry) => (entry?.task ? taskTimeline(entry.task, entry.mine) : []);
1164
+
1165
+ /** Whether the conversation still has a task that is not finished. */
1166
+ const conversationIsLive = (conversation) => conversation.tasks.some((entry) => taskIsOpen(entry.task));
1167
+
1168
+ /**
1169
+ * Conversations as the list shows them. `direction` keeps the conversations that have a
1170
+ * task in that direction; the conversation itself is always shown whole, because cutting
1171
+ * the other side's tasks out of a dialogue would make it unreadable.
1172
+ */
1173
+ function visibleConversations(conversations, { filter = "open", query = "", direction = "all" } = {}) {
1174
+ const needle = query.trim().toLowerCase();
1175
+ return conversations.filter((conversation) => {
1176
+ if (filter === "open" && !conversationIsLive(conversation)) return false;
1177
+ if (direction === "sent" && !conversation.sent) return false;
1178
+ if (direction === "mine" && !conversation.received) return false;
1179
+ if (needle && !`${conversation.peer.name} ${conversation.peer.role}`.toLowerCase().includes(needle)) return false;
1180
+ return true;
1181
+ });
1182
+ }
1183
+
1184
+ // ---- projects: pure logic ---------------------------------------------------------------------
1185
+ // What a directory goes by among teammates' machines (the service keeps the names, one
1186
+ // record per directory). Everything here works on plain data, like the rest of this block.
1187
+
1188
+ /** The name a task's project goes by: what the executor last confirmed, else what the task was sent with; "" when it has none. */
1189
+ const projectNameOf = (item) => String((item?.projectName ?? item?.payload?.projectName) ?? "").trim();
1190
+
1191
+ /** What two names must share to be the same project: case and stray whitespace do not count. */
1192
+ const projectNameKey = (name) => String(name ?? "").trim().replace(/\s+/g, " ").toLowerCase();
1193
+
1194
+ /**
1195
+ * The one project of this machine that goes by a name, or null when none or two of them do:
1196
+ * which of two is the owner's to pick. `projects` are as net_chat_list_projects lists them.
1197
+ */
1198
+ function projectByName(projects, name) {
1199
+ const wanted = projectNameKey(name);
1200
+ if (!wanted) return null;
1201
+ const found = (projects ?? []).filter((entry) => projectNameKey(entry?.name) === wanted);
1202
+ return found.length === 1 ? found[0] : null;
1203
+ }
1204
+
1205
+ /**
1206
+ * The local project the "start" dialog opens on for a task ("" = on none, to be chosen),
1207
+ * as net_chat_list_projects lists them. A task that names its project opens on the one of
1208
+ * this machine that goes by that name, and on none when none or two of them do: which of
1209
+ * the directories here is that project is the owner's to say, not whichever was used
1210
+ * last. A task that names no project opens on `previous`, what was used before.
1211
+ */
1212
+ const projectToOpenOn = (item, projects, previous) => {
1213
+ const named = projectByName(projects, projectNameOf(item));
1214
+ return named ? named.projectId : projectNameOf(item) ? "" : previous;
1215
+ };
1216
+ // __CHAT_LOGIC_END__
1217
+
1218
+ // ---- agents: removing one -----------------------------------------------------------------
1219
+ /**
1220
+ * Takes the party of a conversation off the list. The service remembers it (and its old
1221
+ * records stay), so the row is gone until the party is next seen coming online; a
1222
+ * conversation that was open moves back to the list rather than showing someone removed.
1223
+ */
1224
+ async function forgetAgent(conversation) {
1225
+ state.menuOpen = null;
1226
+ state.forgetConfirm = null;
1227
+ const wasOpen = state.conversation === conversation.key;
1228
+ if (wasOpen) {
1229
+ state.conversation = null;
1230
+ state.drawer = null;
1231
+ }
1232
+ renderView();
1233
+ try {
1234
+ await call("net_chat_forget_agent", { agentId: conversation.peer.id });
1235
+ toast(t("removedToast", { name: conversation.peer.name }));
1236
+ } catch (error) {
1237
+ toast(explain(error), true);
1238
+ }
1239
+ await refresh({ silent: true });
1240
+ if (wasOpen) {
1241
+ const first = defaultConversation();
1242
+ if (first) await openConversation(first);
1243
+ }
1244
+ }
1245
+
1246
+
1247
+ // ---- chat ----------------------------------------------------------------------------------
1248
+ // One conversation per other party, and a conversation is its tasks: each task is one
1249
+ // bubble, on the left when the other party sent it and on the right when this machine did.
1250
+ // What is said about a task is not here; it is in the task's drawer, with the place to reply.
1251
+ const RECEIPT_LABEL = { accepted: "theirAccepted", started: "theirRunning", declined: "theirDeclined", failed: "theirFailed", done: "theirDone" };
1252
+ const speaker = (role) => (role === "user" ? (lang === "zh" ? "用户" : "user") : lang === "zh" ? "助手" : "assistant");
1253
+
1254
+ function renderChat() {
1255
+ const conversation = currentConversation();
1256
+ // The drawer is positioned against the view, so it overlays whichever column is showing.
1257
+ const open = conversation?.tasks.find((entry) => entry.task.id === state.drawer);
1258
+ // The "start" dialog is a fixed overlay above the drawer.
1259
+ const starting = [...state.inbox, ...state.outbox].find((item) => item.id === state.executeDialog);
1260
+ return h("div", { class: `chat${conversation ? " in-conv" : ""}`, dataset: { focusKey: "chat" } },
1261
+ conversationList(),
1262
+ conversation ? conversationView(conversation) : null,
1263
+ // Last, so that the two columns before it keep their place (children are matched in order).
1264
+ open ? taskDrawer(open, conversation) : null,
1265
+ starting ? executeDialog(starting) : null,
1266
+ );
1267
+ }
1268
+
1269
+ // ---- conversation list -----------------------------------------------------------------------
1270
+ // One row per party: everyone discovered on the LAN, and anyone there are records with.
1271
+ // Conversations that have something in them come first; the rest follow, still reachable
1272
+ // so that a first task can be sent.
1273
+
1274
+ function conversationList() {
1275
+ const all = conversations();
1276
+ const shown = visibleConversations(all, listOptions());
1277
+ const empty = !all.length;
1278
+ return h("div", { class: "chat-list" },
1279
+ h("div", { class: "toolbar" },
1280
+ h("button", { class: "icon-btn back-btn", title: t("backToList"), onclick: () => void closeConversation() }, icon("back")),
1281
+ h("label", { class: "search" }, icon("search"),
1282
+ h("input", {
1283
+ value: state.convQuery, placeholder: t("searchConversation"), dataset: { focusKey: "conv-search" },
1284
+ oninput: (event) => { state.convQuery = event.target.value; renderView(); },
1285
+ }))),
1286
+ h("div", { class: "chat-items" },
1287
+ shown.length
1288
+ ? shown.map((conversation) => conversationRow(conversation))
1289
+ : h("div", { class: "empty" },
1290
+ h("div", {}, h("strong", {}, t(empty ? "noOneTitle" : "noMatchConversation"))),
1291
+ empty ? h("div", { style: "max-width:260px;margin:6px auto 0" }, t("noOneBody")) : null)));
1292
+ }
1293
+
1294
+ function conversationRow(conversation) {
1295
+ const agent = state.agents.find((entry) => entry.id === conversation.peer.id);
1296
+ const online = agent?.online ?? false;
1297
+ const selected = conversation.key === state.conversation;
1298
+ return h("div", {
1299
+ key: conversation.key,
1300
+ class: `row click conv-row${selected ? " selected" : ""}${conversation.unread ? " unread" : ""}`,
1301
+ dataset: { conv: conversation.key },
1302
+ onclick: () => void openConversation(conversation.key),
1303
+ },
1304
+ avatar(conversation.peer.name),
1305
+ h("div", { class: "main" },
1306
+ h("div", { class: "title" },
1307
+ h("span", { class: "name" }, conversation.peer.name),
1308
+ conversation.peer.role ? h("span", { class: "tag role" }, conversation.peer.role) : null),
1309
+ h("div", { class: "meta" }, conversation.lastText || (conversation.fresh ? t("noTaskYetShort") : t("taskOf")))),
1310
+ h("div", { class: "conv-side" },
1311
+ conversation.lastTs ? h("div", { class: "meta" }, ago(conversation.lastTs)) : null,
1312
+ conversation.openQuestions ? h("span", { class: "tag accent" }, `${t("awaitingAnswer")} ${conversation.openQuestions}`) : null,
1313
+ conversation.unread ? h("span", { class: "pill hot" }, String(conversation.unread)) : h("span", { class: `dot ${online ? "on" : ""}` })));
1314
+ }
1315
+
1316
+ /** Back from a conversation to the list; on a wide panel the list was never hidden. */
1317
+ function closeConversation() {
1318
+ state.conversation = null;
1319
+ state.drawer = null;
1320
+ state.menuOpen = null;
1321
+ renderView();
1322
+ }
1323
+
1324
+ // ---- conversation view -----------------------------------------------------------------------
1325
+
1326
+ function conversationView(conversation) {
1327
+ const agent = state.agents.find((entry) => entry.id === conversation.peer.id) ?? null;
1328
+ const online = agent?.online ?? false;
1329
+ const trust = !agent
1330
+ ? ["", t("notDiscovered")]
1331
+ : agent.trust === "team" ? ["ok", t("verified")] : agent.trust === "foreign" ? ["warn", t("unverified")] : ["", t("noKey")];
1332
+ const menuOpen = state.menuOpen === conversation.key;
1333
+ return h("div", { class: "conv" },
1334
+ h("div", { class: "conv-head" },
1335
+ avatar(conversation.peer.name, true),
1336
+ h("div", { class: "title" },
1337
+ h("div", { class: "name-row" },
1338
+ h("span", { class: "name" }, conversation.peer.name),
1339
+ conversation.peer.role ? h("span", { class: "tag role" }, conversation.peer.role) : null),
1340
+ h("div", { class: "meta" },
1341
+ h("span", { class: `dot inline ${online ? "on" : ""}` }), ` ${agent ? (online ? t("online") : t("offline")) : t("notDiscovered")}`,
1342
+ agent?.host ? ` · ${agent.host}` : "",
1343
+ agent ? h("span", { class: `tag ${trust[0]}`.trim() }, trust[1]) : null)),
1344
+ h("div", { class: "conv-menu-wrap" },
1345
+ h("button", {
1346
+ class: `icon-btn${menuOpen ? " active" : ""}`, title: t("convMenu"), "aria-expanded": String(menuOpen), "aria-haspopup": "true",
1347
+ dataset: { focusKey: "conv-menu" }, onclick: (event) => { event.stopPropagation(); state.menuOpen = menuOpen ? null : conversation.key; state.forgetConfirm = null; renderView(); },
1348
+ }, icon("more")),
1349
+ menuOpen ? conversationMenu(conversation, agent) : null)),
1350
+ h("div", { class: "conv-body", dataset: { focusKey: "conv-body" }, onscroll: keepScrollStick },
1351
+ conversation.tasks.length
1352
+ ? withDayBreaks(conversation.tasks.map((entry) => taskRow(entry)))
1353
+ : h("div", { class: "empty conv-empty" },
1354
+ h("div", {}, t("emptyConversation")),
1355
+ h("div", { class: "small muted" }, t("emptyConversationHint")))),
1356
+ conversationInput(conversation));
1357
+ }
1358
+
1359
+ /**
1360
+ * What can be done to a conversation as a whole. So far one thing: take the party off the
1361
+ * list, which hides it — and its old records — until it is next seen coming online. It works
1362
+ * for a party known only from old records as well as for one on the LAN; one that is online
1363
+ * right now stays off until it has actually been away and comes back.
1364
+ */
1365
+ function conversationMenu(conversation, agent) {
1366
+ const online = agent?.online === true;
1367
+ return h("div", { class: "menu", role: "menu", dataset: { focusKey: "conv-menu-items" } },
1368
+ state.forgetConfirm === conversation.peer.id
1369
+ ? h("button", {
1370
+ class: "menu-item danger", role: "menuitem", dataset: { focusKey: "conv-menu-confirm" },
1371
+ onclick: () => void forgetAgent(conversation),
1372
+ }, t("confirmForgetShort"))
1373
+ : h("button", {
1374
+ class: "menu-item danger", role: "menuitem",
1375
+ // Records stay; a party on the LAN right now returns after it has been away once.
1376
+ title: agent ? (online ? t("forgetOnlineHint") : t("confirmForget")) : t("confirmForget"),
1377
+ onclick: () => { state.forgetConfirm = conversation.peer.id; renderView(); },
1378
+ }, icon("trash"), t("removeAgent")));
1379
+ }
1380
+
1381
+ /** Closes the conversation menu when something outside it is clicked or Escape is pressed. */
1382
+ function watchConversationMenu() {
1383
+ const app = document.getElementById("app");
1384
+ app.addEventListener("click", (event) => {
1385
+ if (state.menuOpen && !event.target.closest(".conv-menu-wrap")) {
1386
+ state.menuOpen = null;
1387
+ state.forgetConfirm = null;
1388
+ renderView();
1389
+ }
1390
+ });
1391
+ app.addEventListener("keydown", (event) => {
1392
+ if (event.key === "Escape" && state.menuOpen) {
1393
+ state.menuOpen = null;
1394
+ state.forgetConfirm = null;
1395
+ renderView();
1396
+ }
1397
+ });
1398
+ }
1399
+
1400
+ /** Whether the task list is scrolled to its end: when it is, a new task is brought into view. */
1401
+ let stickToEnd = true;
1402
+ function keepScrollStick(event) {
1403
+ const el = event.target;
1404
+ stickToEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
1405
+ }
1406
+
1407
+ /** After sending a task, shows it: the list goes to its end and stays there. */
1408
+ function scrollConversationToEnd() {
1409
+ stickToEnd = true;
1410
+ const body = document.querySelector('[data-focus-key="conv-body"]');
1411
+ if (body) body.scrollTop = body.scrollHeight;
1412
+ }
1413
+
1414
+ // Elements are kept across renders (see patch), so a scroll position, an open select and the
1415
+ // focus survive on their own. What a render still has to do is follow new content: a list
1416
+ // that was at its end goes on being at its end, and the drawer takes the focus when it opens.
1417
+ function afterRenderScroll() {
1418
+ const body = document.querySelector('[data-focus-key="conv-body"]');
1419
+ if (body && stickToEnd) body.scrollTop = body.scrollHeight;
1420
+ afterDrawerRender();
1421
+ // The "start" dialog takes the focus when it appears, so the project can be picked at once.
1422
+ if (state.executeDialog && !document.querySelector(".dialog .select:focus, .dialog .btn:focus")) {
1423
+ const pick = document.querySelector('.dialog [data-focus-key="execute.project"]');
1424
+ if (pick) pick.focus();
1425
+ }
1426
+ }
1427
+
1428
+ /** Whether the thread of the open drawer is scrolled to its newest message. */
1429
+ let threadStickToEnd = true;
1430
+ function keepThreadStick(event) {
1431
+ const el = event.target;
1432
+ threadStickToEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40;
1433
+ }
1434
+
1435
+ function afterDrawerRender() {
1436
+ const backdrop = document.querySelector(".drawer-backdrop");
1437
+ if (!backdrop) {
1438
+ state.drawerJustOpened = false;
1439
+ return;
1440
+ }
1441
+ if (state.drawerJustOpened) {
1442
+ // Escape closes the drawer from wherever the focus is, so it starts on the backdrop.
1443
+ state.drawerJustOpened = false;
1444
+ backdrop.focus();
1445
+ threadStickToEnd = true;
1446
+ }
1447
+ const thread = backdrop.querySelector('[data-focus-key="thread-body"]');
1448
+ if (thread && threadStickToEnd) thread.scrollTop = thread.scrollHeight;
1449
+ }
1450
+
1451
+ /** A day marker before the first task of each day, so a long list stays readable. */
1452
+ function withDayBreaks(rows) {
1453
+ const parts = [];
1454
+ let day = "";
1455
+ const dayOf = (iso) => {
1456
+ const date = new Date(iso);
1457
+ return Number.isNaN(date.getTime()) ? "" : date.toDateString();
1458
+ };
1459
+ for (const row of rows) {
1460
+ const ts = row.props?.dataset?.ts ?? "";
1461
+ const key = dayOf(ts);
1462
+ if (key && key !== day) {
1463
+ day = key;
1464
+ parts.push(h("div", { key: `day-${key}`, class: "day" }, new Date(ts).toLocaleDateString(undefined, { month: "long", day: "numeric" })));
1465
+ }
1466
+ parts.push(row);
1467
+ }
1468
+ return parts;
1469
+ }
1470
+
1471
+ /**
1472
+ * One task as a row. Which side it is on follows who sent it: what this machine sent is on
1473
+ * the right, what the other party did is on the left.
1474
+ */
1475
+ function taskRow(entry) {
1476
+ const mine = entry.mine;
1477
+ const who = mine ? (state.status?.identity?.name ?? "?") : (entry.task.from?.name ?? "?");
1478
+ return h("div", { key: entry.id, class: `msg ${mine ? "mine" : "theirs"}`, dataset: { ts: entry.ts, task: entry.id } },
1479
+ h("div", { class: "msg-col" },
1480
+ // The avatar sits on the line above the bubble, to the left of the name.
1481
+ h("div", { class: "msg-meta" }, avatar(who, true), h("span", { class: "who" }, mine ? t("self") : (entry.task.from?.name ?? "")), " · ", clock(entry.ts)),
1482
+ taskBubble(entry)));
1483
+ }
1484
+
1485
+ /**
1486
+ * The task as a bubble: title, state, a line or two of what it asks, and what is new in it.
1487
+ * Clicking it opens the drawer, where its messages are and where to reply.
1488
+ */
1489
+ function taskBubble(entry) {
1490
+ const task = entry.task;
1491
+ const mine = entry.mine;
1492
+ const status = mine ? outboxStatus(task) : task.status;
1493
+ const tag = statusTag(mine ? OUTBOX_TAG : INBOX_TAG, status);
1494
+ const marks = [];
1495
+ if (entry.openQuestions) marks.push(h("span", { class: "tag accent" }, `${t("awaitingAnswer")} ${entry.openQuestions}`));
1496
+ if (entry.unseen) marks.push(h("span", { class: "pill hot" }, String(entry.unseen)));
1497
+ // A task the other side sent that has not been started offers "start" right on the
1498
+ // bubble: that is what is usually wanted of it, and it opens the same project dialog
1499
+ // the drawer does. Anything else offers to open the task. The button stops the click, so
1500
+ // the bubble's own action (opening the drawer) does not also run.
1501
+ const canStart = !mine && (task.status === "new" || task.status === "accepted");
1502
+ const execute = state.status?.capabilities?.execute;
1503
+ const startButton = canStart
1504
+ ? h("button", {
1505
+ class: "btn primary sm", disabled: executionOf(task.id).busy || !execute, title: execute ? "" : t("extensionHint"),
1506
+ onclick: (event) => { event.stopPropagation(); openExecuteDialog(task); },
1507
+ // The bubble opens the drawer on Enter; from the button that key is the button's own.
1508
+ onkeydown: (event) => { if (event.key === "Enter" || event.key === " ") event.stopPropagation(); },
1509
+ }, icon("play"), t("execute"))
1510
+ : null;
1511
+ // The project the task belongs to leads the title, so tasks of one project line up.
1512
+ const projectName = projectNameOf(task);
1513
+ return h("div", { class: `bubble task${entry.unseen || entry.openQuestions ? " has-news" : ""}`, role: "button", tabindex: "0", title: t("openDrawer"),
1514
+ onclick: () => void openDrawer(task.id),
1515
+ onkeydown: (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); void openDrawer(task.id); } } },
1516
+ h("div", { class: "task-title" }, icon("file"),
1517
+ projectName ? h("span", { class: "tag project", title: `${t("projectName")}:${projectName}` }, projectName) : null,
1518
+ h("span", { class: "name" }, task.payload.title ?? ""), tag),
1519
+ task.payload.body ? h("div", { class: "task-teaser" }, task.payload.body) : null,
1520
+ h("div", { class: "task-foot" },
1521
+ canStart ? startButton : h("span", { class: "task-open" }, t("openDrawer")),
1522
+ marks.length ? h("span", { class: "task-marks" }, marks) : null));
1523
+ }
1524
+
1525
+ // ---- input -----------------------------------------------------------------------------------
1526
+ // The bottom of a conversation is one box, for a task. What is said about a task is typed in
1527
+ // the task's drawer. The task's title is made from its first line; nothing else is asked for.
1528
+
1529
+ /**
1530
+ * The box's text as the task the service is sent. The whole text is the request; the title
1531
+ * is its first line, cut to the length a session title may have. The title is what lists and
1532
+ * session tabs show, so it only has to be recognisable.
1533
+ */
1534
+ function taskFromText(text) {
1535
+ const body = text.trim();
1536
+ const firstLine = body.split(/\r?\n/)[0].trim();
1537
+ const title = firstLine.length > MAX_TASK_TITLE ? `${firstLine.slice(0, MAX_TASK_TITLE - 1)}…` : firstLine;
1538
+ return { title, body };
1539
+ }
1540
+ const MAX_TASK_TITLE = 80;
1541
+
1542
+ /** The text typed for a task in one conversation, kept while the panel is open so switching does not lose it. */
1543
+ function taskDraft(conversation) {
1544
+ let draft = state.taskDrafts.get(conversation.key);
1545
+ if (!draft) {
1546
+ draft = { text: "", busy: false };
1547
+ state.taskDrafts.set(conversation.key, draft);
1548
+ }
1549
+ return draft;
1550
+ }
1551
+
1552
+ function conversationInput(conversation) {
1553
+ const draft = taskDraft(conversation);
1554
+ const box = h("textarea", {
1555
+ class: "textarea", placeholder: t("taskTextPh"), value: draft.text, dataset: { focusKey: "task.text" },
1556
+ style: boxHeightStyle("task"), disabled: draft.busy,
1557
+ // Typing only stores the text; a re-render here would pull the caret out of the box.
1558
+ oninput: (event) => { draft.text = event.target.value; },
1559
+ onkeydown: (event) => {
1560
+ // Enter sends, Shift+Enter makes a new line, as in the chat apps people are used to.
1561
+ if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
1562
+ event.preventDefault();
1563
+ if (draft.text.trim() && !draft.busy) void sendTaskFromConversation(conversation);
1564
+ }
1565
+ },
1566
+ });
1567
+ return h("div", { class: "conv-input" },
1568
+ conversation.fresh ? h("div", { class: "notice" }, t("firstTaskHint")) : null,
1569
+ boxResizer(box, "task"),
1570
+ box);
1571
+ }
1572
+
1573
+ // ---- box height ----------------------------------------------------------------------------------
1574
+ // Each sending box is as tall as the user last dragged it. The height is kept in state, so it
1575
+ // survives re-renders, switching conversations and opening another task's drawer.
1576
+
1577
+ // The box starts at the stylesheet's height and can be dragged taller, not shorter: the least it
1578
+ // can be is what it was before it was touched.
1579
+ const BOX_MIN = { task: 66, thread: 78 };
1580
+ const BOX_MAX = 480;
1581
+
1582
+ /** The inline style that gives a box its remembered height; without one the stylesheet's default applies. */
1583
+ function boxHeightStyle(kind) {
1584
+ const height = state.inputHeights.get(kind);
1585
+ return height ? `height: ${height}px` : null;
1586
+ }
1587
+
1588
+ /**
1589
+ * The bar above a box that sets how tall the box is, by dragging or with the arrow keys.
1590
+ * The bar is the box's top edge, so dragging up makes the box taller and down makes it
1591
+ * shorter. The box is resized straight away while dragging; the value is remembered when
1592
+ * the drag ends.
1593
+ */
1594
+ function boxResizer(box, kind) {
1595
+ const min = BOX_MIN[kind];
1596
+ const max = () => Math.max(min, Math.min(BOX_MAX, Math.floor(window.innerHeight * 0.6)));
1597
+ const bar = h("div", {
1598
+ class: "box-resizer", role: "separator", "aria-orientation": "horizontal", tabindex: "0", title: t("resizeBox"),
1599
+ "aria-label": t("resizeBox"),
1600
+ onpointerdown: (event) => {
1601
+ if (event.button !== 0) return;
1602
+ event.preventDefault();
1603
+ const startY = event.clientY;
1604
+ const startHeight = box.getBoundingClientRect().height;
1605
+ bar.classList.add("dragging");
1606
+ bar.closest(".chat")?.classList.add("resizing");
1607
+ bar.setPointerCapture?.(event.pointerId);
1608
+ const move = (moved) => { box.style.height = `${Math.round(Math.min(max(), Math.max(min, startHeight - (moved.clientY - startY))))}px`; };
1609
+ const up = () => {
1610
+ bar.removeEventListener("pointermove", move);
1611
+ bar.removeEventListener("pointerup", up);
1612
+ bar.removeEventListener("pointercancel", up);
1613
+ bar.classList.remove("dragging");
1614
+ bar.closest(".chat")?.classList.remove("resizing");
1615
+ state.inputHeights.set(kind, Math.round(box.getBoundingClientRect().height));
1616
+ };
1617
+ bar.addEventListener("pointermove", move);
1618
+ bar.addEventListener("pointerup", up);
1619
+ bar.addEventListener("pointercancel", up);
1620
+ },
1621
+ onkeydown: (event) => {
1622
+ const step = event.shiftKey ? 40 : 10;
1623
+ const delta = event.key === "ArrowUp" ? step : event.key === "ArrowDown" ? -step : 0;
1624
+ if (!delta) return;
1625
+ event.preventDefault();
1626
+ const height = Math.round(Math.min(max(), Math.max(min, box.getBoundingClientRect().height + delta)));
1627
+ box.style.height = `${height}px`;
1628
+ state.inputHeights.set(kind, height);
1629
+ },
1630
+ // A double-click puts the box back to its default height.
1631
+ ondblclick: () => {
1632
+ state.inputHeights.delete(kind);
1633
+ box.style.height = "";
1634
+ },
1635
+ });
1636
+ return bar;
1637
+ }
1638
+
1639
+ /** Sends the task typed for this conversation to its other party. The text is kept if sending fails. */
1640
+ async function sendTaskFromConversation(conversation) {
1641
+ const draft = taskDraft(conversation);
1642
+ if (!draft.text.trim()) return toast(t("needText"), true);
1643
+ draft.busy = true;
1644
+ renderView();
1645
+ try {
1646
+ const result = await call("net_chat_send_task", { agent: conversation.peer.id, ...taskFromText(draft.text) });
1647
+ const delivered = result.delivered === true;
1648
+ toast(t(delivered ? "sentOk" : "sentFail", { name: conversation.peer.name }), !delivered);
1649
+ state.taskDrafts.delete(conversation.key);
1650
+ await refresh({ silent: true });
1651
+ scrollConversationToEnd();
1652
+ } catch (error) {
1653
+ toast(explain(error), true);
1654
+ draft.busy = false;
1655
+ renderView();
1656
+ }
1657
+ // A disabled box loses the focus, so it is put back: the next task should not need a click.
1658
+ focusTaskBox();
1659
+ }
1660
+
1661
+ /** Puts the focus in the task box of the conversation shown, when there is one. */
1662
+ function focusTaskBox() {
1663
+ document.querySelector(".conv-input:not(.drawer-input) textarea")?.focus();
1664
+ }
1665
+
1666
+ // ---- messages: said about one task, typed in its drawer ------------------------------------------------
1667
+
1668
+ /** A textarea whose text lives in state, so re-renders (a message arriving) never lose what is being typed. */
1669
+ function messageBox(task) {
1670
+ const key = `thread:${task.id}`;
1671
+ return h("textarea", {
1672
+ class: "textarea", style: boxHeightStyle("thread"), placeholder: t("threadPh"), value: state.drafts.get(key) ?? "", dataset: { focusKey: `thread.${task.id}` },
1673
+ disabled: state.sendingThread === `thread.${task.id}`,
1674
+ oninput: (event) => state.drafts.set(key, event.target.value),
1675
+ onkeydown: (event) => {
1676
+ // Enter sends, Shift+Enter makes a new line, as in the chat apps people are used to.
1677
+ if (event.key === "Enter" && !event.shiftKey && !event.isComposing) {
1678
+ event.preventDefault();
1679
+ void sendThreadMessage(task);
1680
+ }
1681
+ },
1682
+ });
1683
+ }
1684
+
1685
+ async function sendThreadMessage(task) {
1686
+ const key = `thread:${task.id}`;
1687
+ const text = (state.drafts.get(key) ?? "").trim();
1688
+ if (!text) return toast(t("needText"), true);
1689
+ const focusKey = `thread.${task.id}`;
1690
+ state.sendingThread = focusKey;
1691
+ renderView();
1692
+ try {
1693
+ await writeIntoThread(task, { text });
1694
+ state.drafts.delete(key);
1695
+ } catch (error) {
1696
+ toast(explain(error), true);
1697
+ }
1698
+ state.sendingThread = null;
1699
+ await refresh({ silent: true });
1700
+ scrollThreadToEnd(task.id);
1701
+ // The box was disabled while sending, which takes the focus off it; it goes back there.
1702
+ document.querySelector(".drawer .conv-input textarea")?.focus();
1703
+ }
1704
+
1705
+ /** Answers the other party's question with one of its choices. */
1706
+ async function answerQuestion(task, option, questionId) {
1707
+ const ex = executionOf(task.id);
1708
+ ex.busy = true;
1709
+ renderView();
1710
+ try {
1711
+ await writeIntoThread(task, { text: option, answerOf: questionId });
1712
+ } catch (error) {
1713
+ toast(explain(error), true);
1714
+ }
1715
+ ex.busy = false;
1716
+ await refresh({ silent: true });
1717
+ scrollThreadToEnd(task.id);
1718
+ }
1719
+
1720
+ /** Puts a message into a task's thread from this machine, whichever side of it this machine is. */
1721
+ function writeIntoThread(task, payload) {
1722
+ return isReceived(task)
1723
+ ? call("net_chat_respond", { itemId: task.id, action: "reply", ...payload })
1724
+ : call("net_chat_write_thread", { taskId: task.id, ...payload });
1725
+ }
1726
+
1727
+ /** Brings the newest message of the task's thread into view in its drawer. */
1728
+ function scrollThreadToEnd(taskId) {
1729
+ // Having written something, the newest message is what the user wants in view, so the
1730
+ // thread counts as "at its end" again from here on.
1731
+ threadStickToEnd = true;
1732
+ const thread = document.querySelector(`.drawer [data-focus-key="thread-body"]`);
1733
+ if (thread) thread.scrollTop = thread.scrollHeight;
1734
+ }
1735
+
1736
+ // A task this machine received sits in the inbox; the read mark is what tells them apart
1737
+ // when both lists happen to hold the same id.
1738
+ const isReceived = (task) => state.inbox.some((item) => item.id === task.id);
1739
+
1740
+ // ---- drawer: one task in full ----------------------------------------------------------------
1741
+
1742
+ // ---- drawer: one task in full, with everything said about it --------------------------------
1743
+ // The drawer holds the task (what it asks, and what to do with it) and, below that, its
1744
+ // thread: the messages the two sides exchanged about it and the receipts, oldest first,
1745
+ // with the box to reply in at the bottom.
1746
+
1747
+ function openDrawer(taskId) {
1748
+ state.drawer = taskId;
1749
+ const task = [...state.inbox, ...state.outbox].find((item) => item.id === taskId) ?? null;
1750
+ if (!state.detail.has(taskId)) {
1751
+ // The whole text and the transcript are fetched only when they are looked at.
1752
+ void loadDetail(taskId, task && isReceived(task) ? "inbox" : "outbox");
1753
+ }
1754
+ // Opening the task is what looks at it: the task itself and everything said in its thread
1755
+ // so far. The service keeps that, so it is still true after the panel is reopened. The
1756
+ // loaded copy is updated first so the count is gone in the render that follows.
1757
+ if (task) {
1758
+ task.readAt = task.readAt ?? new Date().toISOString();
1759
+ task.seenThread = threadOf(task).filter((entry) => entry.from !== "me").length;
1760
+ }
1761
+ state.drawerJustOpened = true;
1762
+ renderView();
1763
+ void call("net_chat_mark_read", { ids: [taskId] })
1764
+ .then(() => refresh({ silent: true }), () => {});
1765
+ }
1766
+
1767
+ /**
1768
+ * Shows one task wherever it is: the conversation that holds it, with its drawer open.
1769
+ * For the host's `netchat/openTask` notification, which may arrive before the list has
1770
+ * the task (the panel has just loaded), so the list is brought up to date first. A
1771
+ * task nobody has in the end is left alone.
1772
+ */
1773
+ async function showTask(taskId) {
1774
+ if (!conversations().some((conversation) => conversation.tasks.some((entry) => entry.task.id === taskId))) {
1775
+ await refresh({ silent: true }).catch(() => {});
1776
+ }
1777
+ const conversation = conversations().find((entry) => entry.tasks.some((item) => item.task.id === taskId));
1778
+ if (!conversation) return;
1779
+ await openConversation(conversation.key);
1780
+ openDrawer(taskId);
1781
+ }
1782
+
1783
+ function taskDrawer(entry, conversation) {
1784
+ const task = entry.task;
1785
+ const inbox = !entry.mine;
1786
+ const item = withDetail(task);
1787
+ // The backdrop dims the chat behind the drawer. A click on the backdrop itself closes the
1788
+ // drawer; a click inside it has the drawer as its target and is left alone. It also takes
1789
+ // Escape, and exists only while the drawer does, so nothing has to be registered globally.
1790
+ const backdrop = h("div", {
1791
+ class: "drawer-backdrop",
1792
+ tabindex: "-1",
1793
+ onclick: (event) => { if (event.target === backdrop) closeDrawer(); },
1794
+ onkeydown: (event) => { if (event.key === "Escape") { event.preventDefault(); closeDrawer(); } },
1795
+ },
1796
+ h("div", { class: "drawer", role: "dialog", "aria-label": t("taskDetails") },
1797
+ h("div", { class: "toolbar" },
1798
+ h("div", { class: "title" }, icon("file"), h("span", { class: "name" }, task.payload.title ?? "")),
1799
+ h("span", { class: "spacer" }),
1800
+ h("button", { class: "icon-btn", title: t("close"), onclick: () => closeDrawer() }, icon("x"))),
1801
+ h("div", { class: "drawer-task" }, taskDetails(item, inbox, conversation)),
1802
+ h("div", { class: "drawer-thread" },
1803
+ h("div", { class: "thread-head" }, t("threadTitle")),
1804
+ h("div", { class: "thread-body", dataset: { focusKey: "thread-body" }, onscroll: keepThreadStick },
1805
+ threadTimeline(entry)),
1806
+ threadComposer(entry))));
1807
+ return backdrop;
1808
+ }
1809
+
1810
+ /**
1811
+ * The panel's document does not run animation frames (it is a sandboxed frame, and
1812
+ * `requestAnimationFrame` never fires in it), so anything that must happen after the drawer
1813
+ * is in the page is done right after the render that puts it there. See afterDrawerRender.
1814
+ */
1815
+
1816
+ function closeDrawer() {
1817
+ state.drawer = null;
1818
+ renderView();
1819
+ }
1820
+
1821
+ /** The task itself: what can be done with it, and — folded away until asked for — what it asks. */
1822
+ function taskDetails(item, inbox, conversation) {
1823
+ const payload = item.payload ?? {};
1824
+ const parts = [];
1825
+ // What can be done comes first, above the text: a long request must not push the
1826
+ // buttons off the bottom of a part that is capped at 40% of the drawer.
1827
+ if (inbox) {
1828
+ parts.push(inboxActions(item));
1829
+ } else if (item.status === "failed" || item.originSessionId) {
1830
+ parts.push(sentActions(item));
1831
+ }
1832
+ // The thread below is what the drawer is opened for; the request and its outcome are
1833
+ // folded up until the owner asks to see them, so the thread gets the room. Remembered
1834
+ // per task. The toggle is offered whenever there is anything to fold.
1835
+ const open = state.openDetails.has(`task:${item.id}`);
1836
+ const projectName = projectNameOf(item);
1837
+ const background = [payload.body, payload.workspaceHint ? `${t("projectHint")}:${payload.workspaceHint}` : null, projectName ? `${t("projectName")}:${projectName}` : null].filter(Boolean);
1838
+ // Where and with what the task runs, once it has been started: the project (its title),
1839
+ // the model the session was given, when one was chosen, and for a task put into an
1840
+ // existing session, that session's own title.
1841
+ const runWith = [item.reusedSession ? `${t("ranInSession")}:${item.sessionTitle}` : item.project?.title, item.model].filter(Boolean).join(" · ");
1842
+ const foldable = background.length > 0 || Boolean(runWith) || payload.session || item.error || item.result;
1843
+ parts.push(h("div", { class: "task-head" },
1844
+ h("div", { class: "meta" },
1845
+ `${inbox ? `${t("self")} ← ${roleText(item.from)}` : `${t("self")} → ${roleText(item.to)}`} · ${clock(item.ts)}`),
1846
+ foldable
1847
+ ? h("button", {
1848
+ class: "btn sm task-toggle", "aria-expanded": String(open), dataset: { focusKey: `task-toggle.${item.id}` },
1849
+ onclick: () => { toggleTaskDetail(item.id); },
1850
+ }, icon(open ? "up" : "down"), t(open ? "taskFold" : "taskUnfold"))
1851
+ : null));
1852
+ if (open) {
1853
+ if (payload.body) parts.push(h("div", { class: "pre" }, payload.body));
1854
+ if (projectName) parts.push(h("div", { class: "meta" }, `${t("projectName")}:${projectName}`));
1855
+ if (payload.workspaceHint) parts.push(h("div", { class: "meta" }, `${t("projectHint")}:${payload.workspaceHint}`));
1856
+ if (runWith) parts.push(h("div", { class: "meta" }, `${t("ranWith")}:${runWith}`));
1857
+ if (payload.session) parts.push(transcriptBlock(item, inbox ? "inbox" : "outbox"));
1858
+ if (item.error) parts.push(h("div", { class: "notice danger" }, item.error));
1859
+ if (item.result) parts.push(h("div", { class: "pre" }, `${t(item.status === "failed" ? "resultFailed" : "resultDone")}:${item.result}`));
1860
+ }
1861
+ return h("div", { class: `stack task-detail${open ? " open" : ""}` }, parts);
1862
+ }
1863
+
1864
+ function toggleTaskDetail(itemId) {
1865
+ const key = `task:${itemId}`;
1866
+ if (state.openDetails.has(key)) state.openDetails.delete(key);
1867
+ else state.openDetails.add(key);
1868
+ state.drawerJustOpened = false;
1869
+ renderView();
1870
+ }
1871
+
1872
+ /**
1873
+ * Everything that happened around the task, oldest first: the receipts the other side sent
1874
+ * and the messages the two of you exchanged. Each is on the left or the right by who it
1875
+ * came from, as tasks are.
1876
+ */
1877
+ function threadTimeline(entry) {
1878
+ const items = timelineOf(entry);
1879
+ // The task itself is already written out above; the thread starts from what followed it.
1880
+ const rows = items.filter((item) => item.type !== "task").map((item) => (item.type === "receipt" ? receiptRow(entry, item) : messageRow(entry, item)));
1881
+ return rows.length ? withDayBreaks(rows) : h("div", { class: "empty small" }, t("threadEmpty"));
1882
+ }
1883
+
1884
+ /** A receipt is the other side's progress; it is a line, centred, not a bubble. */
1885
+ function receiptRow(entry, item) {
1886
+ return h("div", { key: `receipt-${item.ts}`, class: "thread-event", dataset: { ts: item.ts } },
1887
+ h("time", null, clock(item.ts)),
1888
+ h("span", {}, `${RECEIPT_LABEL[item.status] ? t(RECEIPT_LABEL[item.status]) : item.status}${item.detail ? `:${item.detail}` : ""}`));
1889
+ }
1890
+
1891
+ function messageRow(entry, item) {
1892
+ const mine = item.mine;
1893
+ const other = entry.mine ? entry.task.to : entry.task.from;
1894
+ return h("div", { key: item.id, class: `msg ${mine ? "mine" : "theirs"}`, dataset: { ts: item.ts, msg: item.id } },
1895
+ h("div", { class: "msg-col" },
1896
+ // The avatar sits on the line above the bubble, to the left of the name.
1897
+ h("div", { class: "msg-meta" }, avatar(mine ? (state.status?.identity?.name ?? "?") : (other?.name ?? "?"), true), h("span", { class: "who" }, mine ? t("self") : roleText(other)), " · ", clock(item.ts)),
1898
+ h("div", { class: "bubble" }, item.text),
1899
+ ...messageChoices(entry, item),
1900
+ item.failed ? h("div", { class: "notice danger" }, item.error ?? t("stSendFailed")) : null));
1901
+ }
1902
+
1903
+ /** What follows a message that offered choices: how it was answered, or the choices to pick from. */
1904
+ function messageChoices(entry, item) {
1905
+ if (!item.options.length) return [];
1906
+ if (item.answer) {
1907
+ return [
1908
+ h("div", { class: "chips" }, item.options.map((option) => h("span", { class: `chip${option === item.answer.text ? " chosen" : ""}` }, option))),
1909
+ h("div", { class: "small muted" }, `${t("answered")}:${item.answer.text}`),
1910
+ ];
1911
+ }
1912
+ if (item.mine) {
1913
+ return [
1914
+ h("div", { class: "chips" }, item.options.map((option) => h("span", { class: "chip" }, option))),
1915
+ h("div", { class: "small muted" }, `${t("awaitingAnswer")}…`),
1916
+ ];
1917
+ }
1918
+ return [
1919
+ h("div", { class: "small muted" }, t("pleaseChoose")),
1920
+ h("div", { class: "chips" }, item.options.map((option) => h("button", {
1921
+ class: "chip", disabled: executionOf(entry.task.id).busy,
1922
+ onclick: () => void answerQuestion(entry.task, option, item.id),
1923
+ }, option))),
1924
+ ];
1925
+ }
1926
+
1927
+ /** The box at the bottom of the thread: a message about this task. It needs no "reply to": the task is the one the drawer is open on. */
1928
+ function threadComposer(entry) {
1929
+ const box = messageBox(entry.task);
1930
+ return h("div", { class: "conv-input drawer-input" }, boxResizer(box, "thread"), box);
1931
+ }
1932
+
1933
+ function transcriptBlock(item, box) {
1934
+ const summary = item.payload.session;
1935
+ const entry = state.detail.get(item.id);
1936
+ return h("details", {
1937
+ open: state.openDetails.has(item.id),
1938
+ ontoggle: (event) => {
1939
+ if (!event.target.open) {
1940
+ state.openDetails.delete(item.id);
1941
+ } else {
1942
+ state.openDetails.add(item.id);
1943
+ if (entry && !entry.loading && entry.messages.length < entry.total) void loadDetail(item.id, box, entry.messages.length);
1944
+ }
1945
+ },
1946
+ },
1947
+ h("summary", {},
1948
+ `${t("attachedSession")} · ${summary.messageCount} ${lang === "zh" ? "条" : ""}${summary.truncated ? t("truncated") : ""}${summary.title ? ` · ${summary.title}` : ""}`),
1949
+ entry
1950
+ ? h("div", {},
1951
+ entry.error ? h("div", { class: "notice danger" }, entry.error) : null,
1952
+ entry.messages.length ? h("div", { class: "transcript" }, entry.messages.map((m) => `[${speaker(m.role)}]\n${m.text}`).join("\n\n---\n\n")) : null,
1953
+ entry.messages.length < entry.total
1954
+ ? h("button", { class: "btn sm", disabled: entry.loading, onclick: () => void loadDetail(item.id, box, entry.messages.length) }, t("loadMore"))
1955
+ : null)
1956
+ : null);
1957
+ }
1958
+
1959
+ /** Lists carry teasers; the whole item, plus a window of its transcript, is fetched when the drawer opens. */
1960
+ async function loadDetail(id, box, offset = 0) {
1961
+ const entry = state.detail.get(id) ?? { item: null, messages: [], total: 0, loading: false, error: null };
1962
+ state.detail.set(id, entry);
1963
+ entry.loading = true;
1964
+ renderView();
1965
+ try {
1966
+ const item = (await call("net_chat_get_item", { id, box, offset, limit: 50 })).item;
1967
+ const session = item.payload.session;
1968
+ entry.item = offset ? entry.item : item;
1969
+ entry.messages = offset && session ? entry.messages.concat(session.messages) : session?.messages ?? [];
1970
+ entry.total = session?.total ?? 0;
1971
+ entry.error = null;
1972
+ } catch (error) {
1973
+ entry.error = error.message;
1974
+ }
1975
+ entry.loading = false;
1976
+ renderView();
1977
+ }
1978
+
1979
+ /**
1980
+ * The list item is always the fresh one; the detail fetched when the drawer was opened only
1981
+ * contributes what lists leave out (the whole text, the transcript). Status, receipts and
1982
+ * session must come from the list, or a started task would still offer "start".
1983
+ */
1984
+ function withDetail(item) {
1985
+ const detail = state.detail.get(item.id)?.item;
1986
+ if (!detail) return item;
1987
+ // Spreading a missing session would yield `{}`, which reads as "has a transcript".
1988
+ const session = detail.payload?.session ?? item.payload?.session;
1989
+ return {
1990
+ ...detail,
1991
+ ...item,
1992
+ payload: { ...detail.payload, ...(session ? { session: { ...detail.payload.session, ...item.payload.session } } : {}) },
1993
+ };
1994
+ }
1995
+
1996
+ function inboxActions(item) {
1997
+ const capabilities = state.status?.capabilities ?? {};
1998
+ const ex = executionOf(item.id);
1999
+ const open = item.status === "new" || item.status === "accepted";
2000
+ const parts = [];
2001
+ if (open) {
2002
+ // The project is chosen in the dialog this opens, the same one the chat's bubble opens.
2003
+ parts.push(h("button", {
2004
+ class: "btn primary", disabled: ex.busy || !capabilities.execute, title: capabilities.execute ? "" : t("extensionHint"),
2005
+ onclick: () => openExecuteDialog(item),
2006
+ }, icon("play"), ex.busy ? t("executing") : t("execute")));
2007
+ if (!state.decline.has(item.id)) {
2008
+ parts.push(h("button", { class: "btn danger", disabled: ex.busy, onclick: () => { state.decline.add(item.id); renderView(); } }, t("decline")));
2009
+ }
2010
+ }
2011
+ if (item.sessionId) parts.push(h("button", { class: "btn", onclick: () => void openSession(item.sessionId) }, icon("external"), t("openSession")));
2012
+ const blocks = [h("div", { class: "actions" }, parts)];
2013
+ if (state.decline.has(item.id)) {
2014
+ blocks.push(h("div", { class: "stack" },
2015
+ noteBox(item.id, "decline", t("declinePh")),
2016
+ h("div", { class: "actions" },
2017
+ h("button", { class: "btn danger", disabled: ex.busy, onclick: () => void declineItem(item) }, t("confirmDecline")),
2018
+ h("button", { class: "btn", onclick: () => { state.decline.delete(item.id); renderView(); } }, t("cancel")))));
2019
+ }
2020
+ if (item.status === "running") {
2021
+ // Nothing to press here: when the work is finished the session reports it itself
2022
+ // (net_chat_respond with done or failed), and the result shows under the task.
2023
+ blocks.push(h("div", { class: "small muted" }, t("runningHint")));
2024
+ }
2025
+ return blocks;
2026
+ }
2027
+
2028
+ /** What can be done with a task sent from here: send it again while it failed, and open the session it was sent from. */
2029
+ function sentActions(item) {
2030
+ const parts = [];
2031
+ if (item.status === "failed") parts.push(h("button", { class: "btn", onclick: () => void resendItem(item) }, t("resend")));
2032
+ if (item.originSessionId) parts.push(h("button", { class: "btn", onclick: () => void openSession(item.originSessionId) }, icon("external"), t("openSession")));
2033
+ return h("div", { class: "actions" }, parts);
2034
+ }
2035
+
2036
+ /** A textarea whose text lives in state, so re-renders (new mail arriving) never lose what is being typed. */
2037
+ function noteBox(itemId, kind, placeholder) {
2038
+ const key = `${kind}:${itemId}`;
2039
+ return h("textarea", {
2040
+ class: "textarea", style: "min-height:56px", placeholder, value: state.drafts.get(key) ?? "", dataset: { focusKey: `${kind}.${itemId}` },
2041
+ oninput: (event) => state.drafts.set(key, event.target.value),
2042
+ });
2043
+ }
2044
+
2045
+ function executionOf(itemId) {
2046
+ let ex = state.exec.get(itemId);
2047
+ if (!ex) {
2048
+ ex = {};
2049
+ state.exec.set(itemId, ex);
2050
+ }
2051
+ return ex;
2052
+ }
2053
+
2054
+ // ---- starting a task --------------------------------------------------------------------------------
2055
+
2056
+ // The project chosen last time, so the dialog opens on it: "start" is usually the same
2057
+ // choice again. The string "none" is the "not in a project" option.
2058
+ let lastProjectChoice = null;
2059
+ // The sessions of one project as the host lists them, fetched when the dialog first asks
2060
+ // for that project and kept for the panel's life ("" = every project). Each entry is
2061
+ // `{ sessions, failed }`.
2062
+ const sessionsOfProject = new Map();
2063
+ const MAX_SESSION_OPTIONS = 50;
2064
+
2065
+ /**
2066
+ * The sessions the host offers for a project, loaded once per project. A failure is kept
2067
+ * as such: the dialog then offers a new session only and says why, rather than retrying
2068
+ * on every render.
2069
+ */
2070
+ async function loadSessions(projectChoice) {
2071
+ const key = projectChoice === "none" ? "none" : projectChoice || "";
2072
+ if (sessionsOfProject.has(key)) return sessionsOfProject.get(key);
2073
+ const entry = { sessions: [], failed: false, loading: true };
2074
+ sessionsOfProject.set(key, entry);
2075
+ try {
2076
+ const project = (state.projects ?? []).find((candidate) => candidate.projectId === key) ?? null;
2077
+ const result = await call("net_chat_list_sessions", project ? { projectId: project.projectId } : {});
2078
+ entry.sessions = Array.isArray(result.sessions) ? result.sessions : [];
2079
+ } catch (error) {
2080
+ entry.failed = true;
2081
+ }
2082
+ entry.loading = false;
2083
+ return entry;
2084
+ }
2085
+
2086
+ /**
2087
+ * The project the execute dialog opens on for a task (see projectToOpenOn): "" when the
2088
+ * task names a project that none of this machine's goes by, so that one has to be chosen.
2089
+ * What was chosen before is `previous` if the dialog was already open for this task, else
2090
+ * last time's choice, else the first one listed.
2091
+ */
2092
+ function defaultProjectChoice(item, projects, previous) {
2093
+ return projectToOpenOn(item, projects, previous ?? lastProjectChoice ?? projects[0]?.projectId ?? "");
2094
+ }
2095
+
2096
+ /**
2097
+ * What the name field of the execute dialog holds: what the owner typed, else the name the
2098
+ * task came with, else the name the project shown already goes by. A task that names its
2099
+ * project keeps that name in the field whichever project is shown: it is what the executor
2100
+ * is asked to confirm (see projectNameChanges for when that would rename the project).
2101
+ */
2102
+ function projectNameField(item, ex, projects) {
2103
+ if (ex.projectNameTyped) return ex.projectName;
2104
+ const choice = ex.projectChoice ?? lastProjectChoice ?? "";
2105
+ const shown = (projects ?? []).find((entry) => entry.projectId === choice) ?? null;
2106
+ return projectNameOf(item) || shown?.name || "";
2107
+ }
2108
+
2109
+ /**
2110
+ * Asks which local project to run the task in, and whether in a new session or one that
2111
+ * already exists, then starts it. One dialog for both places a task is started from (the
2112
+ * drawer and the bubble in the chat), so the choice is made the same way wherever the
2113
+ * button is. The dialog offers "not in a project" as well.
2114
+ */
2115
+ function openExecuteDialog(item) {
2116
+ const ex = executionOf(item.id);
2117
+ ex.loadingProjects = true;
2118
+ // A session is never preselected: putting a task into an old one is a choice, not a default.
2119
+ ex.sessionChoice = "";
2120
+ // The name field starts over: what was typed last time was for the project shown then.
2121
+ ex.projectName = "";
2122
+ ex.projectNameTyped = false;
2123
+ // The project the dialog opens on (see defaultProjectChoice). Fixed here rather than
2124
+ // left to the select's own first option, so the session list is loaded for the project
2125
+ // actually shown.
2126
+ if (state.projects) ex.projectChoice = defaultProjectChoice(item, state.projects, ex.projectChoice);
2127
+ state.executeDialog = item.id;
2128
+ renderView();
2129
+ void (async () => {
2130
+ if (state.status?.capabilities?.listProjects && state.projects === null) {
2131
+ try {
2132
+ state.projects = (await call("net_chat_list_projects")).projects ?? [];
2133
+ } catch (error) {
2134
+ toast(explain(error), true);
2135
+ state.projects = [];
2136
+ }
2137
+ ex.projectChoice = defaultProjectChoice(item, state.projects, null);
2138
+ }
2139
+ ex.loadingProjects = false;
2140
+ // The sessions of the project the dialog opens on, so the second choice is there at once
2141
+ // (none to load while no project is chosen).
2142
+ if (state.status?.capabilities?.listSessions && ex.projectChoice) void loadSessions(ex.projectChoice).then(() => { if (state.executeDialog === item.id) renderView(); });
2143
+ // Only if the dialog is still the one asking about this task (it may have been closed).
2144
+ if (state.executeDialog === item.id) renderView();
2145
+ })();
2146
+ }
2147
+
2148
+ function executeDialog(item) {
2149
+ const ex = executionOf(item.id);
2150
+ const projects = state.status?.capabilities?.listProjects ? (state.projects ?? []) : [];
2151
+ const choice = ex.projectChoice ?? lastProjectChoice ?? "";
2152
+ const loading = Boolean(ex.loadingProjects);
2153
+ const canListSessions = state.status?.capabilities?.listSessions === true && state.status?.capabilities?.sendToSession === true;
2154
+ // A task that names a project none of this machine's goes by opens on no project at all:
2155
+ // which directory is that project is to be chosen, and nothing starts before it is.
2156
+ const choosing = !choice && projects.length > 0;
2157
+ // A project that already goes by a name says so, so the owner can tell the directories apart.
2158
+ const options = projects.map((entry) => h("option", { value: entry.projectId, selected: entry.projectId === choice }, entry.name ? `${entry.title} · ${entry.name}` : entry.title));
2159
+ if (projects.length) options.unshift(h("option", { value: "", disabled: true, selected: choosing }, t("chooseProject")));
2160
+ // "Not in a project" is always offered, and is the only option when none can be listed.
2161
+ const noProjectChosen = choice === "none" || (!choice && !projects.length);
2162
+ options.push(h("option", { value: "none", selected: noProjectChosen }, t("runNoProject")));
2163
+ // Whether a task can be put in an existing session: only for a real project, and only
2164
+ // when the host can both list its sessions and take input for one.
2165
+ const reusable = canListSessions && !noProjectChosen && Boolean(choice);
2166
+ const listed = reusable ? (sessionsOfProject.get(choice) ?? null) : null;
2167
+ const sessions = listed?.sessions ?? [];
2168
+ const sessionChoice = reusable ? (ex.sessionChoice ?? "") : "";
2169
+ const projectPick = h("select", {
2170
+ class: "select", dataset: { focusKey: "execute.project" }, disabled: loading || Boolean(sessionChoice),
2171
+ onchange: (event) => {
2172
+ ex.projectChoice = event.target.value;
2173
+ // Another project means other sessions: the one chosen no longer applies.
2174
+ ex.sessionChoice = "";
2175
+ if (state.status?.capabilities?.listSessions) void loadSessions(ex.projectChoice).then(() => { if (state.executeDialog === item.id) renderView(); });
2176
+ renderView();
2177
+ },
2178
+ }, options);
2179
+ // The second choice: a new session, or one of the project's existing sessions.
2180
+ const sessionOptions = [h("option", { value: "", selected: sessionChoice === "" }, t("newSession"))];
2181
+ if (reusable && !listed?.loading) {
2182
+ for (const session of sessions.slice(0, MAX_SESSION_OPTIONS)) {
2183
+ sessionOptions.push(h("option", { value: session.sessionId, selected: session.sessionId === sessionChoice }, `${session.title || session.sessionId}(${session.running ? t("sessionRunning") : t("sessionIdle")})`));
2184
+ }
2185
+ }
2186
+ const sessionPick = h("select", {
2187
+ class: "select", dataset: { focusKey: "execute.session" }, disabled: loading || !reusable || listed?.loading === true,
2188
+ onchange: (event) => { ex.sessionChoice = event.target.value; renderView(); },
2189
+ }, sessionOptions);
2190
+ const sessionNote = !reusable
2191
+ ? null
2192
+ : listed?.failed
2193
+ ? h("div", { class: "small muted", style: "margin-top:6px" }, t("sessionListFailed"))
2194
+ : listed?.loading
2195
+ ? h("div", { class: "small muted", style: "margin-top:6px" }, t("loading"))
2196
+ : h("div", { class: "small muted", style: "margin-top:6px" }, sessionChoice ? t("reuseSessionHint") : t("newSessionHint"));
2197
+ // The project's name as the field holds it (see projectNameField), and a word when
2198
+ // confirming it would change the name the project shown goes by.
2199
+ const fieldName = projectNameField(item, ex, projects);
2200
+ const shown = projects.find((entry) => entry.projectId === choice) ?? null;
2201
+ const typed = fieldName.trim();
2202
+ const renameNote = !noProjectChosen && shown?.name && typed && projectNameKey(typed) !== projectNameKey(shown.name)
2203
+ ? h("div", { class: "small muted", style: "margin-top:6px" }, t("projectNameChanges", { project: shown.title, old: shown.name, new: typed }))
2204
+ : null;
2205
+ const nameField = h("div", { class: "field" },
2206
+ h("label", { for: "execute-project-name" }, t("projectName")),
2207
+ h("input", {
2208
+ class: "input", id: "execute-project-name", list: "execute-project-names", maxlength: "60", autocomplete: "off",
2209
+ value: fieldName, disabled: loading || noProjectChosen, dataset: { focusKey: "execute.projectName" },
2210
+ oninput: (event) => { ex.projectName = event.target.value; ex.projectNameTyped = true; },
2211
+ }),
2212
+ // The names this machine's other projects go by, to pick one rather than retype it.
2213
+ h("datalist", { id: "execute-project-names" }, [...new Set(projects.map((entry) => entry.name).filter(Boolean))].map((name) => h("option", { value: name }))),
2214
+ h("div", { class: "small muted", style: "margin-top:6px" }, t("projectNameHint")),
2215
+ renameNote);
2216
+ const overlay = h("div", {
2217
+ class: "dialog", onclick: (event) => { if (event.target === overlay) closeExecuteDialog(); },
2218
+ onkeydown: (event) => { if (event.key === "Escape") { event.preventDefault(); closeExecuteDialog(); } },
2219
+ },
2220
+ h("div", { class: "dialog-box", role: "dialog", "aria-label": t("executeTitle") },
2221
+ h("h2", {}, t("executeTitle")),
2222
+ h("div", { class: "task-name" }, item.payload.title ?? ""),
2223
+ h("div", { class: "field" }, h("label", {}, t("executeWhichProject")),
2224
+ loading ? h("div", { class: "small muted" }, t("loading")) : projectPick,
2225
+ noProjectChosen && !loading ? h("div", { class: "small muted", style: "margin-top:6px" }, t("runNoProjectHint")) : null),
2226
+ // The name the project goes by from now on: what the task came with, else what this
2227
+ // project already goes by, else whatever the owner types.
2228
+ nameField,
2229
+ // The session choice is shown only where it can be made; elsewhere a new session is
2230
+ // what happens, and the project line above already says everything.
2231
+ canListSessions ? h("div", { class: "field" }, h("label", {}, t("executeWhichSession")), sessionPick, sessionNote) : null,
2232
+ h("div", { class: "actions" },
2233
+ h("button", { class: "btn", onclick: closeExecuteDialog }, t("cancel")),
2234
+ h("button", {
2235
+ class: "btn primary", disabled: loading || listed?.loading === true || choosing,
2236
+ // The chosen values live in the selects' onchange handlers, and are read from
2237
+ // the DOM as a fallback (the descriptions are not the elements).
2238
+ onclick: () => {
2239
+ const selected = ex.projectChoice ?? document.querySelector('.dialog select[data-focus-key="execute.project"]')?.value ?? "";
2240
+ const session = reusable ? (ex.sessionChoice ?? document.querySelector('.dialog select[data-focus-key="execute.session"]')?.value ?? "") : "";
2241
+ // The name as the field holds it is confirmed with the start, for a real project only.
2242
+ const projectName = selected !== "none" ? projectNameField(item, ex, projects) : undefined;
2243
+ lastProjectChoice = selected;
2244
+ closeExecuteDialog();
2245
+ void executeItem(item, selected, session, projectName);
2246
+ },
2247
+ }, icon("play"), t("execute")))));
2248
+ return overlay;
2249
+ }
2250
+
2251
+ function closeExecuteDialog() {
2252
+ const id = state.executeDialog;
2253
+ state.executeDialog = null;
2254
+ if (id) {
2255
+ const ex = state.exec.get(id);
2256
+ if (ex) ex.loadingProjects = false;
2257
+ }
2258
+ renderView();
2259
+ }
2260
+
2261
+ /**
2262
+ * Starts the task in the project chosen in the dialog ("none" = not in a project), in a
2263
+ * new session or, when `session` names one, in that existing session. `projectName` is the
2264
+ * name the dialog confirmed for the project (see projectNameField): the service keeps it
2265
+ * for the project's directory and tells the sender.
2266
+ */
2267
+ async function executeItem(item, projectChoice, session = "", projectName = undefined) {
2268
+ const ex = executionOf(item.id);
2269
+ ex.busy = true;
2270
+ renderView();
2271
+ try {
2272
+ const result = await call("net_chat_respond", {
2273
+ itemId: item.id,
2274
+ action: "execute",
2275
+ // Into an existing session: the project is sent too, so the service checks the
2276
+ // session among that project's. Otherwise the project choice says where to start.
2277
+ ...(session
2278
+ ? { sessionId: session, ...(projectChoice && projectChoice !== "none" ? { projectId: projectChoice } : {}) }
2279
+ : projectChoice === "none" ? { noProject: true } : projectChoice ? { projectId: projectChoice } : {}),
2280
+ ...(projectName === undefined ? {} : { projectName }),
2281
+ });
2282
+ const title = result.item?.payload?.title ?? "";
2283
+ toast(session && result.item?.sessionId ? t("reusedToast", { title, session: result.item.sessionTitle ?? session }) : t("startedToast", { title }));
2284
+ // The names are part of the project list: it is loaded afresh when it is next needed.
2285
+ state.projects = null;
2286
+ } catch (error) {
2287
+ toast(explain(error), true);
2288
+ }
2289
+ ex.busy = false;
2290
+ await refresh({ silent: true });
2291
+ }
2292
+
2293
+ async function declineItem(item) {
2294
+ const key = `decline:${item.id}`;
2295
+ try {
2296
+ await call("net_chat_respond", { itemId: item.id, action: "decline", text: (state.drafts.get(key) ?? "").trim() });
2297
+ state.drafts.delete(key);
2298
+ state.decline.delete(item.id);
2299
+ toast(t("stDeclined"));
2300
+ } catch (error) {
2301
+ toast(explain(error), true);
2302
+ }
2303
+ await refresh({ silent: true });
2304
+ }
2305
+
2306
+ async function openSession(sessionId) {
2307
+ try {
2308
+ await call("net_chat_open_session", { sessionId });
2309
+ } catch (error) {
2310
+ toast(explain(error), true);
2311
+ }
2312
+ }
2313
+
2314
+ async function resendItem(item) {
2315
+ try {
2316
+ const result = await call("net_chat_resend", { itemId: item.id });
2317
+ toast(t(result.item.status === "delivered" ? "sentOk" : "sentFail", { name: item.to.name }), result.item.status !== "delivered");
2318
+ } catch (error) {
2319
+ toast(explain(error), true);
2320
+ }
2321
+ await refresh({ silent: true });
2322
+ }
2323
+
2324
+ // ---- settings ------------------------------------------------------------------------------
2325
+ async function openSettings() {
2326
+ const status = state.status;
2327
+ if (!status) return;
2328
+ const who = status.identity ?? {};
2329
+ const settings = status.settings ?? {};
2330
+ state.form = {
2331
+ name: who.name ?? "", role: who.role ?? "", teamKey: "", autoExecute: settings.autoExecute ?? "off", autoAnswer: settings.autoAnswer ?? "off",
2332
+ defaultProject: settings.defaultProject ?? "", defaultModel: settings.defaultModel ?? "", announce: settings.announce !== false,
2333
+ };
2334
+ state.settingsOpen = true;
2335
+ renderSettings();
2336
+ if (state.projects === null && status.capabilities?.listProjects) {
2337
+ state.projects = [];
2338
+ try {
2339
+ state.projects = (await call("net_chat_list_projects")).projects ?? [];
2340
+ } catch (error) {
2341
+ toast(explain(error), true);
2342
+ }
2343
+ if (state.settingsOpen) renderSettings();
2344
+ }
2345
+ }
2346
+
2347
+ function closeSettings() {
2348
+ state.settingsOpen = false;
2349
+ document.getElementById("sheet")?.remove();
2350
+ }
2351
+
2352
+ // ---- Feishu (settings) --------------------------------------------------------------------
2353
+ // One section of the settings sheet: the bridge's state, who is waiting to be bound, and
2354
+ // who is bound. Everything it shows comes from status.feishu, which every refresh carries.
2355
+ function renderFeishuSection(f) {
2356
+ const feishu = state.status?.feishu ?? {};
2357
+ const settings = state.status?.settings ?? {};
2358
+ const state_ = t(`feishuState${(feishu.state ?? "off").replace(/^./, (c) => c.toUpperCase())}`);
2359
+ const tagClass = feishu.state === "listening" ? "tag ok" : ["connecting", "reconnecting"].includes(feishu.state) ? "tag warn" : "tag danger";
2360
+ const bindings = feishu.bindingsList ?? [];
2361
+ const form = state.feishuForm ?? (state.feishuForm = { secret: "", code: "" });
2362
+ const stateLine =
2363
+ feishu.state === "unconfigured" || !feishu.configured
2364
+ ? h("div", { class: "notice warn" }, t("feishuConfigure"))
2365
+ : feishu.lastError
2366
+ ? h("div", { class: "notice warn" }, feishu.lastError)
2367
+ : null;
2368
+ // The credentials: App ID always editable; the Secret is never shown back, only whether one is saved.
2369
+ const credentials = h("div", { style: "margin-top:10px" },
2370
+ h("div", { class: "field" }, h("label", {}, t("feishuAppId")),
2371
+ h("input", { class: "input mono", id: "feishu-app-id", maxlength: "32", autocomplete: "off", placeholder: "cli_…", value: feishu.appId ?? "", oninput: (event) => { form.appId = event.target.value; } })),
2372
+ h("div", { class: "field" }, h("label", { class: "inline" }, t("feishuAppSecret"), feishu.hasSecret ? h("span", { class: "tag ok", style: "margin-left:6px" }, t("feishuSecretSaved")) : null),
2373
+ h("input", { class: "input mono", id: "feishu-app-secret", type: "password", maxlength: "128", autocomplete: "new-password", placeholder: feishu.hasSecret ? t("feishuSecretPh") : "", value: form.secret, oninput: (event) => { form.secret = event.target.value; } })),
2374
+ h("div", { class: "small muted" }, t("feishuCredentialsHint")),
2375
+ h("div", { class: "actions" },
2376
+ h("button", { class: "btn sm", onclick: () => void feishuSaveCredentials() }, t("feishuSave")),
2377
+ feishu.state === "listening" ? h("button", { class: "btn sm", onclick: () => void feishuReconnect() }, t("feishuReconnect")) : null));
2378
+ // Binding is by pairing code: the owner writes to the bot in Feishu and pastes what it
2379
+ // answers here — the code, or the whole message, the service finds the code in it. No
2380
+ // length limit on the field: the message is about 150 characters, and a limit cut it
2381
+ // short before it reached the service. Offered only while nobody is bound: one machine,
2382
+ // one owner's account; to change it, unbind first.
2383
+ const bindBox = bindings.length ? null : h("div", { style: "margin-top:10px" },
2384
+ h("div", { class: "small muted" }, t("feishuBindHow")),
2385
+ h("div", { class: "inline", style: "flex-wrap:wrap;margin-top:4px" },
2386
+ h("input", { class: "input mono", id: "feishu-code", style: "flex:1;min-width:160px;text-transform:uppercase", autocomplete: "off", placeholder: t("feishuCodePh"), value: form.code ?? "", oninput: (event) => { form.code = event.target.value; }, onkeydown: (event) => { if (event.key === "Enter") { event.preventDefault(); void feishuBindByCode(); } } }),
2387
+ h("button", { class: "btn sm primary", onclick: () => void feishuBindByCode() }, t("feishuBind"))));
2388
+ const boundRows = bindings.map((entry) =>
2389
+ h("div", { class: "kv", style: "margin:6px 0;padding:6px 8px;border:1px solid var(--border);border-radius:8px" },
2390
+ h("dt", {}, entry.name),
2391
+ h("dd", { class: "inline", style: "justify-content:space-between;width:100%" },
2392
+ h("span", { class: "mono muted" }, entry.maskedOpenId),
2393
+ h("span", { class: "small muted" }, entry.lastMessageAt ? t("feishuLast", { time: ago(entry.lastMessageAt) }) : t("feishuNever")),
2394
+ h("button", { class: "btn sm danger", onclick: () => void feishuUnbind(entry.openId) }, t("feishuUnbind")))));
2395
+ // The form value, not the saved one: the owner may have switched auto-answer on in this
2396
+ // sheet and not saved yet, and the two must still not be on together when they do.
2397
+ const notifyOff = f.autoAnswer === "on";
2398
+ return h("section", {},
2399
+ h("h3", { class: "inline" }, t("feishu"), h("span", { class: tagClass }, state_)),
2400
+ h("div", { class: "small muted", style: "margin-top:4px" }, t("feishuHint")),
2401
+ stateLine,
2402
+ credentials,
2403
+ bindBox,
2404
+ h("div", { class: "check", style: "margin-top:10px" },
2405
+ h("input", { type: "checkbox", checked: settings.feishuNotify === true, disabled: notifyOff, onchange: (event) => void setFeishuNotify(event.target.checked) }),
2406
+ h("span", {}, t("feishuNotify"))),
2407
+ h("div", { class: "small muted", style: "margin-left:22px" }, notifyOff ? t("feishuNotifyBlocked") : t("feishuNotifyHint")),
2408
+ h("div", { class: "small muted", style: "margin-top:12px;font-weight:600" }, `${t("feishuBound")}(${bindings.length})`),
2409
+ h("div", { class: "small muted" }, t("feishuBoundHint")),
2410
+ bindings.length ? boundRows : h("div", { class: "small muted", style: "margin:4px 0 0 0" }, t("feishuNoBindings")));
2411
+ }
2412
+
2413
+ /** Saves the credentials typed in the sheet; only the fields that were touched go. */
2414
+ async function feishuSaveCredentials() {
2415
+ const appId = document.getElementById("feishu-app-id")?.value?.trim() ?? "";
2416
+ const secret = document.getElementById("feishu-app-secret")?.value ?? "";
2417
+ if (!appId) return toast(t("feishuAppId"), true);
2418
+ if (!secret && !state.status?.feishu?.hasSecret) return toast(t("feishuAppSecret"), true);
2419
+ await feishuAction("net_chat_feishu_configure", { appId, ...(secret ? { appSecret: secret } : {}) }, t("saved"));
2420
+ }
2421
+
2422
+ async function feishuReconnect() {
2423
+ await feishuAction("net_chat_feishu_configure", { appId: state.status?.feishu?.appId ?? "" }, t("feishuReconnect"));
2424
+ }
2425
+
2426
+ async function feishuAction(name, args, okText) {
2427
+ try {
2428
+ await call(name, args);
2429
+ toast(okText);
2430
+ } catch (error) {
2431
+ toast(explain(error), true);
2432
+ }
2433
+ await refresh({ silent: true });
2434
+ if (state.settingsOpen) renderSettings();
2435
+ }
2436
+
2437
+ /** Binds whoever the code the owner typed in was given to. */
2438
+ async function feishuBindByCode() {
2439
+ const code = (state.feishuForm?.code ?? document.getElementById("feishu-code")?.value ?? "").trim();
2440
+ if (!code) return toast(t("feishuCodePh"), true);
2441
+ // Cleared first: the sheet is rebuilt when the action is done, from the form.
2442
+ state.feishuForm.code = "";
2443
+ await feishuAction("net_chat_feishu_bind", { code }, t("feishuBind"));
2444
+ }
2445
+
2446
+ async function feishuUnbind(openId) {
2447
+ await feishuAction("net_chat_feishu_unbind", { openId }, t("feishuUnbind"));
2448
+ }
2449
+
2450
+ /** The Feishu reminder switch; refused by the service while auto-answer is on. */
2451
+ async function setFeishuNotify(on) {
2452
+ await feishuAction("net_chat_update_profile", { feishuNotify: on }, on ? t("feishuNotifyOn") : t("feishuNotifyOff"));
2453
+ }
2454
+
2455
+ function renderSettings() {
2456
+ document.getElementById("sheet")?.remove();
2457
+ const f = state.form;
2458
+ const status = state.status;
2459
+ const settings = status?.settings ?? {};
2460
+ const grants = status?.grants ?? {};
2461
+ const bind = (key) => ({ value: f[key], dataset: { focusKey: `settings.${key}` }, oninput: (event) => { f[key] = event.target.value; } });
2462
+ const grantState = (value) => (value === true ? h("span", { class: "tag ok" }, t("yes")) : value === false ? h("span", { class: "tag danger" }, t("no")) : h("span", { class: "tag" }, t("unknown")));
2463
+ const projects = state.projects ?? [];
2464
+ const overlay = h("div", { class: "sheet", id: "sheet", onclick: (event) => { if (event.target === overlay) closeSettings(); } },
2465
+ h("div", { class: "panel" },
2466
+ h("div", { class: "toolbar" }, h("h2", { class: "spacer" }, t("settings")),
2467
+ h("button", { class: "icon-btn", title: t("cancel"), onclick: closeSettings }, icon("x"))),
2468
+ h("section", {},
2469
+ h("div", { class: "field" }, h("label", {}, t("displayName")), h("input", { class: "input", maxlength: "60", ...bind("name") })),
2470
+ h("div", { class: "field" }, h("label", {}, t("roleLabel")), h("input", { class: "input", maxlength: "40", placeholder: t("rolePh"), ...bind("role") }))),
2471
+ h("section", {},
2472
+ h("h3", {}, t("teamKey")),
2473
+ h("input", { class: "input mono", type: "password", autocomplete: "off", placeholder: t("teamKeyPh"), ...bind("teamKey") }),
2474
+ h("div", { class: "small muted", style: "margin-top:6px" }, t("teamKeyHint")),
2475
+ settings.hasTeamKey
2476
+ ? h("div", { class: "small muted", style: "margin-top:6px" }, `${t("teamKey")}:${t("yes")} · ${settings.teamTag ?? ""}`)
2477
+ : null),
2478
+ renderFeishuSection(f),
2479
+ h("section", {},
2480
+ h("h3", {}, t("autoExecute")),
2481
+ h("select", { class: "select", onchange: (event) => { f.autoExecute = event.target.value; renderSettings(); } },
2482
+ h("option", { value: "off", selected: f.autoExecute === "off" }, t("autoOff")),
2483
+ h("option", { value: "trusted", selected: f.autoExecute === "trusted" }, t("autoTrusted"))),
2484
+ f.autoExecute === "trusted" ? h("div", { class: "notice warn" }, t("autoWarn")) : null,
2485
+ // Who answers a question the other side asks about work sent from here: the agent
2486
+ // picks, or the owner does (told on Feishu when that is on). One or the other.
2487
+ h("h3", { style: "margin-top:14px" }, t("autoAnswer")),
2488
+ h("select", { class: "select", disabled: settings.feishuNotify === true, onchange: (event) => { f.autoAnswer = event.target.value; renderSettings(); } },
2489
+ h("option", { value: "off", selected: f.autoAnswer !== "on" }, t("autoAnswerOff")),
2490
+ h("option", { value: "on", selected: f.autoAnswer === "on" }, t("autoAnswerOn"))),
2491
+ f.autoAnswer === "on" ? h("div", { class: "notice warn" }, t("autoAnswerWarn")) : null,
2492
+ h("div", { class: "small muted", style: "margin-left:0" }, settings.feishuNotify === true ? t("autoAnswerBlocked") : t("autoAnswerHint")),
2493
+ h("div", { class: "field", style: "margin-top:10px" }, h("label", {}, t("defaultProject")),
2494
+ h("select", { class: "select", disabled: !projects.length, onchange: (event) => { f.defaultProject = event.target.value; } },
2495
+ h("option", { value: "", selected: f.defaultProject === "" }, t("noDefault")),
2496
+ projects.map((entry) => h("option", { value: entry.projectId, selected: entry.projectId === f.defaultProject }, entry.title)))),
2497
+ h("div", { class: "small muted" }, t("defaultProjectHint")),
2498
+ // The model a session is started with. The list is what this host offers (status.models);
2499
+ // with none the choice is the host's own default and nothing else is offered. A setting
2500
+ // the host no longer has stays selected and is said to be so, until the owner changes it.
2501
+ h("div", { class: "field", style: "margin-top:10px" }, h("label", {}, t("defaultModel")),
2502
+ (() => {
2503
+ const models = status?.models ?? [];
2504
+ const chosen = f.defaultModel ?? "";
2505
+ // Always offered, and the only option when the host lists none.
2506
+ const options = [h("option", { value: "", selected: chosen === "" }, t("noDefaultModel"))];
2507
+ for (const model of models) options.push(h("option", { value: model.id, selected: model.id === chosen }, model.label));
2508
+ if (chosen && !models.some((model) => model.id === chosen)) {
2509
+ // Kept as an option so the select shows what is set rather than silently changing.
2510
+ options.push(h("option", { value: chosen, selected: true }, chosen));
2511
+ }
2512
+ return h("select", { class: "select", disabled: !models.length && !chosen, onchange: (event) => { f.defaultModel = event.target.value; renderSettings(); } }, options);
2513
+ })()),
2514
+ h("div", { class: "small muted" }, t("defaultModelHint")),
2515
+ // What the state of that choice is: no models from this host, or a stale setting.
2516
+ !(status?.models ?? []).length && !(f.defaultModel ?? "")
2517
+ ? h("div", { class: "notice" }, t("defaultModelNone"))
2518
+ : (f.defaultModel ?? "") && !(status?.models ?? []).some((model) => model.id === f.defaultModel)
2519
+ ? h("div", { class: "notice warn" }, t("defaultModelStale", { model: f.defaultModel }))
2520
+ : null,
2521
+ h("div", { class: "check", style: "margin-top:10px" },
2522
+ h("input", { type: "checkbox", checked: f.announce, onchange: (event) => { f.announce = event.target.checked; } }),
2523
+ h("span", {}, t("announce"))),
2524
+ h("div", { class: "small muted", style: "margin-left:22px" }, t("announceHint"))),
2525
+ h("section", {},
2526
+ h("h3", {}, t("permissions")),
2527
+ h("div", { class: "inline", style: "gap:14px;flex-wrap:wrap" },
2528
+ h("span", { class: "inline" }, t("permRead"), grantState(grants.read)),
2529
+ h("span", { class: "inline" }, t("permWrite"), grantState(grants.write)),
2530
+ h("span", { class: "inline" }, t("permNotify"), grantState(grants.notifications))),
2531
+ status?.capabilities?.requestGrants ? h("div", { class: "actions" }, h("button", { class: "btn", onclick: () => void requestGrants() }, t("grant"))) : null,
2532
+ status?.owner === "mcp" ? h("div", { class: "notice" }, t("extensionHint")) : null),
2533
+ h("section", {},
2534
+ h("h3", {}, t("diagnostics")),
2535
+ h("dl", { class: "kv" },
2536
+ h("dt", {}, t("service")), h("dd", {}, `${status?.owner === "extension" ? t("ownerExtension") : t("ownerMcp")} · ${t("port")} ${status?.port ?? "-"}`),
2537
+ h("dt", {}, t("addresses")), h("dd", { class: "mono" }, (status?.addresses ?? []).join(", ") || "-"),
2538
+ h("dt", {}, t("instanceId")), h("dd", { class: "mono" }, status?.identity?.id ?? "-"),
2539
+ h("dt", {}, t("version")), h("dd", {}, `${APP.version} / ${status?.version ?? "-"}`)),
2540
+ h("div", { class: "actions" }, h("button", { class: "btn sm", onclick: () => void copyDiagnostics() }, icon("copy"), t("copy")))),
2541
+ h("div", { class: "actions" },
2542
+ h("button", { class: "btn primary", onclick: () => void saveSettings() }, t("save")),
2543
+ settings.hasTeamKey ? h("button", { class: "btn danger", onclick: () => void clearTeamKey() }, t("clearKey")) : null)));
2544
+ // `h` returns a description; the DOM wants the node made from it.
2545
+ document.body.append(make(overlay));
2546
+ }
2547
+
2548
+ async function requestGrants() {
2549
+ try {
2550
+ const result = await call("net_chat_request_grants");
2551
+ toast(result.granted?.length ? `${t("grant")}:${result.granted.join(", ")}` : t("unknown"));
2552
+ } catch (error) {
2553
+ toast(explain(error), true);
2554
+ }
2555
+ await refresh({ silent: true });
2556
+ if (state.settingsOpen) renderSettings();
2557
+ }
2558
+
2559
+ async function saveSettings() {
2560
+ const f = state.form;
2561
+ const who = state.status?.identity ?? {};
2562
+ const settings = state.status?.settings ?? {};
2563
+ if (!f.name.trim()) return toast(t("displayName"), true);
2564
+ const patch = {};
2565
+ if (f.name.trim() !== who.name) patch.name = f.name.trim();
2566
+ if (f.role.trim() !== (who.role ?? "")) patch.role = f.role.trim();
2567
+ if (f.teamKey.trim()) patch.teamKey = f.teamKey.trim();
2568
+ if (f.autoExecute !== settings.autoExecute) patch.autoExecute = f.autoExecute;
2569
+ if (f.autoAnswer !== (settings.autoAnswer ?? "off")) patch.autoAnswer = f.autoAnswer;
2570
+ if (f.defaultProject !== (settings.defaultProject ?? "")) patch.defaultProject = f.defaultProject;
2571
+ if (f.defaultModel !== (settings.defaultModel ?? "")) patch.defaultModel = f.defaultModel;
2572
+ if (f.announce !== settings.announce) patch.announce = f.announce;
2573
+ try {
2574
+ if (Object.keys(patch).length) await call("net_chat_update_profile", patch);
2575
+ closeSettings();
2576
+ toast(t("saved"));
2577
+ } catch (error) {
2578
+ toast(explain(error), true);
2579
+ }
2580
+ await refresh({ silent: true });
2581
+ }
2582
+
2583
+ async function clearTeamKey() {
2584
+ try {
2585
+ await call("net_chat_update_profile", { teamKey: "" });
2586
+ closeSettings();
2587
+ toast(t("saved"));
2588
+ } catch (error) {
2589
+ toast(explain(error), true);
2590
+ }
2591
+ await refresh({ silent: true });
2592
+ }
2593
+
2594
+ async function copyDiagnostics() {
2595
+ const status = state.status ?? {};
2596
+ const text = JSON.stringify({
2597
+ version: APP.version, serviceVersion: status.version, owner: status.owner, port: status.port,
2598
+ addresses: status.addresses, identity: status.identity, online: status.online, known: status.known,
2599
+ capabilities: status.capabilities, grants: status.grants,
2600
+ }, null, 2);
2601
+ try {
2602
+ await navigator.clipboard.writeText(text);
2603
+ toast(t("copied"));
2604
+ } catch {
2605
+ toast(text, false);
2606
+ }
2607
+ }
2608
+
2609
+ // __END_VIEWS__
2610
+
2611
+ async function boot() {
2612
+ const bootEl = document.getElementById("boot");
2613
+ bootEl.textContent = t("booting");
2614
+ try {
2615
+ if (window.parent === window) throw Object.assign(new Error(t("noHostBody")), { code: "no_host" });
2616
+ const init = await bridge.request(
2617
+ "ui/initialize",
2618
+ { appInfo: { name: APP.name, version: APP.version }, appCapabilities: {}, protocolVersion: PROTOCOL },
2619
+ 8000,
2620
+ );
2621
+ lang = pickLang(init?.hostContext?.locale);
2622
+ hostName = pickHost(init?.hostContext?.host);
2623
+ bridge.notify("ui/notifications/initialized");
2624
+ buildShell();
2625
+ watchConversationMenu();
2626
+ await refresh();
2627
+ // Open the conversation with the newest activity, unless there is none to open.
2628
+ const first = defaultConversation();
2629
+ if (first) await openConversation(first);
2630
+ state.booted = true;
2631
+ void pollLoop();
2632
+ } catch (error) {
2633
+ fatal(error.code === "no_host" ? t("noHostTitle") : t("fatalTitle"), explain(error));
2634
+ }
2635
+ }
2636
+
2637
+ function fatal(title, message, retry = true) {
2638
+ const view = document.getElementById("view") ?? document.getElementById("app");
2639
+ render(view,
2640
+ h("div", { class: "center" },
2641
+ icon("alert"),
2642
+ h("h3", {}, title),
2643
+ h("p", {}, message),
2644
+ retry ? h("button", { class: "btn primary", onclick: () => void boot() }, t("retry")) : null),
2645
+ );
2646
+ }
2647
+
2648
+ boot();
2649
+ })();
2650
+ </script>
2651
+ </body>
2652
+ </html>