dsh-wsr-execution 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.js ADDED
@@ -0,0 +1,3211 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-wsr-execution",
3
+ factory: (platformRequire) => {
4
+ const fixedWorkspaceUi = ((require) => {
5
+ var module = { exports: {} };
6
+ var exports = module.exports;
7
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
8
+ let _deepseek_ai_dsh_client_runtime_client = require("@deepseek-ai/dsh-client-runtime/client");
9
+ let react_jsx_runtime = require("react/jsx-runtime");
10
+ let react = require("react");
11
+ let _deepseek_ai_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
12
+ //#region lib/types/client/stores.js
13
+ /**
14
+ * The workspace browser's viewing store: the session-list grouping mode,
15
+ * persisted across reloads. Module level exports the factory only (a
16
+ * module-level handle would pin the store identity across plugin reloads);
17
+ * register() receives the factory and the browser derives its PropsStore
18
+ * share from the return type.
19
+ */
20
+ /** Browser-local order account for the hierarchy-free flat Session list. */
21
+ const FLAT_SESSION_ORDER_KEY = "__flat_session_order__";
22
+ /**
23
+ * Create the workspace browser viewing store handle.
24
+ * @returns the store handle (spec + type + identity + factory in one).
25
+ */
26
+ function createWorkspaceViewStore() {
27
+ return (0, _deepseek_ai_dsh_client_runtime_client.defineStore)({
28
+ init: () => ({
29
+ groupBy: "workspace",
30
+ orderBy: "updated",
31
+ groupExpansion: {},
32
+ sessionOrderByAccount: {},
33
+ sessionUpdatedAtByAccount: {}
34
+ }),
35
+ persist: "dsh.workspace.view.v5",
36
+ actions: {
37
+ setGroupBy: (d, mode) => {
38
+ d.groupBy = mode;
39
+ },
40
+ setOrderBy: (d, mode) => {
41
+ d.orderBy = mode;
42
+ },
43
+ setGroupExpanded: (d, key, expanded) => {
44
+ d.groupExpansion[key] = expanded;
45
+ },
46
+ retainAccountKeys: (d, workspaceKeys) => {
47
+ const retained = new Set(workspaceKeys);
48
+ d.groupExpansion = Object.fromEntries(Object.entries(d.groupExpansion).filter(([key]) => retained.has(key)));
49
+ d.sessionOrderByAccount = Object.fromEntries(Object.entries(d.sessionOrderByAccount).filter(([key]) => retained.has(key)));
50
+ d.sessionUpdatedAtByAccount = Object.fromEntries(Object.entries(d.sessionUpdatedAtByAccount).filter(([key]) => retained.has(key)));
51
+ },
52
+ syncSessionOrderAccount: (d, accountKey, order, updatedAt) => {
53
+ d.sessionOrderByAccount[accountKey] = order;
54
+ d.sessionUpdatedAtByAccount[accountKey] = updatedAt;
55
+ },
56
+ setSessionOrder: (d, accountKey, order) => {
57
+ d.sessionOrderByAccount[accountKey] = order;
58
+ }
59
+ }
60
+ });
61
+ }
62
+ //#endregion
63
+ //#region ../../../node_modules/.pnpm/clsx@2.1.1/node_modules/clsx/dist/clsx.mjs
64
+ function r(e) {
65
+ var t, f, n = "";
66
+ if ("string" == typeof e || "number" == typeof e) n += e;
67
+ else if ("object" == typeof e) if (Array.isArray(e)) {
68
+ var o = e.length;
69
+ for (t = 0; t < o; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
70
+ } else for (f in e) e[f] && (n && (n += " "), n += f);
71
+ return n;
72
+ }
73
+ function clsx() {
74
+ for (var e, t, f = 0, n = "", o = arguments.length; f < o; f++) (e = arguments[f]) && (t = r(e)) && (n && (n += " "), n += t);
75
+ return n;
76
+ }
77
+ /** Display label for the ungrouped bucket row. */
78
+ const UNGROUPED_LABEL = "Ungrouped";
79
+ /**
80
+ * Directory display label: basename of the path (both separators accepted).
81
+ * Ungrouped-bucket fallback for surfaces without a workspace title.
82
+ * @param cwd - directory path, or undefined for the ungrouped bucket.
83
+ * @returns basename, the raw cwd when it has no basename, or the ungrouped label.
84
+ */
85
+ function workspaceLabel(cwd) {
86
+ if (cwd === void 0 || cwd === "") return UNGROUPED_LABEL;
87
+ const base = cwd.replace(/[/\\]+$/, "").split(/[/\\]/).pop();
88
+ return base !== void 0 && base !== "" ? base : cwd;
89
+ }
90
+ /** Recency comparator: newest first, id as the deterministic tiebreak (ids are unique per group). */
91
+ function byRecency(a, b) {
92
+ if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt;
93
+ return a.id < b.id ? -1 : 1;
94
+ }
95
+ /**
96
+ * Ordinary sessions are visible; among blank sessions, only the current one
97
+ * is visible. Subagent children use their parent header catalog; archived
98
+ * sessions are visible nowhere, while their accounting slots remain so
99
+ * unarchiving restores position.
100
+ */
101
+ function sessionVisible(session, current, archived) {
102
+ return session.origin !== "subagent" && !archived.has(session.id) && (!session.blank || session.id === current);
103
+ }
104
+ /**
105
+ * A blank session is the selected Workspace's provisional New Session row;
106
+ * its canonical title never enters search (blank rows are query-excluded)
107
+ * and the renderer localizes its display label.
108
+ */
109
+ function sessionTitle(session) {
110
+ return session.blank ? "New Session" : session.displayTitle;
111
+ }
112
+ /** Build one group without projecting session lineage into presentation. */
113
+ function buildGroup(key, workspaceId, cwd, createdAt, label, members, order) {
114
+ const sessions = [...members];
115
+ if (order === "recency") sessions.sort(byRecency);
116
+ return {
117
+ key,
118
+ workspaceId,
119
+ cwd,
120
+ createdAt,
121
+ label,
122
+ sessions
123
+ };
124
+ }
125
+ /** Apply a stored Ungrouped order and append newly loose Sessions by recency. */
126
+ function orderedUngrouped(members, stored) {
127
+ const byId = new Map(members.map((session) => [session.id, session]));
128
+ const included = /* @__PURE__ */ new Set();
129
+ const ordered = [];
130
+ for (const key of stored) {
131
+ const session = byId.get(key);
132
+ if (session === void 0 || included.has(key)) continue;
133
+ ordered.push(session);
134
+ included.add(key);
135
+ }
136
+ for (const session of [...members].sort(byRecency)) {
137
+ if (included.has(session.id)) continue;
138
+ ordered.push(session);
139
+ }
140
+ return ordered;
141
+ }
142
+ /**
143
+ * Group Sessions by Host Workspace: one group per entity in stable Host
144
+ * order, with members resolved from sessionIds in their stored order. Sessions
145
+ * outside every Workspace trail in the browser-local Ungrouped order, which
146
+ * falls back to recency before that order is initialized.
147
+ */
148
+ function groupByWorkspace(list, workspaces, archived, ungroupedOrder) {
149
+ const groups = [];
150
+ const accounted = /* @__PURE__ */ new Set();
151
+ for (const workspace of workspaces) {
152
+ const members = [];
153
+ for (const id of workspace.sessionIds) {
154
+ const summary = list.byId[id];
155
+ if (summary === void 0) continue;
156
+ accounted.add(id);
157
+ if (!sessionVisible(summary, list.current, archived)) continue;
158
+ members.push(summary);
159
+ }
160
+ groups.push(buildGroup(workspace.workspaceId, workspace.workspaceId, workspace.path, Date.parse(workspace.createdAt), workspace.title, members, "account"));
161
+ }
162
+ const stray = list.ids.map((id) => list.byId[id]).filter((s) => s !== void 0 && !accounted.has(s.id) && sessionVisible(s, list.current, archived));
163
+ if (stray.length > 0) groups.push(buildGroup("", void 0, void 0, void 0, UNGROUPED_LABEL, ungroupedOrder === void 0 ? stray : orderedUngrouped(stray, ungroupedOrder), ungroupedOrder === void 0 ? "recency" : "account"));
164
+ return groups;
165
+ }
166
+ function sessionNode(s, descendants) {
167
+ return {
168
+ id: s.id,
169
+ title: sessionTitle(s),
170
+ blank: s.blank,
171
+ running: s.running,
172
+ runningSubagentCount: descendants.get(s.id)?.runningCount ?? 0,
173
+ completed: s.completed === true,
174
+ updatedAt: s.updatedAt,
175
+ ...s.pendingInteraction === void 0 ? {} : { pendingInteraction: s.pendingInteraction }
176
+ };
177
+ }
178
+ /**
179
+ * Derive the workspace browser groups with every session as a top-level row.
180
+ *
181
+ * Every group shows; sessions populate under expanded groups in the selected
182
+ * local order. Blank sessions are excluded except for the selected
183
+ * provisional New Session row; archived sessions are excluded everywhere.
184
+ * Content search lives outside this derivation
185
+ * (see {@link deriveSearchResults}).
186
+ * @param list - sessions list snapshot (`current` feeds containsCurrent).
187
+ * @param workspaces - real workspaces in stable Host order.
188
+ * @param archivedSessionIds - registry-global archive set.
189
+ * @param view - local expansion arrays.
190
+ * @returns group sections in render order.
191
+ */
192
+ function deriveGroups(list, workspaces, archivedSessionIds, view) {
193
+ const archived = new Set(archivedSessionIds);
194
+ const expandedGroups = new Set(view.expandedGroups);
195
+ const descendants = (0, _deepseek_ai_dsh_client_runtime_client.indexSubagentDescendants)(list.byId);
196
+ const currentGroup = list.current === void 0 ? void 0 : workspaces.find((w) => w.sessionIds.includes(list.current))?.workspaceId ?? "";
197
+ const groups = [];
198
+ for (const g of groupByWorkspace(list, workspaces, archived, view.ungroupedOrder)) {
199
+ const expanded = expandedGroups.has(g.key);
200
+ groups.push({
201
+ key: g.key,
202
+ workspaceId: g.workspaceId,
203
+ cwd: g.cwd,
204
+ createdAt: g.createdAt,
205
+ label: g.label,
206
+ sessionCount: g.sessions.length,
207
+ expanded,
208
+ containsCurrent: g.key === currentGroup,
209
+ sessions: expanded ? g.sessions.map((session) => sessionNode(session, descendants)) : []
210
+ });
211
+ }
212
+ return groups;
213
+ }
214
+ /**
215
+ * Derive the flat session list ("In one list" mode): every session — fork
216
+ * children included — as a top-level row, strictly newest-first. No grouping,
217
+ * no parent/child adjacency. Content search lives outside this derivation
218
+ * (see {@link deriveSearchResults}).
219
+ * @param list - sessions list snapshot.
220
+ * @param archivedSessionIds - registry-global archive set.
221
+ * @returns flat rows in render order.
222
+ */
223
+ function deriveFlat(list, archivedSessionIds) {
224
+ const archived = new Set(archivedSessionIds);
225
+ const descendants = (0, _deepseek_ai_dsh_client_runtime_client.indexSubagentDescendants)(list.byId);
226
+ const rows = [];
227
+ for (const id of list.ids) {
228
+ const s = list.byId[id];
229
+ if (s === void 0 || !sessionVisible(s, list.current, archived)) continue;
230
+ rows.push(s);
231
+ }
232
+ rows.sort(byRecency);
233
+ return rows.map((session) => sessionNode(session, descendants));
234
+ }
235
+ /**
236
+ * Merge immediate title/Workspace substring matches with ranked Host content
237
+ * matches. Local rows lead newest-first, content-only rows retain backend
238
+ * order, and duplicate sessions receive the backend snippet in place.
239
+ * @param list - session metadata authority.
240
+ * @param workspaces - Workspace membership and display labels.
241
+ * @param query - caller text; surrounding whitespace is ignored.
242
+ * @param archivedSessionIds - registry-global archive set (members never match).
243
+ * @param content - ranked Host content-search page.
244
+ * @param limit - protocol-owned maximum merged row count.
245
+ * @returns bounded deduplicated flat rows and a refine-query hint bit.
246
+ */
247
+ function deriveSearchResults(list, workspaces, query, archivedSessionIds, content, limit) {
248
+ const q = query.trim().toLowerCase();
249
+ if (q === "") return {
250
+ items: [],
251
+ hasMore: false
252
+ };
253
+ const archived = new Set(archivedSessionIds);
254
+ const descendants = (0, _deepseek_ai_dsh_client_runtime_client.indexSubagentDescendants)(list.byId);
255
+ const workspaceBySession = /* @__PURE__ */ new Map();
256
+ for (const workspace of workspaces) for (const sessionId of workspace.sessionIds) if (!workspaceBySession.has(sessionId)) workspaceBySession.set(sessionId, workspace.title);
257
+ const labelOf = (summary) => workspaceBySession.get(summary.id) ?? workspaceLabel(summary.cwd);
258
+ const contentBySession = /* @__PURE__ */ new Map();
259
+ for (const item of content.items) if (!contentBySession.has(item.sessionId)) contentBySession.set(item.sessionId, item);
260
+ const local = [];
261
+ for (const id of list.ids) {
262
+ const summary = list.byId[id];
263
+ if (summary === void 0 || summary.blank || !sessionVisible(summary, list.current, archived)) continue;
264
+ if (sessionTitle(summary).toLowerCase().includes(q) || labelOf(summary).toLowerCase().includes(q)) local.push(summary);
265
+ }
266
+ local.sort(byRecency);
267
+ const ordered = [];
268
+ const included = /* @__PURE__ */ new Set();
269
+ const include = (summary) => {
270
+ if (included.has(summary.id)) return;
271
+ included.add(summary.id);
272
+ ordered.push(summary);
273
+ };
274
+ for (const summary of local) include(summary);
275
+ for (const item of content.items) {
276
+ const summary = list.byId[item.sessionId];
277
+ if (summary !== void 0 && !summary.blank && sessionVisible(summary, list.current, archived)) include(summary);
278
+ }
279
+ return {
280
+ items: ordered.slice(0, limit).map((summary) => {
281
+ const match = contentBySession.get(summary.id);
282
+ return {
283
+ id: summary.id,
284
+ title: sessionTitle(summary),
285
+ workspace: labelOf(summary),
286
+ running: summary.running,
287
+ runningSubagentCount: descendants.get(summary.id)?.runningCount ?? 0,
288
+ ...summary.pendingInteraction === void 0 ? {} : { pendingInteraction: summary.pendingInteraction },
289
+ completed: summary.completed === true,
290
+ ...match === void 0 ? {} : { snippet: match.snippet }
291
+ };
292
+ }),
293
+ hasMore: content.hasMore || ordered.length > limit
294
+ };
295
+ }
296
+ /**
297
+ * Compact relative time for session rows, as a structured bucket the
298
+ * renderer localizes ("now"/"5min"/"3h"/"2d"/"4mo"/"1y" in en).
299
+ * @param updatedAt - epoch ms of the session's last activity.
300
+ * @param now - current epoch ms (injected for pure rendering).
301
+ * @returns the row's trailing time bucket and magnitude.
302
+ */
303
+ function relativeTime(updatedAt, now) {
304
+ const MIN = 6e4;
305
+ const HOUR = 36e5;
306
+ const DAY = 864e5;
307
+ const diff = Math.max(0, now - updatedAt);
308
+ if (diff < MIN) return {
309
+ unit: "now",
310
+ n: 0
311
+ };
312
+ if (diff < HOUR) return {
313
+ unit: "minutes",
314
+ n: Math.floor(diff / MIN)
315
+ };
316
+ if (diff < DAY) return {
317
+ unit: "hours",
318
+ n: Math.floor(diff / HOUR)
319
+ };
320
+ if (diff < 30 * DAY) return {
321
+ unit: "days",
322
+ n: Math.floor(diff / DAY)
323
+ };
324
+ if (diff < 365 * DAY) return {
325
+ unit: "months",
326
+ n: Math.floor(diff / (30 * DAY))
327
+ };
328
+ return {
329
+ unit: "years",
330
+ n: Math.floor(diff / (365 * DAY))
331
+ };
332
+ }
333
+ //#endregion
334
+ //#region \0dsh-css:/home/runner/work/deepseek-harness/deepseek-harness/packages/client/ui-workspace/src/client/rows/Rows.module.css.mjs
335
+ const css$2 = ".YDXeBa_projectRow,.YDXeBa_sessionRow{cursor:pointer;user-select:none;color:var(--dsw-alias-label-primary);border-radius:8px;align-items:center;gap:6px;padding:0 8px;display:flex}.YDXeBa_projectRow:hover,.YDXeBa_sessionRow:hover,.YDXeBa_sessionRow.YDXeBa_selected{background:var(--dsw-alias-interactive-bg-hover)}.YDXeBa_searchResultRow{box-sizing:border-box;cursor:pointer;text-align:left;width:100%;min-height:48px;color:var(--dsw-alias-label-primary);background:0 0;border:none;border-radius:8px;flex-direction:column;align-items:stretch;padding:4px 8px;display:flex}.YDXeBa_searchResultRow:hover,.YDXeBa_searchResultRow.YDXeBa_selected{background:var(--dsw-alias-interactive-bg-hover)}.YDXeBa_searchResultHeading{align-items:center;min-width:0;display:flex}.YDXeBa_searchResultTitle{text-overflow:ellipsis;white-space:nowrap;min-width:0;margin-left:4px;font-size:14px;line-height:20px;overflow:hidden}.YDXeBa_searchResultMeta{align-items:center;gap:6px;min-width:0;margin-left:20px;display:flex}.YDXeBa_searchResultWorkspace,.YDXeBa_searchResultSnippet{text-overflow:ellipsis;white-space:nowrap;font-size:12px;line-height:17px;overflow:hidden}.YDXeBa_searchResultWorkspace{max-width:40%;color:var(--dsw-alias-label-tertiary);flex:none}.YDXeBa_searchResultSnippet{min-width:0;color:var(--dsw-alias-label-secondary);flex:1}.YDXeBa_projectRow{box-sizing:border-box;align-items:center;height:34px}.YDXeBa_projectRow .YDXeBa_rowActions{height:20px}.YDXeBa_sessionRow{height:32px;animation:YDXeBa_row-in .15s var(--ds-ease-in-out);gap:0}.YDXeBa_sessionRow .YDXeBa_title{margin:0 6px 0 4px}.YDXeBa_flatSessionRowWithoutStatus .YDXeBa_title{margin-left:0}@keyframes YDXeBa_row-in{0%{opacity:0}}.YDXeBa_slot{width:16px;height:20px;color:var(--dsw-alias-label-tertiary);flex:none;justify-content:center;align-items:center;display:inline-flex}.YDXeBa_visuallyHidden{clip:rect(0 0 0 0);white-space:nowrap;width:1px;height:1px;position:absolute;overflow:hidden}.YDXeBa_folderActive{color:var(--dsw-alias-state-business-primary)}.YDXeBa_projectRow .YDXeBa_chevron{display:none}.YDXeBa_projectRow:hover .YDXeBa_chevron{display:inline-flex}.YDXeBa_projectRow:hover .YDXeBa_folder{display:none}.YDXeBa_arrow{transition:transform .15s var(--ds-ease-in-out)}.YDXeBa_arrowOpen{transform:rotate(90deg)}.YDXeBa_projectText{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.YDXeBa_title{text-overflow:ellipsis;white-space:nowrap;min-width:0;font-size:14px;line-height:20px;overflow:hidden}.YDXeBa_renameInput{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-button-elevated-fill);min-width:0;color:inherit;border-radius:4px;outline:none;padding:0 2px;font-size:14px;line-height:20px}.YDXeBa_sessionRow .YDXeBa_title{flex:1}.YDXeBa_meta{text-overflow:ellipsis;white-space:nowrap;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:20px;overflow:hidden}.YDXeBa_time{color:var(--dsw-alias-label-tertiary);flex:none;font-size:12px;line-height:20px}.YDXeBa_dot{flex:none}.YDXeBa_rowActions{flex:none;align-items:center;gap:12px;display:none}.YDXeBa_projectRow:hover .YDXeBa_rowActions,.YDXeBa_sessionRow:hover .YDXeBa_rowActions,.YDXeBa_projectRow.YDXeBa_menuOpen .YDXeBa_rowActions,.YDXeBa_sessionRow.YDXeBa_menuOpen .YDXeBa_rowActions{display:inline-flex}.YDXeBa_sessionRow:hover .YDXeBa_time,.YDXeBa_sessionRow.YDXeBa_menuOpen .YDXeBa_time{display:none}.YDXeBa_projectRow.YDXeBa_menuOpen,.YDXeBa_sessionRow.YDXeBa_menuOpen{background:var(--dsw-alias-interactive-bg-hover)}.YDXeBa_sessionRow.YDXeBa_dropBefore,.YDXeBa_sessionRow.YDXeBa_dropAfter{position:relative}.YDXeBa_sessionRow.YDXeBa_dropBefore:before,.YDXeBa_sessionRow.YDXeBa_dropAfter:after{content:\"\";z-index:1;background:linear-gradient(55deg, transparent calc(50% - 1px), var(--dsw-alias-state-business-primary) calc(50% - 1px) calc(50% + 1px), transparent calc(50% + 1px)) 0 0 / 5px 7px no-repeat, linear-gradient(125deg, transparent calc(50% - 1px), var(--dsw-alias-state-business-primary) calc(50% - 1px) calc(50% + 1px), transparent calc(50% + 1px)) 0 5px / 5px 7px no-repeat, linear-gradient(var(--dsw-alias-state-business-primary) 0 0) 4px 5px / calc(100% - 4px) 2px no-repeat;pointer-events:none;height:12px;position:absolute;left:0;right:4px}.YDXeBa_sessionRow.YDXeBa_dropBefore:before{top:-7px}.YDXeBa_sessionRow.YDXeBa_dropAfter:after{bottom:-7px}.YDXeBa_hoverContent{flex-direction:column;gap:8px;display:flex}.YDXeBa_hoverTitle{color:#fff;overflow-wrap:break-word;font-size:14px;line-height:20px}.YDXeBa_hoverPath{color:#cfd3d6;word-break:break-all;font-size:12px;line-height:16px}.YDXeBa_hoverTime{color:#cfd3d6;font-size:12px;line-height:16px}.YDXeBa_hoverStatus{color:#adb2b8;align-items:center;gap:8px;font-size:12px;line-height:20px;display:flex}.YDXeBa_iconButton{cursor:pointer;width:16px;height:16px;color:var(--dsw-alias-label-tertiary);background:0 0;border:none;border-radius:4px;flex:none;justify-content:center;align-items:center;padding:0;display:inline-flex}.YDXeBa_iconButton:hover{color:var(--dsw-alias-label-primary)}.YDXeBa_chevron{color:var(--dsw-alias-label-caption)}@media (prefers-reduced-motion:reduce){.YDXeBa_sessionRow,.YDXeBa_arrow{transition:none;animation:none}}";
336
+ const tagId$2 = "@deepseek-ai/dsh-client-ui-workspace/Rows.module.css";
337
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$2) + "]") === null) {
338
+ const tag = document.createElement("style");
339
+ tag.dataset.plugin = "@deepseek-ai/dsh-client-ui-workspace";
340
+ tag.dataset.pluginCss = tagId$2;
341
+ tag.textContent = css$2;
342
+ document.head.appendChild(tag);
343
+ }
344
+ var Rows_module_css_default = {
345
+ "arrow": "YDXeBa_arrow",
346
+ "arrowOpen": "YDXeBa_arrowOpen",
347
+ "chevron": "YDXeBa_chevron",
348
+ "dot": "YDXeBa_dot",
349
+ "dropAfter": "YDXeBa_dropAfter",
350
+ "dropBefore": "YDXeBa_dropBefore",
351
+ "flatSessionRowWithoutStatus": "YDXeBa_flatSessionRowWithoutStatus",
352
+ "folder": "YDXeBa_folder",
353
+ "folderActive": "YDXeBa_folderActive",
354
+ "hoverContent": "YDXeBa_hoverContent",
355
+ "hoverPath": "YDXeBa_hoverPath",
356
+ "hoverStatus": "YDXeBa_hoverStatus",
357
+ "hoverTime": "YDXeBa_hoverTime",
358
+ "hoverTitle": "YDXeBa_hoverTitle",
359
+ "iconButton": "YDXeBa_iconButton",
360
+ "menuOpen": "YDXeBa_menuOpen",
361
+ "meta": "YDXeBa_meta",
362
+ "projectRow": "YDXeBa_projectRow",
363
+ "projectText": "YDXeBa_projectText",
364
+ "renameInput": "YDXeBa_renameInput",
365
+ "row-in": "YDXeBa_row-in",
366
+ "rowActions": "YDXeBa_rowActions",
367
+ "searchResultHeading": "YDXeBa_searchResultHeading",
368
+ "searchResultMeta": "YDXeBa_searchResultMeta",
369
+ "searchResultRow": "YDXeBa_searchResultRow",
370
+ "searchResultSnippet": "YDXeBa_searchResultSnippet",
371
+ "searchResultTitle": "YDXeBa_searchResultTitle",
372
+ "searchResultWorkspace": "YDXeBa_searchResultWorkspace",
373
+ "selected": "YDXeBa_selected",
374
+ "sessionRow": "YDXeBa_sessionRow",
375
+ "slot": "YDXeBa_slot",
376
+ "time": "YDXeBa_time",
377
+ "title": "YDXeBa_title",
378
+ "visuallyHidden": "YDXeBa_visuallyHidden"
379
+ };
380
+ //#endregion
381
+ //#region lib/types/client/rows/Rows.js
382
+ /**
383
+ * Workspace browser tree row components (figma Cell set 14:3080): pure presentational —
384
+ * all data and callbacks arrive via props. Hover swaps (folder->chevron,
385
+ * time->ellipsis, action buttons) are CSS-only. Row ... menus are visual-only
386
+ * except workspace Rename/Delete and session Rename/Fork/Archive; the session
387
+ * and workspace hover cards are suppressed while a menu is open.
388
+ */
389
+ /** Row display title: blank rows show the localized New Session label. */
390
+ function displayTitle(node, t) {
391
+ return node.blank ? t("session.new") : node.title;
392
+ }
393
+ /** Localized compact relative time ("刚刚"/"5分钟" in zh, "now"/"5min" in en). */
394
+ function timeLabel(updatedAt, now, t) {
395
+ const { unit, n } = relativeTime(updatedAt, now);
396
+ return unit === "now" ? t("time.now") : t(`time.${unit}`, { n });
397
+ }
398
+ /** Hover-card variant: distances wrap in the ago template; the now bucket stays bare (no "now ago"). */
399
+ function hoverTimeLabel(updatedAt, now, t) {
400
+ const { unit, n } = relativeTime(updatedAt, now);
401
+ return unit === "now" ? t("time.now") : t("time.ago", { t: t(`time.${unit}`, { n }) });
402
+ }
403
+ /**
404
+ * Absolute creation time through the dictionary's date template (the message
405
+ * clock pattern): `toLocaleString` would follow the browser language, not the
406
+ * app locale, and produce mixed-language text after a switch.
407
+ */
408
+ function createdLabel(createdAt, t) {
409
+ const d = new Date(createdAt);
410
+ const pad2 = (v) => String(v).padStart(2, "0");
411
+ return t("hover.created", { time: `${t("date.ymd", {
412
+ y: d.getFullYear(),
413
+ m: d.getMonth() + 1,
414
+ d: d.getDate()
415
+ })} ${pad2(d.getHours())}:${pad2(d.getMinutes())}` });
416
+ }
417
+ /** Hover-card body: workspace title, display directory path, absolute creation time. */
418
+ function WorkspaceHoverContent({ label, cwd, createdAt, t }) {
419
+ return (0, react_jsx_runtime.jsxs)("div", {
420
+ className: Rows_module_css_default.hoverContent,
421
+ children: [
422
+ (0, react_jsx_runtime.jsx)("div", {
423
+ className: Rows_module_css_default.hoverTitle,
424
+ children: label
425
+ }),
426
+ (0, react_jsx_runtime.jsx)("div", {
427
+ className: Rows_module_css_default.hoverPath,
428
+ children: cwd
429
+ }),
430
+ (0, react_jsx_runtime.jsx)("div", {
431
+ className: Rows_module_css_default.hoverTime,
432
+ children: createdLabel(createdAt, t)
433
+ })
434
+ ]
435
+ });
436
+ }
437
+ /** Pointer-position half of a row (insert line above or below). */
438
+ function rowHalf(e) {
439
+ const rect = e.currentTarget.getBoundingClientRect();
440
+ return e.clientY < rect.top + rect.height / 2 ? "before" : "after";
441
+ }
442
+ /**
443
+ * Project (workspace) header row: folder + title;
444
+ * hover reveals the chevron and create button, and dwelling on a real
445
+ * Workspace shows its hover card (the ungrouped bucket has none).
446
+ * `containsCurrent` arrives on the node (derivation fact, no renderer scan).
447
+ * @param props.group - derived group node.
448
+ * @param props.onToggle - expand/collapse the group.
449
+ * @param props.onCreate - start a frontend Session inside this Workspace.
450
+ * @param props.drag - optional workspace-row drag wiring.
451
+ * @param props.home - host account home for POSIX hover-path abbreviation.
452
+ * @param props.t - the browser root's locale seat.
453
+ * @returns the row element.
454
+ */
455
+ function ProjectRowItem({ group, onToggle, onCreate, actions, drag, home, t }) {
456
+ const row = group;
457
+ const label = row.workspaceId === void 0 ? t("group.ungrouped") : row.label;
458
+ const active = group.expanded && group.containsCurrent;
459
+ const [menuOpen, setMenuOpen] = (0, react.useState)(false);
460
+ const workspaceMenuItems = [{
461
+ id: "rename",
462
+ label: t("rename"),
463
+ icon: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconEditOutline16, {})
464
+ }, {
465
+ id: "delete",
466
+ label: t("delete.workspace"),
467
+ icon: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconTrashOutline16, {}),
468
+ danger: true
469
+ }];
470
+ const ownRow = (0, react_jsx_runtime.jsxs)("div", {
471
+ className: clsx(Rows_module_css_default.projectRow, menuOpen && Rows_module_css_default.menuOpen),
472
+ role: "treeitem",
473
+ "aria-expanded": row.expanded,
474
+ onClick: onToggle,
475
+ draggable: drag !== void 0,
476
+ onDragStart: drag === void 0 ? void 0 : (e) => {
477
+ e.dataTransfer.effectAllowed = "move";
478
+ e.dataTransfer.setData("text/plain", row.key);
479
+ drag.start();
480
+ },
481
+ onDragEnd: drag?.end,
482
+ children: [
483
+ (0, react_jsx_runtime.jsx)("span", {
484
+ className: clsx(Rows_module_css_default.slot, Rows_module_css_default.folder, active && Rows_module_css_default.folderActive),
485
+ children: row.expanded ? (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderOpen16, {}) : (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderClose16, {})
486
+ }),
487
+ (0, react_jsx_runtime.jsx)("span", {
488
+ className: clsx(Rows_module_css_default.slot, Rows_module_css_default.chevron),
489
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconTriangleRightFill14, { className: clsx(Rows_module_css_default.arrow, row.expanded && Rows_module_css_default.arrowOpen) })
490
+ }),
491
+ (0, react_jsx_runtime.jsx)("span", {
492
+ className: Rows_module_css_default.projectText,
493
+ children: (0, react_jsx_runtime.jsx)("span", {
494
+ className: Rows_module_css_default.title,
495
+ children: label
496
+ })
497
+ }),
498
+ (0, react_jsx_runtime.jsxs)("span", {
499
+ className: Rows_module_css_default.rowActions,
500
+ children: [actions !== void 0 && (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu, {
501
+ open: menuOpen,
502
+ onClose: () => {
503
+ setMenuOpen(false);
504
+ },
505
+ items: workspaceMenuItems,
506
+ onSelect: (id) => {
507
+ setMenuOpen(false);
508
+ /* v8 ignore next -- workspaceMenuItems carries exactly these two rows today. */
509
+ if (id !== "rename" && id !== "delete") return;
510
+ if (id === "rename") actions.rename();
511
+ else actions.delete();
512
+ },
513
+ portal: true,
514
+ closeOnPointerLeave: true,
515
+ anchor: (0, react_jsx_runtime.jsx)("button", {
516
+ type: "button",
517
+ className: Rows_module_css_default.iconButton,
518
+ "aria-label": t("actions.workspace.aria", { name: label }),
519
+ onClick: (e) => {
520
+ e.stopPropagation();
521
+ setMenuOpen((v) => !v);
522
+ },
523
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconEllipsisOutline16, {})
524
+ })
525
+ }), (0, react_jsx_runtime.jsx)("button", {
526
+ type: "button",
527
+ className: Rows_module_css_default.iconButton,
528
+ "aria-label": t("actions.newSession.aria", { name: label }),
529
+ onClick: (e) => {
530
+ e.stopPropagation();
531
+ onCreate();
532
+ },
533
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPlusOutline16, {})
534
+ })]
535
+ })
536
+ ]
537
+ });
538
+ if (row.createdAt === void 0) return ownRow;
539
+ return (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.HoverCard, {
540
+ anchor: ownRow,
541
+ content: (0, react_jsx_runtime.jsx)(WorkspaceHoverContent, {
542
+ label: row.label,
543
+ cwd: row.cwd === void 0 ? void 0 : (0, _deepseek_ai_dsh_client_runtime_client.abbreviateHomePath)(row.cwd, home),
544
+ createdAt: row.createdAt,
545
+ t
546
+ }),
547
+ disabled: menuOpen,
548
+ copyText: row.cwd,
549
+ copyLabel: t("copy"),
550
+ copiedLabel: t("hover.copied")
551
+ });
552
+ }
553
+ /* v8 ignore next 3 -- closed-union backstop; only reached if the status is forged */
554
+ function assertNever(value) {
555
+ throw new Error(`unknown pending interaction: ${String(value)}`);
556
+ }
557
+ /**
558
+ * Session status presentation; pending interaction is primary and live activity
559
+ * outranks completion reminders.
560
+ */
561
+ function sessionStatuses(node, t) {
562
+ const subagents = node.runningSubagentCount === 0 ? void 0 : {
563
+ state: "ongoing",
564
+ label: t(node.runningSubagentCount === 1 ? "status.subagentsRunning.one" : "status.subagentsRunning.other", { n: node.runningSubagentCount })
565
+ };
566
+ let pending;
567
+ switch (node.pendingInteraction) {
568
+ case "approval":
569
+ pending = {
570
+ state: "warning",
571
+ label: t("status.waitingApproval")
572
+ };
573
+ break;
574
+ case "plan-review":
575
+ pending = {
576
+ state: "warning",
577
+ label: t("status.planReview")
578
+ };
579
+ break;
580
+ case "question":
581
+ pending = {
582
+ state: "warning",
583
+ label: t("status.waitingAnswer")
584
+ };
585
+ break;
586
+ case void 0: break;
587
+ /* v8 ignore next -- closed PendingInteractionStatus union */
588
+ default: return assertNever(node.pendingInteraction);
589
+ }
590
+ if (pending !== void 0) return subagents === void 0 ? [pending] : [pending, subagents];
591
+ if (node.running) {
592
+ const primary = {
593
+ state: "ongoing",
594
+ label: t("status.running")
595
+ };
596
+ return subagents === void 0 ? [primary] : [primary, subagents];
597
+ }
598
+ if (subagents !== void 0) return [subagents];
599
+ if (node.completed) return [{
600
+ state: "done",
601
+ label: t("status.completed")
602
+ }];
603
+ return [{
604
+ state: "done",
605
+ label: t("status.idle")
606
+ }];
607
+ }
608
+ /** Primary status dot plus every status's screen-reader label, shared by the search and session rows. */
609
+ function SessionStatusDots({ statuses }) {
610
+ return (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.StateDot, { state: statuses[0].state }), statuses.map((status) => (0, react_jsx_runtime.jsx)("span", {
611
+ className: Rows_module_css_default.visuallyHidden,
612
+ children: status.label
613
+ }, status.label))] });
614
+ }
615
+ /** Hover-card body: full title, relative time, and every relevant live status. */
616
+ function SessionHoverContent({ node, now, t }) {
617
+ const statuses = sessionStatuses(node, t);
618
+ return (0, react_jsx_runtime.jsxs)("div", {
619
+ className: Rows_module_css_default.hoverContent,
620
+ children: [
621
+ (0, react_jsx_runtime.jsx)("div", {
622
+ className: Rows_module_css_default.hoverTitle,
623
+ children: displayTitle(node, t)
624
+ }),
625
+ !node.blank && (0, react_jsx_runtime.jsx)("div", {
626
+ className: Rows_module_css_default.hoverTime,
627
+ children: hoverTimeLabel(node.updatedAt, now, t)
628
+ }),
629
+ statuses.map((status) => (0, react_jsx_runtime.jsxs)("div", {
630
+ className: Rows_module_css_default.hoverStatus,
631
+ children: [(0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.StateDot, { state: status.state }), (0, react_jsx_runtime.jsx)("span", { children: status.label })]
632
+ }, status.label))
633
+ ]
634
+ });
635
+ }
636
+ /**
637
+ * One flat search result: title, Workspace context, and optional content
638
+ * excerpt. Search navigation opens the session only; it does not address an
639
+ * event inside the conversation.
640
+ * @param props.result - merged local/content search row.
641
+ * @param props.currentId - selected session id.
642
+ * @param props.onOpen - open the selected session.
643
+ * @param props.t - Workspace-browser translation seat.
644
+ * @returns the result button.
645
+ */
646
+ function SearchResultItem({ result, currentId, onOpen, t }) {
647
+ const selected = result.id === currentId;
648
+ const statuses = sessionStatuses(result, t);
649
+ const primaryStatus = statuses[0];
650
+ return (0, react_jsx_runtime.jsxs)("button", {
651
+ type: "button",
652
+ className: clsx(Rows_module_css_default.searchResultRow, selected && Rows_module_css_default.selected),
653
+ role: "treeitem",
654
+ "aria-selected": selected,
655
+ onClick: () => {
656
+ onOpen(result.id);
657
+ },
658
+ children: [(0, react_jsx_runtime.jsxs)("span", {
659
+ className: Rows_module_css_default.searchResultHeading,
660
+ children: [(0, react_jsx_runtime.jsx)("span", {
661
+ className: Rows_module_css_default.slot,
662
+ children: (primaryStatus.state !== "done" || result.completed) && (0, react_jsx_runtime.jsx)(SessionStatusDots, { statuses })
663
+ }), (0, react_jsx_runtime.jsx)("span", {
664
+ className: Rows_module_css_default.searchResultTitle,
665
+ children: result.title
666
+ })]
667
+ }), (0, react_jsx_runtime.jsxs)("span", {
668
+ className: Rows_module_css_default.searchResultMeta,
669
+ children: [(0, react_jsx_runtime.jsx)("span", {
670
+ className: Rows_module_css_default.searchResultWorkspace,
671
+ children: result.workspace
672
+ }), result.snippet !== void 0 && (0, react_jsx_runtime.jsx)("span", {
673
+ className: Rows_module_css_default.searchResultSnippet,
674
+ children: result.snippet
675
+ })]
676
+ })]
677
+ });
678
+ }
679
+ /**
680
+ * One top-level 34px session row: status dot (pending user interaction outranks
681
+ * own or descendant activity), title, relative time, and the row actions menu.
682
+ * @param props.node - derived session node.
683
+ * @param props.currentId - selected session id (row highlight).
684
+ * @param props.now - epoch ms for relative-time formatting.
685
+ * @param props.onOpen - open a session by id.
686
+ * @param props.onRename - open the session rename dialog (id + current title).
687
+ * @param props.onFork - fork a session at its last completed turn.
688
+ * @param props.onArchive - archive a session by id.
689
+ * @param props.drag - optional draggable-row wiring.
690
+ * @param props.flat - omit the empty status slot in the hierarchy-free flat list.
691
+ * @param props.t - the browser root's locale seat.
692
+ * @returns the session row.
693
+ */
694
+ function SessionNodeItem({ node, currentId, now, onOpen, onRename, onFork, onArchive, drag, flat = false, t }) {
695
+ const row = node;
696
+ const title = displayTitle(node, t);
697
+ const selected = node.id === currentId;
698
+ const statuses = sessionStatuses(node, t);
699
+ const showStatus = statuses[0].state !== "done" || row.completed;
700
+ const [menuOpen, setMenuOpen] = (0, react.useState)(false);
701
+ const sessionMenuItems = [
702
+ {
703
+ id: "rename",
704
+ label: t("rename"),
705
+ icon: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconEditOutline16, {})
706
+ },
707
+ {
708
+ id: "fork",
709
+ label: t("menu.fork"),
710
+ icon: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconBranchOutline16, {})
711
+ },
712
+ {
713
+ id: "archive",
714
+ label: t("menu.archiveSession"),
715
+ icon: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconArchiveOutline20, { size: 16 })
716
+ }
717
+ ];
718
+ return (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.HoverCard, {
719
+ anchor: (0, react_jsx_runtime.jsxs)("div", {
720
+ className: clsx(Rows_module_css_default.sessionRow, selected && Rows_module_css_default.selected, menuOpen && Rows_module_css_default.menuOpen, flat && !showStatus && Rows_module_css_default.flatSessionRowWithoutStatus, drag?.marker === "before" && Rows_module_css_default.dropBefore, drag?.marker === "after" && Rows_module_css_default.dropAfter),
721
+ role: "treeitem",
722
+ "aria-selected": selected,
723
+ onClick: () => {
724
+ onOpen(node.id);
725
+ },
726
+ draggable: drag !== void 0,
727
+ onDragStart: drag === void 0 ? void 0 : (e) => {
728
+ e.dataTransfer.effectAllowed = "move";
729
+ e.dataTransfer.setData("text/plain", node.id);
730
+ drag.start();
731
+ },
732
+ onDragEnd: drag?.end,
733
+ onDragOver: drag === void 0 ? void 0 : (e) => {
734
+ if (!drag.active) return;
735
+ e.preventDefault();
736
+ e.dataTransfer.dropEffect = "move";
737
+ drag.hover(rowHalf(e));
738
+ },
739
+ onDrop: drag === void 0 ? void 0 : (e) => {
740
+ if (!drag.active) return;
741
+ e.preventDefault();
742
+ drag.drop(rowHalf(e));
743
+ },
744
+ children: [
745
+ (!flat || showStatus) && (0, react_jsx_runtime.jsx)("span", {
746
+ className: Rows_module_css_default.slot,
747
+ children: showStatus && (0, react_jsx_runtime.jsx)(SessionStatusDots, { statuses })
748
+ }),
749
+ (0, react_jsx_runtime.jsx)("span", {
750
+ className: Rows_module_css_default.title,
751
+ children: title
752
+ }),
753
+ !row.blank && (0, react_jsx_runtime.jsx)("span", {
754
+ className: Rows_module_css_default.time,
755
+ children: timeLabel(row.updatedAt, now, t)
756
+ }),
757
+ !row.blank && (0, react_jsx_runtime.jsx)("span", {
758
+ className: Rows_module_css_default.rowActions,
759
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu, {
760
+ open: menuOpen,
761
+ onClose: () => {
762
+ setMenuOpen(false);
763
+ },
764
+ items: sessionMenuItems,
765
+ onSelect: (id) => {
766
+ setMenuOpen(false);
767
+ if (id === "rename") onRename(node.id, row.title);
768
+ if (id === "fork") onFork(node.id);
769
+ if (id === "archive") onArchive(node.id);
770
+ },
771
+ portal: true,
772
+ closeOnPointerLeave: true,
773
+ anchor: (0, react_jsx_runtime.jsx)("button", {
774
+ type: "button",
775
+ className: Rows_module_css_default.iconButton,
776
+ "aria-label": t("actions.session.aria", { name: title }),
777
+ onClick: (e) => {
778
+ e.stopPropagation();
779
+ setMenuOpen((v) => !v);
780
+ },
781
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconEllipsisOutline16, {})
782
+ })
783
+ })
784
+ })
785
+ ]
786
+ }),
787
+ content: (0, react_jsx_runtime.jsx)(SessionHoverContent, {
788
+ node,
789
+ now,
790
+ t
791
+ }),
792
+ disabled: menuOpen || drag?.active === true,
793
+ copyText: row.blank ? void 0 : row.title,
794
+ copyLabel: t("copy"),
795
+ copiedLabel: t("hover.copied")
796
+ });
797
+ }
798
+ //#endregion
799
+ //#region \0dsh-css:/home/runner/work/deepseek-harness/deepseek-harness/packages/client/ui-workspace/src/client/WorkspacePicker.module.css.mjs
800
+ const css$1 = "._G5b-a_modalAction{min-width:72px}._G5b-a_modalError,._G5b-a_menuStatus{margin-top:8px;font-size:12px;line-height:18px}._G5b-a_modalError{color:var(--dsw-alias-state-error-primary)}._G5b-a_menuStatus{color:var(--dsw-alias-label-secondary)}";
801
+ const tagId$1 = "@deepseek-ai/dsh-client-ui-workspace/WorkspacePicker.module.css";
802
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId$1) + "]") === null) {
803
+ const tag = document.createElement("style");
804
+ tag.dataset.plugin = "@deepseek-ai/dsh-client-ui-workspace";
805
+ tag.dataset.pluginCss = tagId$1;
806
+ tag.textContent = css$1;
807
+ document.head.appendChild(tag);
808
+ }
809
+ var WorkspacePicker_module_css_default = {
810
+ "menuStatus": "_G5b-a_menuStatus",
811
+ "modalAction": "_G5b-a_modalAction",
812
+ "modalError": "_G5b-a_modalError"
813
+ };
814
+ //#endregion
815
+ //#region lib/types/client/WorkspacePicker.js
816
+ const ADD_WORKSPACE = "::add-workspace";
817
+ /**
818
+ * Render the pick menu plus the adoption error dialog.
819
+ * @param props - owner-controlled flow props.
820
+ * @returns menu + dialog elements.
821
+ */
822
+ function WorkspacePickFlow({ t, open, anchorRef, useWorkspaces, createWorkspace, useDirectoryFlow, renderDirectoryFlow, onPick, onClose, addOnly = false, side = "bottom", selectedId }) {
823
+ const workspaceSnapshot = useWorkspaces((state) => state);
824
+ const workspaces = workspaceSnapshot.items;
825
+ const getAnchorRect = (0, react.useCallback)(() => anchorRef?.current?.getBoundingClientRect() ?? null, [anchorRef]);
826
+ const [errorOpen, setErrorOpen] = (0, react.useState)(false);
827
+ const [modalError, setModalError] = (0, react.useState)(null);
828
+ const [flowOpen, setFlowOpen] = (0, react.useState)(false);
829
+ const [pickingFolder, setPickingFolder] = (0, react.useState)(false);
830
+ const flowBusy = flowOpen || pickingFolder;
831
+ const flowAvailable = useDirectoryFlow((occupied) => occupied);
832
+ (0, react.useEffect)(() => {
833
+ if (flowOpen && !flowAvailable) setFlowOpen(false);
834
+ }, [flowOpen, flowAvailable]);
835
+ const addEntries = flowAvailable ? [{
836
+ id: ADD_WORKSPACE,
837
+ label: t("menu.addWorkspace"),
838
+ icon: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPlusOutline16, { size: 16 }),
839
+ disabled: flowBusy
840
+ }] : [];
841
+ const pinAdd = !addOnly && workspaces.length > 0;
842
+ const items = pinAdd ? workspaces.map((workspace) => ({
843
+ id: workspace.workspaceId,
844
+ label: workspace.title,
845
+ icon: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconFolderClose16, { size: 16 }),
846
+ disabled: flowBusy
847
+ })) : addEntries;
848
+ const menuIsEmpty = items.length === 0;
849
+ const closeModal = () => {
850
+ setErrorOpen(false);
851
+ setModalError(null);
852
+ };
853
+ /** Adopt a picked directory; failures land in the folder-error dialog (Choose again reopens the flow). */
854
+ const adoptDirectory = (path) => createWorkspace({ path }).then((workspace) => {
855
+ setFlowOpen(false);
856
+ onPick(workspace.workspaceId);
857
+ }).catch((reason) => {
858
+ setModalError(reason instanceof Error ? reason.message : String(reason));
859
+ setFlowOpen(false);
860
+ setErrorOpen(true);
861
+ });
862
+ const openDirectoryFlow = (0, react.useCallback)(() => {
863
+ onClose();
864
+ setErrorOpen(false);
865
+ setModalError(null);
866
+ setFlowOpen(true);
867
+ }, [onClose]);
868
+ const listSettled = addOnly || workspaceSnapshot.phase === "ready";
869
+ const addIsTheOnlyEntry = !pinAdd && listSettled && addEntries.length === 1;
870
+ (0, react.useEffect)(() => {
871
+ if (open && addIsTheOnlyEntry && !flowBusy) openDirectoryFlow();
872
+ }, [
873
+ open,
874
+ addIsTheOnlyEntry,
875
+ flowBusy,
876
+ openDirectoryFlow
877
+ ]);
878
+ /** Owner side of the flow conversation: adopt keeps the flow open (busy) until the Host answers. */
879
+ const flowOwner = {
880
+ open: flowOpen,
881
+ busy: pickingFolder,
882
+ onPicked: (path) => {
883
+ setPickingFolder(true);
884
+ adoptDirectory(path).finally(() => {
885
+ setPickingFolder(false);
886
+ });
887
+ },
888
+ onCancel: () => {
889
+ setFlowOpen(false);
890
+ },
891
+ onError: (message) => {
892
+ setFlowOpen(false);
893
+ setModalError(message);
894
+ setErrorOpen(true);
895
+ }
896
+ };
897
+ const handleSelect = (id) => {
898
+ if (id === ADD_WORKSPACE) {
899
+ openDirectoryFlow();
900
+ return;
901
+ }
902
+ onPick(id);
903
+ };
904
+ return (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [
905
+ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu, {
906
+ open: open && !addIsTheOnlyEntry && !menuIsEmpty,
907
+ anchor: null,
908
+ items,
909
+ ...pinAdd ? { footer: addEntries } : {},
910
+ selectedId,
911
+ onSelect: handleSelect,
912
+ onClose,
913
+ side,
914
+ portal: true,
915
+ getAnchorRect
916
+ }),
917
+ open && !addIsTheOnlyEntry && !menuIsEmpty && workspaceSnapshot.phase === "pending" && (0, react_jsx_runtime.jsx)("div", {
918
+ className: WorkspacePicker_module_css_default.menuStatus,
919
+ role: "status",
920
+ children: t("picker.loading")
921
+ }),
922
+ renderDirectoryFlow(flowOwner),
923
+ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Modal, {
924
+ open: errorOpen,
925
+ onClose: closeModal,
926
+ closeLabel: t("close"),
927
+ title: t("folderError.title"),
928
+ footer: (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
929
+ variant: "outline",
930
+ className: WorkspacePicker_module_css_default.modalAction,
931
+ onClick: closeModal,
932
+ children: t("cancel")
933
+ }), (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
934
+ variant: "primary",
935
+ className: WorkspacePicker_module_css_default.modalAction,
936
+ disabled: !flowAvailable,
937
+ onClick: openDirectoryFlow,
938
+ children: t("folderError.retry")
939
+ })] }),
940
+ children: (0, react_jsx_runtime.jsx)("div", {
941
+ className: WorkspacePicker_module_css_default.modalError,
942
+ role: "alert",
943
+ children: modalError
944
+ })
945
+ })
946
+ ] });
947
+ }
948
+ /**
949
+ * The conversation empty-state registration: adapts the owner share to the
950
+ * core flow (all state and semantics live in the flow / the owner).
951
+ * @param props - empty-state slot props (owner share + injected creation callback).
952
+ * @returns the flow element.
953
+ */
954
+ function WorkspacePicker({ open, anchorRef, useWorkspaces, selectedId, onPick, onClose, createWorkspace, useDirectoryFlow, renderSlot, t }) {
955
+ return (0, react_jsx_runtime.jsx)(WorkspacePickFlow, {
956
+ t,
957
+ open,
958
+ anchorRef,
959
+ useWorkspaces,
960
+ createWorkspace,
961
+ useDirectoryFlow,
962
+ renderDirectoryFlow: (owner) => renderSlot("conversation.hero.workspace.directoryFlow", owner),
963
+ selectedId,
964
+ onPick,
965
+ onClose
966
+ });
967
+ }
968
+ //#endregion
969
+ //#region \0dsh-css:/home/runner/work/deepseek-harness/deepseek-harness/packages/client/ui-workspace/src/client/WorkspaceBrowser.module.css.mjs
970
+ const css = ".qDHVXG_root{--dsh-session-list-edge-inset:var(--dsh-sidebar-inline-padding);--dsh-session-list-scrollbar-width:8px;--dsh-session-list-scrollbar-offset:2px;box-sizing:border-box;min-height:0;padding-right:var(--dsh-session-list-edge-inset);flex-direction:column;flex:1;display:flex}.qDHVXG_root.qDHVXG_rail{padding-right:0}.qDHVXG_iconButton{cursor:pointer;width:28px;height:28px;color:var(--dsw-alias-label-secondary);background:0 0;border:none;border-radius:50%;flex:none;justify-content:center;align-items:center;padding:0;display:inline-flex}.qDHVXG_iconButton:hover{background:var(--dsw-alias-interactive-bg-hover)}.qDHVXG_sectionHeader{box-sizing:border-box;height:36px;color:var(--dsw-alias-label-tertiary);border-radius:12px;flex:none;justify-content:flex-end;align-items:center;gap:4px;margin-bottom:4px;padding-left:4px;display:flex;overflow:hidden}.qDHVXG_root:not(.qDHVXG_rail) .qDHVXG_sectionHeader{margin-top:2px;margin-right:-4px}.qDHVXG_sectionLabel{white-space:nowrap;opacity:1;visibility:visible;min-width:0;max-width:45%;transition:max-width .18s var(--ds-ease-in-out), margin-right .18s var(--ds-ease-in-out), opacity .12s var(--ds-ease-in-out), transform .18s var(--ds-ease-in-out), visibility 0s linear;flex:none;line-height:20px;overflow:hidden}.qDHVXG_sectionLabelHidden{opacity:0;visibility:hidden;max-width:0;margin-right:-4px;transition-delay:0s,0s,0s,0s,.18s;transform:translate(-4px)}.qDHVXG_searchSlot{box-sizing:border-box;min-width:0;max-width:28px;transition:max-width .18s var(--ds-ease-in-out), padding-left .18s var(--ds-ease-in-out);flex:1;align-items:center;margin-left:auto;padding-left:0;display:flex}.qDHVXG_searchSlotExpanded{max-width:100%;padding-left:0}.qDHVXG_headerActions{opacity:1;visibility:visible;max-width:60px;transition:max-width .18s var(--ds-ease-in-out), opacity .12s var(--ds-ease-in-out), transform .18s var(--ds-ease-in-out), visibility 0s linear;flex:none;align-items:center;gap:4px;display:flex;overflow:hidden}.qDHVXG_headerActionsHidden{opacity:0;visibility:hidden;pointer-events:none;max-width:0;transition-delay:0s,0s,0s,.18s;transform:translate(4px)}.qDHVXG_search{box-sizing:border-box;cursor:text;width:100%;height:28px;color:var(--dsw-alias-label-secondary);transition:width .18s var(--ds-ease-in-out), padding .18s var(--ds-ease-in-out), border-color .18s var(--ds-ease-in-out), background-color .18s var(--ds-ease-in-out);background:0 0;border:none;border-radius:50%;flex:none;align-items:center;gap:0;margin:0;padding:0;display:flex;overflow:hidden}.qDHVXG_searchExpanded{border:1px solid var(--dsw-alias-border-l2);width:calc(100% + 4px);height:30px;color:var(--dsw-alias-label-caption);background:0 0;border-radius:10px;margin-inline:-2px;padding:0 4px 0 0}.qDHVXG_searchButton{cursor:pointer;width:28px;height:28px;color:inherit;background:0 0;border:none;border-radius:50%;flex:none;justify-content:center;align-items:center;padding:0;display:inline-flex}.qDHVXG_searchExpanded .qDHVXG_searchButton{width:28px;height:30px}.qDHVXG_searchButton:hover{background:var(--dsw-alias-interactive-bg-hover)}.qDHVXG_searchExpanded .qDHVXG_searchButton:hover{background:0 0}.qDHVXG_searchInput{opacity:0;pointer-events:none;width:0;min-width:0;color:var(--dsw-alias-label-primary);transition:opacity .12s var(--ds-ease-in-out);background:0 0;border:none;outline:none;flex:1;font-size:13px;line-height:18px}.qDHVXG_searchExpanded .qDHVXG_searchInput{opacity:1;pointer-events:auto;margin-left:-2px}.qDHVXG_searchInput::placeholder{color:var(--dsw-alias-label-tertiary)}.qDHVXG_clearButton{cursor:pointer;width:24px;height:24px;color:var(--dsw-alias-label-secondary);background:0 0;border:none;border-radius:50%;flex:none;justify-content:center;align-items:center;padding:0;display:inline-flex}.qDHVXG_clearButton:hover{background:var(--dsw-alias-interactive-bg-hover)}.qDHVXG_rail .qDHVXG_sectionHeader{justify-content:flex-start;gap:0;margin-bottom:12px;padding-left:0}.qDHVXG_rail .qDHVXG_headerActions{max-width:none}.qDHVXG_rail .qDHVXG_iconButton{width:36px;height:36px;color:var(--dsw-alias-label-primary)}.qDHVXG_rail .qDHVXG_search{background:0 0;border-color:#0000;gap:0;width:36px;height:36px;margin:0 0 12px;padding:0}.qDHVXG_rail .qDHVXG_searchButton{width:36px;height:36px;color:var(--dsw-alias-label-primary)}.qDHVXG_rail .qDHVXG_searchButton:hover{background:var(--dsw-alias-interactive-bg-hover)}.qDHVXG_listArea{min-height:0;margin-left:-4px;margin-right:calc(-1 * var(--dsh-session-list-edge-inset));flex-direction:column;flex:1;padding-left:4px;display:flex;overflow:visible}.qDHVXG_rail .qDHVXG_listArea{margin-left:0;margin-right:0;padding-left:0}.qDHVXG_treeBody{flex-direction:column;flex:1;min-height:0;display:flex;position:relative}.qDHVXG_fade{left:0;right:var(--dsh-session-list-edge-inset);background:linear-gradient(to bottom, transparent, var(--dsw-specific-sidebar-fill));pointer-events:none;height:24px;position:absolute;bottom:0}.qDHVXG_wide{animation:qDHVXG_wide-in .2s var(--ds-ease-in-out)}@keyframes qDHVXG_wide-in{0%{opacity:0}}.qDHVXG_list{min-height:0;margin-left:-4px;margin-right:var(--dsh-session-list-scrollbar-offset);padding-left:4px;padding-right:calc(var(--dsh-session-list-edge-inset) - var(--dsh-session-list-scrollbar-width) - var(--dsh-session-list-scrollbar-offset));scrollbar-gutter:stable;flex:1;padding-bottom:16px;overflow-y:auto}.qDHVXG_flatList>*+*,.qDHVXG_searchTree>[role=treeitem]+[role=treeitem],.qDHVXG_groupSection>*+*{margin-top:2px}.qDHVXG_searchStatus,.qDHVXG_searchWarning{color:var(--dsw-alias-label-tertiary);padding:10px 12px;font-size:12px;line-height:18px}.qDHVXG_searchWarning{color:var(--dsw-alias-label-secondary)}.qDHVXG_groupSection{position:relative}.qDHVXG_groupSection+.qDHVXG_groupSection{margin-top:4px}.qDHVXG_listTopDropIndicator,.qDHVXG_workspaceDropBefore:before,.qDHVXG_workspaceDropAfter:after{content:\"\";z-index:1;background:linear-gradient(55deg, transparent calc(50% - 1px), var(--dsw-alias-state-business-primary) calc(50% - 1px) calc(50% + 1px), transparent calc(50% + 1px)) 0 0 / 5px 7px no-repeat, linear-gradient(125deg, transparent calc(50% - 1px), var(--dsw-alias-state-business-primary) calc(50% - 1px) calc(50% + 1px), transparent calc(50% + 1px)) 0 5px / 5px 7px no-repeat, linear-gradient(var(--dsw-alias-state-business-primary) 0 0) 4px 5px / calc(100% - 4px) 2px no-repeat;pointer-events:none;height:12px;position:absolute;left:0;right:0}.qDHVXG_listTopDropIndicator{top:-8px;left:0;right:var(--dsh-session-list-edge-inset)}.qDHVXG_listTopDropActive>.qDHVXG_workspaceDropBefore:first-child:before{display:none}.qDHVXG_workspaceDropBefore:before{top:-8px}.qDHVXG_workspaceDropAfter:after{bottom:-8px}.qDHVXG_sessionOverflowButton{cursor:pointer;text-align:left;width:100%;height:28px;color:var(--dsw-alias-label-tertiary);background:0 0;border:none;border-radius:8px;padding:0 12px 0 28px;font-size:12px}.qDHVXG_groupSection>.qDHVXG_sessionOverflowButton{margin-top:0}.qDHVXG_sessionOverflowButton:hover{color:var(--dsw-alias-label-secondary);background:0 0}.qDHVXG_empty{color:var(--dsw-alias-label-tertiary);padding:16px 12px;font-size:13px}.qDHVXG_renameInput{box-sizing:border-box;border:1px solid var(--dsw-alias-border-l2);width:100%;height:44px;color:var(--dsw-alias-label-primary);background:0 0;border-radius:22px;outline:none;padding:7px 14px;font-size:14px;font-weight:400;line-height:22px}.qDHVXG_renameInput:disabled{color:var(--dsw-alias-label-dimmed)}.qDHVXG_renameError{color:var(--dsw-alias-state-error-primary);margin-top:8px;font-size:12px;line-height:18px}.qDHVXG_deleteAction:not(:disabled){color:var(--dsw-alias-state-error-primary)}.qDHVXG_deleteStatus{color:var(--dsw-alias-label-secondary);font-size:12px;line-height:18px}@media (prefers-reduced-motion:reduce){.qDHVXG_wide{animation:none}.qDHVXG_search,.qDHVXG_sectionLabel,.qDHVXG_searchSlot,.qDHVXG_searchInput,.qDHVXG_headerActions{transition:none}}";
971
+ const tagId = "@deepseek-ai/dsh-client-ui-workspace/WorkspaceBrowser.module.css";
972
+ if (typeof document !== "undefined" && document.querySelector("style[data-plugin-css=" + JSON.stringify(tagId) + "]") === null) {
973
+ const tag = document.createElement("style");
974
+ tag.dataset.plugin = "@deepseek-ai/dsh-client-ui-workspace";
975
+ tag.dataset.pluginCss = tagId;
976
+ tag.textContent = css;
977
+ document.head.appendChild(tag);
978
+ }
979
+ var WorkspaceBrowser_module_css_default = {
980
+ "clearButton": "qDHVXG_clearButton",
981
+ "deleteAction": "qDHVXG_deleteAction",
982
+ "deleteStatus": "qDHVXG_deleteStatus",
983
+ "empty": "qDHVXG_empty",
984
+ "fade": "qDHVXG_fade",
985
+ "flatList": "qDHVXG_flatList",
986
+ "groupSection": "qDHVXG_groupSection",
987
+ "headerActions": "qDHVXG_headerActions",
988
+ "headerActionsHidden": "qDHVXG_headerActionsHidden",
989
+ "iconButton": "qDHVXG_iconButton",
990
+ "list": "qDHVXG_list",
991
+ "listArea": "qDHVXG_listArea",
992
+ "listTopDropActive": "qDHVXG_listTopDropActive",
993
+ "listTopDropIndicator": "qDHVXG_listTopDropIndicator",
994
+ "rail": "qDHVXG_rail",
995
+ "renameError": "qDHVXG_renameError",
996
+ "renameInput": "qDHVXG_renameInput",
997
+ "root": "qDHVXG_root",
998
+ "search": "qDHVXG_search",
999
+ "searchButton": "qDHVXG_searchButton",
1000
+ "searchExpanded": "qDHVXG_searchExpanded",
1001
+ "searchInput": "qDHVXG_searchInput",
1002
+ "searchSlot": "qDHVXG_searchSlot",
1003
+ "searchSlotExpanded": "qDHVXG_searchSlotExpanded",
1004
+ "searchStatus": "qDHVXG_searchStatus",
1005
+ "searchTree": "qDHVXG_searchTree",
1006
+ "searchWarning": "qDHVXG_searchWarning",
1007
+ "sectionHeader": "qDHVXG_sectionHeader",
1008
+ "sectionLabel": "qDHVXG_sectionLabel",
1009
+ "sectionLabelHidden": "qDHVXG_sectionLabelHidden",
1010
+ "sessionOverflowButton": "qDHVXG_sessionOverflowButton",
1011
+ "treeBody": "qDHVXG_treeBody",
1012
+ "wide": "qDHVXG_wide",
1013
+ "wide-in": "qDHVXG_wide-in",
1014
+ "workspaceDropAfter": "qDHVXG_workspaceDropAfter",
1015
+ "workspaceDropBefore": "qDHVXG_workspaceDropBefore"
1016
+ };
1017
+ //#endregion
1018
+ //#region lib/types/client/WorkspaceBrowser.js
1019
+ /**
1020
+ * The workspace/session browsing region filling the sidebar shell's
1021
+ * `sidebar.workspaces` hole: section header (title + view options + add
1022
+ * workspace), search, the grouped tree or flat list, and the workspace
1023
+ * dialogs. Wide state renders the full browser; rail state renders the two
1024
+ * region icons (search / add workspace) as 36px controls on the shell's shared
1025
+ * rail entry path, each requesting expansion through the owner share. Adding
1026
+ * is the header button's one action, so it raises the directory flow with no
1027
+ * menu in between; the flow and its error dialog live in WorkspacePicker
1028
+ * (same package — direct composition, no slot between them).
1029
+ */
1030
+ /**
1031
+ * Column slide length (--ds-transition-duration-slow): rail-search focus waits it out —
1032
+ * focus() forces a synchronous layout and would jank the slide.
1033
+ */
1034
+ const EXPAND_SLIDE_MS = 300;
1035
+ /** Pause between the latest keystroke and a Host content-search request. */
1036
+ const SEARCH_DEBOUNCE_MS = 250;
1037
+ /** `session.search` wire bound, measured in JavaScript UTF-16 code units. */
1038
+ const SEARCH_QUERY_MAX_CODE_UNITS = 500;
1039
+ /** Session rows visible per Workspace before the local overflow control. */
1040
+ const COLLAPSED_SESSION_LIMIT = 5;
1041
+ /** Keep controlled input and RPC payload inside the session.search wire contract. */
1042
+ function sanitizeSearchQuery(value) {
1043
+ const withoutNul = value.replaceAll("\0", "");
1044
+ if (withoutNul.length <= SEARCH_QUERY_MAX_CODE_UNITS) return withoutNul;
1045
+ let end = SEARCH_QUERY_MAX_CODE_UNITS;
1046
+ const last = withoutNul.charCodeAt(end - 1);
1047
+ const next = withoutNul.charCodeAt(end);
1048
+ if (last >= 55296 && last <= 56319 && next >= 56320 && next <= 57343) end--;
1049
+ return withoutNul.slice(0, end);
1050
+ }
1051
+ /** Immutable membership toggle for the local expand-all array. */
1052
+ function toggled(list, key) {
1053
+ return list.includes(key) ? list.filter((k) => k !== key) : [...list, key];
1054
+ }
1055
+ /**
1056
+ * Accept the native drag at document level while a row drag is active: row
1057
+ * hover still owns the insertion marker, and releasing outside the list must
1058
+ * not be rendered as a rejected drop before dragend commits that last marker.
1059
+ */
1060
+ function useNativeDragAcceptance(active) {
1061
+ (0, react.useEffect)(() => {
1062
+ if (!active) return;
1063
+ const acceptDrag = (event) => {
1064
+ event.preventDefault();
1065
+ if (event.dataTransfer !== null) event.dataTransfer.dropEffect = "move";
1066
+ };
1067
+ const acceptDrop = (event) => {
1068
+ event.preventDefault();
1069
+ };
1070
+ document.addEventListener("dragover", acceptDrag);
1071
+ document.addEventListener("drop", acceptDrop);
1072
+ return () => {
1073
+ document.removeEventListener("dragover", acceptDrag);
1074
+ document.removeEventListener("drop", acceptDrop);
1075
+ };
1076
+ }, [active]);
1077
+ }
1078
+ /** Reconcile a stored view order with the Workspace's current session account. */
1079
+ function reconciledSessionOrder(sessionIds, stored) {
1080
+ if (stored === void 0) return [...sessionIds];
1081
+ const byId = new Map(sessionIds.map((id) => [id, id]));
1082
+ const ordered = [];
1083
+ const included = /* @__PURE__ */ new Set();
1084
+ for (const key of stored) {
1085
+ const id = byId.get(key);
1086
+ if (id === void 0 || included.has(key)) continue;
1087
+ ordered.push(id);
1088
+ included.add(key);
1089
+ }
1090
+ for (const id of sessionIds) {
1091
+ if (included.has(id)) continue;
1092
+ ordered.push(id);
1093
+ }
1094
+ return ordered;
1095
+ }
1096
+ /** Newest update first with stable Session identity as the tie-break. */
1097
+ function compareSessionRecency(a, b, byId) {
1098
+ const aUpdatedAt = byId[a]?.updatedAt ?? Number.NEGATIVE_INFINITY;
1099
+ const bUpdatedAt = byId[b]?.updatedAt ?? Number.NEGATIVE_INFINITY;
1100
+ if (aUpdatedAt !== bUpdatedAt) return bUpdatedAt - aUpdatedAt;
1101
+ return a < b ? -1 : 1;
1102
+ }
1103
+ /** Reconcile one editable order account and apply its activity-promotion policy. */
1104
+ function nextSessionOrderAccount({ sessionIds, previousOrder, previousUpdatedAt, list, orderBy, sortByRecency }) {
1105
+ let order = reconciledSessionOrder(sessionIds, previousOrder);
1106
+ if (sortByRecency) order.sort((a, b) => compareSessionRecency(a, b, list.byId));
1107
+ else if (orderBy === "updated") {
1108
+ const promoted = sessionIds.filter((id) => {
1109
+ const session = list.byId[id];
1110
+ return session !== void 0 && (previousUpdatedAt[id] === void 0 || session.updatedAt > previousUpdatedAt[id]);
1111
+ }).sort((a, b) => compareSessionRecency(a, b, list.byId));
1112
+ if (promoted.length > 0) {
1113
+ const promotedIds = new Set(promoted);
1114
+ order = [...promoted, ...order.filter((id) => !promotedIds.has(id))];
1115
+ }
1116
+ }
1117
+ const updatedAt = {};
1118
+ for (const id of sessionIds) {
1119
+ const session = list.byId[id];
1120
+ if (session !== void 0) updatedAt[id] = session.updatedAt;
1121
+ }
1122
+ const orderChanged = previousOrder === void 0 || order.length !== previousOrder.length || order.some((id, index) => id !== previousOrder[index]);
1123
+ const timestampsChanged = Object.keys(updatedAt).length !== Object.keys(previousUpdatedAt).length || Object.entries(updatedAt).some(([id, timestamp]) => previousUpdatedAt[id] !== timestamp);
1124
+ return {
1125
+ order,
1126
+ updatedAt,
1127
+ changed: orderChanged || timestampsChanged
1128
+ };
1129
+ }
1130
+ /** Grouping and ordering menu; own open state so it resets with the wide chrome. */
1131
+ function ViewOptionsMenu({ groupBy, orderBy, onGroupPick, onOrderPick, t }) {
1132
+ const [open, setOpen] = (0, react.useState)(false);
1133
+ return (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Menu, {
1134
+ open,
1135
+ onClose: () => {
1136
+ setOpen(false);
1137
+ },
1138
+ items: [
1139
+ {
1140
+ type: "label",
1141
+ id: "group-by",
1142
+ text: t("groupBy.label")
1143
+ },
1144
+ {
1145
+ id: "workspace",
1146
+ label: t("groupBy.workspace")
1147
+ },
1148
+ {
1149
+ id: "flat",
1150
+ label: t("groupBy.flat")
1151
+ },
1152
+ {
1153
+ type: "separator",
1154
+ id: "order-by-separator"
1155
+ },
1156
+ {
1157
+ type: "label",
1158
+ id: "order-by",
1159
+ text: t("orderBy.label")
1160
+ },
1161
+ {
1162
+ id: "manual",
1163
+ label: t("orderBy.manual")
1164
+ },
1165
+ {
1166
+ id: "updated",
1167
+ label: t("orderBy.updated")
1168
+ }
1169
+ ],
1170
+ selectedIds: [groupBy, orderBy],
1171
+ onSelect: (id) => {
1172
+ if (id === "workspace" || id === "flat") onGroupPick(id);
1173
+ else if (id === "manual" || id === "updated") onOrderPick(id);
1174
+ setOpen(false);
1175
+ },
1176
+ align: "end",
1177
+ dense: true,
1178
+ portal: true,
1179
+ anchor: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
1180
+ label: t("viewOptions.label"),
1181
+ side: "bottom",
1182
+ delayMs: 500,
1183
+ children: (0, react_jsx_runtime.jsx)("button", {
1184
+ type: "button",
1185
+ className: clsx(WorkspaceBrowser_module_css_default.iconButton, WorkspaceBrowser_module_css_default.wide),
1186
+ "aria-label": t("viewOptions.label"),
1187
+ onClick: () => {
1188
+ setOpen((v) => !v);
1189
+ },
1190
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconPersonalizationOutline16, {})
1191
+ })
1192
+ })
1193
+ });
1194
+ }
1195
+ /** Resolve an insertion side from the full rendered workspace group. */
1196
+ function workspaceGroupHalf(e) {
1197
+ const rect = e.currentTarget.getBoundingClientRect();
1198
+ return e.clientY < rect.top + rect.height / 2 ? "before" : "after";
1199
+ }
1200
+ /** The scrolling session tree; unmounting drops the sessions subscription and expand-all state. */
1201
+ function SessionTree({ useSessions, startSession, open, forkSession, workspaces, archivedSessionIds, onRenameRequest, onDeleteRequest, onSessionRename, onSessionArchive, insertWorkspaceBefore, insertSessionBefore, orderBy, groupExpansion, setGroupExpanded, sessionOrderByAccount, sessionUpdatedAtByAccount, syncSessionOrderAccount, setSessionOrder, home, t }) {
1202
+ const list = useSessions((s) => s);
1203
+ const current = list.current;
1204
+ const [expandedSessionGroups, setExpandedSessionGroups] = (0, react.useState)([]);
1205
+ const [drag, setDrag] = (0, react.useState)(null);
1206
+ const sessionDropCommitted = (0, react.useRef)(false);
1207
+ const [workspaceDrag, setWorkspaceDrag] = (0, react.useState)(null);
1208
+ const workspaceDropCommitted = (0, react.useRef)(false);
1209
+ const previousOrderBy = (0, react.useRef)(orderBy);
1210
+ useNativeDragAcceptance(drag !== null || workspaceDrag !== null);
1211
+ const currentGroup = current === void 0 ? void 0 : workspaces.find((w) => w.sessionIds.includes(current))?.workspaceId ?? "";
1212
+ (0, react.useEffect)(() => {
1213
+ if (current === void 0 || currentGroup === void 0 || Object.hasOwn(groupExpansion, currentGroup)) return;
1214
+ setGroupExpanded(currentGroup, true);
1215
+ }, [
1216
+ current,
1217
+ currentGroup,
1218
+ setGroupExpanded,
1219
+ groupExpansion
1220
+ ]);
1221
+ const expandedGroups = (0, react.useMemo)(() => Object.entries(groupExpansion).filter(([, expanded]) => expanded).map(([key]) => key), [groupExpansion]);
1222
+ const ungroupedSessionIds = (0, react.useMemo)(() => {
1223
+ const accounted = new Set(workspaces.flatMap((workspace) => workspace.sessionIds));
1224
+ return list.ids.filter((id) => list.byId[id] !== void 0 && !accounted.has(id));
1225
+ }, [list, workspaces]);
1226
+ (0, react.useEffect)(() => {
1227
+ if (list.phase !== "ready") return;
1228
+ const switchedToUpdated = previousOrderBy.current !== "updated" && orderBy === "updated";
1229
+ previousOrderBy.current = orderBy;
1230
+ const accounts = [...workspaces.map((workspace) => ({
1231
+ key: workspace.workspaceId,
1232
+ sessionIds: workspace.sessionIds.filter((id) => list.byId[id] !== void 0)
1233
+ })), {
1234
+ key: "",
1235
+ sessionIds: ungroupedSessionIds
1236
+ }];
1237
+ for (const { key, sessionIds } of accounts) {
1238
+ const previousOrder = sessionOrderByAccount[key];
1239
+ const next = nextSessionOrderAccount({
1240
+ sessionIds,
1241
+ previousOrder,
1242
+ previousUpdatedAt: sessionUpdatedAtByAccount[key] ?? {},
1243
+ list,
1244
+ orderBy,
1245
+ sortByRecency: orderBy === "updated" && (previousOrder === void 0 || switchedToUpdated)
1246
+ });
1247
+ if (next.changed) syncSessionOrderAccount(key, next.order.map((id) => id), next.updatedAt);
1248
+ }
1249
+ }, [
1250
+ list,
1251
+ orderBy,
1252
+ sessionOrderByAccount,
1253
+ sessionUpdatedAtByAccount,
1254
+ syncSessionOrderAccount,
1255
+ ungroupedSessionIds,
1256
+ workspaces
1257
+ ]);
1258
+ const orderedWorkspaces = (0, react.useMemo)(() => {
1259
+ return workspaces.map((workspace) => {
1260
+ const stored = sessionOrderByAccount[workspace.workspaceId];
1261
+ const sessionIds = reconciledSessionOrder(workspace.sessionIds, stored);
1262
+ return {
1263
+ ...workspace,
1264
+ sessionIds
1265
+ };
1266
+ });
1267
+ }, [sessionOrderByAccount, workspaces]);
1268
+ const orderedUngroupedSessionIds = (0, react.useMemo)(() => reconciledSessionOrder(ungroupedSessionIds, sessionOrderByAccount[""]), [sessionOrderByAccount, ungroupedSessionIds]);
1269
+ const groups = (0, react.useMemo)(() => deriveGroups(list, orderedWorkspaces, archivedSessionIds, {
1270
+ expandedGroups,
1271
+ ...sessionOrderByAccount[""] === void 0 ? {} : { ungroupedOrder: sessionOrderByAccount[""] }
1272
+ }), [
1273
+ list,
1274
+ orderedWorkspaces,
1275
+ archivedSessionIds,
1276
+ expandedGroups,
1277
+ sessionOrderByAccount
1278
+ ]);
1279
+ const now = Date.now();
1280
+ const commitSessionDrag = (activeDrag, over) => {
1281
+ if (sessionDropCommitted.current) return;
1282
+ sessionDropCommitted.current = true;
1283
+ setDrag(null);
1284
+ const group = groups.find((candidate) => candidate.key === activeDrag.accountKey);
1285
+ if (group === void 0) return;
1286
+ const targetIndex = group.sessions.findIndex((session) => session.id === over.id);
1287
+ if (targetIndex === -1) return;
1288
+ const anchor = over.half === "before" ? over.id : group.sessions[targetIndex + 1]?.id;
1289
+ if (anchor === activeDrag.sessionId) return;
1290
+ const sourceIndex = group.sessions.findIndex((session) => session.id === activeDrag.sessionId);
1291
+ const anchorIndex = anchor === void 0 ? group.sessions.length : group.sessions.findIndex((session) => session.id === anchor);
1292
+ if (sourceIndex !== -1 && (anchorIndex === sourceIndex || anchorIndex === sourceIndex + 1)) return;
1293
+ const accountSessionIds = activeDrag.accountKey === "" ? orderedUngroupedSessionIds : orderedWorkspaces.find((workspace) => workspace.workspaceId === activeDrag.accountKey)?.sessionIds;
1294
+ if (accountSessionIds === void 0) return;
1295
+ const nextOrder = accountSessionIds.filter((id) => id !== activeDrag.sessionId);
1296
+ const insertAt = anchor === void 0 ? nextOrder.length : nextOrder.indexOf(anchor);
1297
+ nextOrder.splice(insertAt === -1 ? nextOrder.length : insertAt, 0, activeDrag.sessionId);
1298
+ setSessionOrder(activeDrag.accountKey, nextOrder.map((id) => id));
1299
+ if (orderBy === "updated" || activeDrag.accountKey === "") return;
1300
+ insertSessionBefore(activeDrag.accountKey, activeDrag.sessionId, anchor).catch((reason) => {
1301
+ console.warn("session reorder rejected:", reason);
1302
+ });
1303
+ };
1304
+ const commitWorkspaceDrag = (activeDrag, over) => {
1305
+ if (workspaceDropCommitted.current) return;
1306
+ workspaceDropCommitted.current = true;
1307
+ setWorkspaceDrag(null);
1308
+ const rowIndex = workspaces.findIndex((workspace) => workspace.workspaceId === over.id);
1309
+ if (rowIndex === -1) return;
1310
+ const anchor = over.half === "before" ? over.id : workspaces[rowIndex + 1]?.workspaceId;
1311
+ if (anchor === activeDrag.workspaceId) return;
1312
+ const sourceIndex = workspaces.findIndex((workspace) => workspace.workspaceId === activeDrag.workspaceId);
1313
+ const anchorIndex = anchor === void 0 ? workspaces.length : workspaces.findIndex((workspace) => workspace.workspaceId === anchor);
1314
+ if (sourceIndex !== -1 && (anchorIndex === sourceIndex || anchorIndex === sourceIndex + 1)) return;
1315
+ insertWorkspaceBefore(activeDrag.workspaceId, anchor).catch((reason) => {
1316
+ console.warn("workspace reorder rejected:", reason);
1317
+ });
1318
+ };
1319
+ const workspaceDropAtListStart = groups[0]?.workspaceId !== void 0 && workspaceDrag?.over?.id === groups[0].workspaceId && workspaceDrag.over.half === "before";
1320
+ return (0, react_jsx_runtime.jsxs)("div", {
1321
+ className: clsx(WorkspaceBrowser_module_css_default.treeBody, WorkspaceBrowser_module_css_default.wide),
1322
+ children: [
1323
+ workspaceDropAtListStart && (0, react_jsx_runtime.jsx)("span", {
1324
+ className: WorkspaceBrowser_module_css_default.listTopDropIndicator,
1325
+ "aria-hidden": "true"
1326
+ }),
1327
+ (0, react_jsx_runtime.jsxs)("div", {
1328
+ className: clsx(WorkspaceBrowser_module_css_default.list, workspaceDropAtListStart && WorkspaceBrowser_module_css_default.listTopDropActive),
1329
+ role: "tree",
1330
+ "aria-label": t("section.sessions"),
1331
+ children: [groups.length === 0 && (0, react_jsx_runtime.jsx)("div", {
1332
+ className: WorkspaceBrowser_module_css_default.empty,
1333
+ children: t("empty.none")
1334
+ }), groups.map((group) => {
1335
+ const workspaceId = group.workspaceId;
1336
+ const workspaceMarker = workspaceId !== void 0 && workspaceDrag?.over?.id === workspaceId ? workspaceDrag.over.half : null;
1337
+ const workspaceDragProps = workspaceId === void 0 ? void 0 : {
1338
+ start: () => {
1339
+ workspaceDropCommitted.current = false;
1340
+ setWorkspaceDrag({
1341
+ workspaceId,
1342
+ over: null
1343
+ });
1344
+ },
1345
+ end: () => {
1346
+ if (workspaceDrag?.over !== null && workspaceDrag?.over !== void 0) commitWorkspaceDrag(workspaceDrag, workspaceDrag.over);
1347
+ else setWorkspaceDrag(null);
1348
+ workspaceDropCommitted.current = false;
1349
+ }
1350
+ };
1351
+ const hoverWorkspace = workspaceId === void 0 ? void 0 : (half) => {
1352
+ setWorkspaceDrag((active) => active === null ? active : {
1353
+ ...active,
1354
+ over: {
1355
+ id: workspaceId,
1356
+ half
1357
+ }
1358
+ });
1359
+ };
1360
+ const dropWorkspace = workspaceId === void 0 ? void 0 : (half) => {
1361
+ if (workspaceDrag === null) return;
1362
+ commitWorkspaceDrag(workspaceDrag, {
1363
+ id: workspaceId,
1364
+ half
1365
+ });
1366
+ };
1367
+ return (0, react_jsx_runtime.jsxs)("div", {
1368
+ className: clsx(WorkspaceBrowser_module_css_default.groupSection, workspaceMarker === "before" && WorkspaceBrowser_module_css_default.workspaceDropBefore, workspaceMarker === "after" && WorkspaceBrowser_module_css_default.workspaceDropAfter),
1369
+ onDragOver: workspaceDrag === null || hoverWorkspace === void 0 ? void 0 : (e) => {
1370
+ e.preventDefault();
1371
+ e.dataTransfer.dropEffect = "move";
1372
+ hoverWorkspace(workspaceGroupHalf(e));
1373
+ },
1374
+ onDrop: workspaceDrag === null || dropWorkspace === void 0 ? void 0 : (e) => {
1375
+ e.preventDefault();
1376
+ dropWorkspace(workspaceGroupHalf(e));
1377
+ },
1378
+ children: [
1379
+ (0, react_jsx_runtime.jsx)(ProjectRowItem, {
1380
+ group,
1381
+ home,
1382
+ t,
1383
+ onToggle: () => {
1384
+ if (group.expanded) setExpandedSessionGroups((keys) => keys.filter((key) => key !== group.key));
1385
+ setGroupExpanded(group.key, !group.expanded);
1386
+ },
1387
+ onCreate: () => {
1388
+ if (group.workspaceId !== void 0) {
1389
+ setGroupExpanded(group.key, true);
1390
+ startSession(group.workspaceId);
1391
+ }
1392
+ },
1393
+ drag: workspaceDragProps,
1394
+ actions: group.workspaceId === void 0 ? void 0 : {
1395
+ rename: () => {
1396
+ /* v8 ignore next -- narrowing guard: the actions object exists only for real-workspace groups. */
1397
+ if (group.workspaceId !== void 0) onRenameRequest(group.workspaceId, group.label);
1398
+ },
1399
+ delete: () => {
1400
+ /* v8 ignore next -- narrowing guard: the actions object exists only for real-workspace groups. */
1401
+ if (group.workspaceId !== void 0) onDeleteRequest(group.workspaceId, group.label);
1402
+ }
1403
+ }
1404
+ }),
1405
+ (expandedSessionGroups.includes(group.key) ? group.sessions : group.sessions.slice(0, COLLAPSED_SESSION_LIMIT)).map((node) => {
1406
+ const sameGroupDrag = drag !== null && drag.accountKey === group.key;
1407
+ return (0, react_jsx_runtime.jsx)(SessionNodeItem, {
1408
+ node,
1409
+ currentId: current,
1410
+ now,
1411
+ onOpen: open,
1412
+ onRename: onSessionRename,
1413
+ onFork: forkSession,
1414
+ onArchive: onSessionArchive,
1415
+ drag: {
1416
+ start: () => {
1417
+ sessionDropCommitted.current = false;
1418
+ setDrag({
1419
+ accountKey: group.key,
1420
+ sessionId: node.id,
1421
+ over: null
1422
+ });
1423
+ },
1424
+ active: sameGroupDrag,
1425
+ marker: sameGroupDrag && drag.over?.id === node.id ? drag.over.half : null,
1426
+ hover: (half) => {
1427
+ /* v8 ignore next -- narrowing guard: Rows gates hover on `active`, which is false while the drag state is null. */
1428
+ setDrag((d) => d === null ? d : {
1429
+ ...d,
1430
+ over: {
1431
+ id: node.id,
1432
+ half
1433
+ }
1434
+ });
1435
+ },
1436
+ drop: (half) => {
1437
+ /* v8 ignore next -- narrowing guard: Rows gates drop on `active`, which is false while the drag state is null. */
1438
+ if (drag === null) return;
1439
+ commitSessionDrag(drag, {
1440
+ id: node.id,
1441
+ half
1442
+ });
1443
+ },
1444
+ end: () => {
1445
+ if (drag?.over !== null && drag?.over !== void 0) commitSessionDrag(drag, drag.over);
1446
+ else setDrag(null);
1447
+ sessionDropCommitted.current = false;
1448
+ }
1449
+ },
1450
+ t
1451
+ }, node.id);
1452
+ }),
1453
+ group.sessions.length > COLLAPSED_SESSION_LIMIT && (0, react_jsx_runtime.jsx)("button", {
1454
+ type: "button",
1455
+ className: WorkspaceBrowser_module_css_default.sessionOverflowButton,
1456
+ "aria-expanded": expandedSessionGroups.includes(group.key),
1457
+ onClick: () => {
1458
+ setExpandedSessionGroups((keys) => toggled(keys, group.key));
1459
+ },
1460
+ children: expandedSessionGroups.includes(group.key) ? t("sessions.collapse") : t("sessions.expand", { n: group.sessions.length - COLLAPSED_SESSION_LIMIT })
1461
+ })
1462
+ ]
1463
+ }, group.key);
1464
+ })]
1465
+ }),
1466
+ (0, react_jsx_runtime.jsx)("span", { className: WorkspaceBrowser_module_css_default.fade })
1467
+ ]
1468
+ });
1469
+ }
1470
+ /** The flat "In one list" body: every session is one draggable top-level row. */
1471
+ function FlatList({ useSessions, open, forkSession, onSessionRename, onSessionArchive, archivedSessionIds, orderBy, sessionOrderByAccount, sessionUpdatedAtByAccount, syncSessionOrderAccount, setSessionOrder, t }) {
1472
+ const list = useSessions((s) => s);
1473
+ const baseRows = (0, react.useMemo)(() => deriveFlat(list, archivedSessionIds), [list, archivedSessionIds]);
1474
+ const sessionIds = (0, react.useMemo)(() => baseRows.map((row) => row.id), [baseRows]);
1475
+ const previousOrderBy = (0, react.useRef)(orderBy);
1476
+ (0, react.useEffect)(() => {
1477
+ if (list.phase !== "ready") return;
1478
+ const previousOrder = sessionOrderByAccount[FLAT_SESSION_ORDER_KEY];
1479
+ const previousUpdatedAt = sessionUpdatedAtByAccount["__flat_session_order__"] ?? {};
1480
+ const switchedToUpdated = previousOrderBy.current !== "updated" && orderBy === "updated";
1481
+ previousOrderBy.current = orderBy;
1482
+ const next = nextSessionOrderAccount({
1483
+ sessionIds,
1484
+ previousOrder,
1485
+ previousUpdatedAt,
1486
+ list,
1487
+ orderBy,
1488
+ sortByRecency: orderBy === "updated" && (previousOrder === void 0 || switchedToUpdated)
1489
+ });
1490
+ if (next.changed) syncSessionOrderAccount(FLAT_SESSION_ORDER_KEY, next.order.map((id) => id), next.updatedAt);
1491
+ }, [
1492
+ list,
1493
+ orderBy,
1494
+ sessionOrderByAccount,
1495
+ sessionUpdatedAtByAccount,
1496
+ sessionIds,
1497
+ syncSessionOrderAccount
1498
+ ]);
1499
+ const rows = (0, react.useMemo)(() => {
1500
+ const byId = new Map(baseRows.map((row) => [row.id, row]));
1501
+ return reconciledSessionOrder(sessionIds, sessionOrderByAccount[FLAT_SESSION_ORDER_KEY]).flatMap((id) => {
1502
+ const row = byId.get(id);
1503
+ return row === void 0 ? [] : [row];
1504
+ });
1505
+ }, [
1506
+ baseRows,
1507
+ sessionOrderByAccount,
1508
+ sessionIds
1509
+ ]);
1510
+ const [drag, setDrag] = (0, react.useState)(null);
1511
+ const dropCommitted = (0, react.useRef)(false);
1512
+ useNativeDragAcceptance(drag !== null);
1513
+ const commitDrag = (activeDrag, over) => {
1514
+ if (dropCommitted.current) return;
1515
+ dropCommitted.current = true;
1516
+ setDrag(null);
1517
+ const targetIndex = rows.findIndex((row) => row.id === over.id);
1518
+ if (targetIndex === -1) return;
1519
+ const anchor = over.half === "before" ? over.id : rows[targetIndex + 1]?.id;
1520
+ if (anchor === activeDrag.sessionId) return;
1521
+ const sourceIndex = rows.findIndex((row) => row.id === activeDrag.sessionId);
1522
+ const anchorIndex = anchor === void 0 ? rows.length : rows.findIndex((row) => row.id === anchor);
1523
+ if (sourceIndex !== -1 && (anchorIndex === sourceIndex || anchorIndex === sourceIndex + 1)) return;
1524
+ const nextOrder = rows.map((row) => row.id).filter((id) => id !== activeDrag.sessionId);
1525
+ const insertAt = anchor === void 0 ? nextOrder.length : nextOrder.indexOf(anchor);
1526
+ nextOrder.splice(insertAt === -1 ? nextOrder.length : insertAt, 0, activeDrag.sessionId);
1527
+ setSessionOrder(FLAT_SESSION_ORDER_KEY, nextOrder.map((id) => id));
1528
+ };
1529
+ const now = Date.now();
1530
+ return (0, react_jsx_runtime.jsxs)("div", {
1531
+ className: clsx(WorkspaceBrowser_module_css_default.treeBody, WorkspaceBrowser_module_css_default.wide),
1532
+ children: [(0, react_jsx_runtime.jsxs)("div", {
1533
+ className: clsx(WorkspaceBrowser_module_css_default.list, WorkspaceBrowser_module_css_default.flatList),
1534
+ role: "tree",
1535
+ "aria-label": t("section.sessions"),
1536
+ children: [rows.length === 0 && (0, react_jsx_runtime.jsx)("div", {
1537
+ className: WorkspaceBrowser_module_css_default.empty,
1538
+ children: t("empty.none")
1539
+ }), rows.map((node) => {
1540
+ const active = drag !== null;
1541
+ return (0, react_jsx_runtime.jsx)(SessionNodeItem, {
1542
+ node,
1543
+ currentId: list.current,
1544
+ now,
1545
+ onOpen: open,
1546
+ onRename: onSessionRename,
1547
+ onFork: forkSession,
1548
+ onArchive: onSessionArchive,
1549
+ flat: true,
1550
+ drag: {
1551
+ start: () => {
1552
+ dropCommitted.current = false;
1553
+ setDrag({
1554
+ accountKey: FLAT_SESSION_ORDER_KEY,
1555
+ sessionId: node.id,
1556
+ over: null
1557
+ });
1558
+ },
1559
+ active,
1560
+ marker: active && drag.over?.id === node.id ? drag.over.half : null,
1561
+ hover: (half) => {
1562
+ setDrag((current) => current === null ? current : {
1563
+ ...current,
1564
+ over: {
1565
+ id: node.id,
1566
+ half
1567
+ }
1568
+ });
1569
+ },
1570
+ drop: (half) => {
1571
+ if (drag !== null) commitDrag(drag, {
1572
+ id: node.id,
1573
+ half
1574
+ });
1575
+ },
1576
+ end: () => {
1577
+ if (drag?.over !== null && drag?.over !== void 0) commitDrag(drag, drag.over);
1578
+ else setDrag(null);
1579
+ dropCommitted.current = false;
1580
+ }
1581
+ },
1582
+ t
1583
+ }, node.id);
1584
+ })]
1585
+ }), (0, react_jsx_runtime.jsx)("span", { className: WorkspaceBrowser_module_css_default.fade })]
1586
+ });
1587
+ }
1588
+ /** Flat search body: local metadata matches plus the current Host result page. */
1589
+ function SearchResults({ useSessions, open, workspaces, archivedSessionIds, query, remote, resultLimit, t }) {
1590
+ const list = useSessions((s) => s);
1591
+ const currentRemote = remote.query === query ? remote : {
1592
+ query,
1593
+ status: "loading",
1594
+ items: [],
1595
+ hasMore: false
1596
+ };
1597
+ const results = (0, react.useMemo)(() => deriveSearchResults(list, workspaces, query, archivedSessionIds, currentRemote, resultLimit), [
1598
+ list,
1599
+ workspaces,
1600
+ query,
1601
+ archivedSessionIds,
1602
+ currentRemote,
1603
+ resultLimit
1604
+ ]);
1605
+ const pending = currentRemote.status === "loading";
1606
+ const failed = currentRemote.status === "error";
1607
+ return (0, react_jsx_runtime.jsxs)("div", {
1608
+ className: clsx(WorkspaceBrowser_module_css_default.treeBody, WorkspaceBrowser_module_css_default.wide),
1609
+ children: [(0, react_jsx_runtime.jsxs)("div", {
1610
+ className: WorkspaceBrowser_module_css_default.list,
1611
+ children: [
1612
+ (0, react_jsx_runtime.jsx)("div", {
1613
+ className: WorkspaceBrowser_module_css_default.searchTree,
1614
+ role: "tree",
1615
+ "aria-label": t("search.results.aria"),
1616
+ children: results.items.map((result) => (0, react_jsx_runtime.jsx)(SearchResultItem, {
1617
+ result,
1618
+ currentId: list.current,
1619
+ onOpen: open,
1620
+ t
1621
+ }, result.id))
1622
+ }),
1623
+ pending && (0, react_jsx_runtime.jsx)("div", {
1624
+ className: WorkspaceBrowser_module_css_default.searchStatus,
1625
+ role: "status",
1626
+ children: t("search.pending")
1627
+ }),
1628
+ failed && (0, react_jsx_runtime.jsx)("div", {
1629
+ className: WorkspaceBrowser_module_css_default.searchWarning,
1630
+ role: "status",
1631
+ children: t("search.unavailable")
1632
+ }),
1633
+ !pending && results.items.length === 0 && (0, react_jsx_runtime.jsx)("div", {
1634
+ className: WorkspaceBrowser_module_css_default.empty,
1635
+ children: t("search.noMatches")
1636
+ }),
1637
+ results.hasMore && (0, react_jsx_runtime.jsx)("div", {
1638
+ className: WorkspaceBrowser_module_css_default.searchStatus,
1639
+ children: t("search.hasMore", { n: resultLimit })
1640
+ })
1641
+ ]
1642
+ }), (0, react_jsx_runtime.jsx)("span", { className: WorkspaceBrowser_module_css_default.fade })]
1643
+ });
1644
+ }
1645
+ /**
1646
+ * Render the browsing region.
1647
+ * @param props - composed slot props (shell owner share + store + injected actions).
1648
+ * @returns the region element tree.
1649
+ */
1650
+ function WorkspaceBrowser({ wide, expandSidebar, useSessions, useWorkspaces, useStore, actions, startSession, open, renameSession, forkSession, renameWorkspace, deleteWorkspace, insertWorkspaceBefore, archiveSession, insertSessionBefore, createWorkspace, searchSessions, searchResultLimit, useDirectoryFlow, useHostDescription, renderSlot, t }) {
1651
+ const home = useHostDescription((description) => description?.home);
1652
+ const workspaces = useWorkspaces((state) => state.items);
1653
+ const workspacePhase = useWorkspaces((state) => state.phase);
1654
+ const archivedSessionIds = useWorkspaces((state) => state.archivedSessionIds);
1655
+ const directoryFlowAvailable = useDirectoryFlow((occupied) => occupied);
1656
+ const groupBy = useStore((s) => s.groupBy);
1657
+ const orderBy = useStore((s) => s.orderBy);
1658
+ const groupExpansion = useStore((s) => s.groupExpansion);
1659
+ const sessionOrderByAccount = useStore((s) => s.sessionOrderByAccount);
1660
+ const sessionUpdatedAtByAccount = useStore((s) => s.sessionUpdatedAtByAccount);
1661
+ const currentBlankSessionId = useSessions((state) => {
1662
+ const current = state.current;
1663
+ return current !== void 0 && state.byId[current]?.blank === true ? current : void 0;
1664
+ });
1665
+ const currentBlankAccount = currentBlankSessionId === void 0 ? void 0 : workspaces.find((workspace) => workspace.sessionIds.includes(currentBlankSessionId))?.workspaceId ?? "";
1666
+ const promotedBlank = (0, react.useRef)(void 0);
1667
+ (0, react.useEffect)(() => {
1668
+ if (currentBlankSessionId === void 0 || currentBlankAccount === void 0) {
1669
+ promotedBlank.current = void 0;
1670
+ return;
1671
+ }
1672
+ if (promotedBlank.current?.sessionId === currentBlankSessionId && promotedBlank.current.accountKey === currentBlankAccount) return;
1673
+ promotedBlank.current = {
1674
+ sessionId: currentBlankSessionId,
1675
+ accountKey: currentBlankAccount
1676
+ };
1677
+ for (const accountKey of new Set([currentBlankAccount, FLAT_SESSION_ORDER_KEY])) {
1678
+ const previous = sessionOrderByAccount[accountKey] ?? [];
1679
+ actions.setSessionOrder(accountKey, [currentBlankSessionId, ...previous.filter((id) => id !== currentBlankSessionId)]);
1680
+ }
1681
+ }, [
1682
+ actions.setSessionOrder,
1683
+ currentBlankAccount,
1684
+ currentBlankSessionId,
1685
+ sessionOrderByAccount
1686
+ ]);
1687
+ (0, react.useEffect)(() => {
1688
+ if (workspacePhase !== "ready") return;
1689
+ actions.retainAccountKeys([
1690
+ "",
1691
+ FLAT_SESSION_ORDER_KEY,
1692
+ ...workspaces.map((workspace) => workspace.workspaceId)
1693
+ ]);
1694
+ }, [
1695
+ actions.retainAccountKeys,
1696
+ workspacePhase,
1697
+ workspaces
1698
+ ]);
1699
+ const [query, setQuery] = (0, react.useState)("");
1700
+ const [searchExpanded, setSearchExpanded] = (0, react.useState)(false);
1701
+ const normalizedQuery = sanitizeSearchQuery(query).trim();
1702
+ const [remoteSearch, setRemoteSearch] = (0, react.useState)({
1703
+ query: "",
1704
+ status: "idle",
1705
+ items: [],
1706
+ hasMore: false
1707
+ });
1708
+ const searchRoot = (0, react.useRef)(null);
1709
+ const searchInput = (0, react.useRef)(null);
1710
+ const [wsPickerOpen, setWsPickerOpen] = (0, react.useState)(false);
1711
+ const wsPlusRef = (0, react.useRef)(null);
1712
+ const composingRef = (0, react.useRef)(false);
1713
+ const [searchOnExpand, setSearchOnExpand] = (0, react.useState)(false);
1714
+ (0, react.useEffect)(() => {
1715
+ if (wide && searchOnExpand) {
1716
+ const timer = window.setTimeout(() => {
1717
+ searchInput.current?.focus({ preventScroll: true });
1718
+ setSearchOnExpand(false);
1719
+ }, EXPAND_SLIDE_MS);
1720
+ return () => {
1721
+ window.clearTimeout(timer);
1722
+ };
1723
+ }
1724
+ }, [wide, searchOnExpand]);
1725
+ (0, react.useEffect)(() => {
1726
+ if (!wide || !searchExpanded || searchOnExpand) return;
1727
+ searchInput.current?.focus({ preventScroll: true });
1728
+ }, [
1729
+ wide,
1730
+ searchExpanded,
1731
+ searchOnExpand
1732
+ ]);
1733
+ (0, react.useEffect)(() => {
1734
+ if (!wide || !searchExpanded || searchOnExpand) return;
1735
+ const onClick = (event) => {
1736
+ if (!(event.target instanceof Node) || searchRoot.current?.contains(event.target) === true) return;
1737
+ searchInput.current?.blur();
1738
+ if (normalizedQuery !== "") return;
1739
+ setSearchExpanded(false);
1740
+ };
1741
+ document.addEventListener("click", onClick);
1742
+ return () => {
1743
+ document.removeEventListener("click", onClick);
1744
+ };
1745
+ }, [
1746
+ normalizedQuery,
1747
+ wide,
1748
+ searchExpanded,
1749
+ searchOnExpand
1750
+ ]);
1751
+ (0, react.useEffect)(() => {
1752
+ if (normalizedQuery === "") {
1753
+ setRemoteSearch({
1754
+ query: "",
1755
+ status: "idle",
1756
+ items: [],
1757
+ hasMore: false
1758
+ });
1759
+ return;
1760
+ }
1761
+ const controller = new AbortController();
1762
+ setRemoteSearch({
1763
+ query: normalizedQuery,
1764
+ status: "loading",
1765
+ items: [],
1766
+ hasMore: false
1767
+ });
1768
+ const timer = window.setTimeout(() => {
1769
+ searchSessions(normalizedQuery, controller.signal).then((result) => {
1770
+ if (controller.signal.aborted) return;
1771
+ setRemoteSearch({
1772
+ query: normalizedQuery,
1773
+ status: "ready",
1774
+ items: result.items,
1775
+ hasMore: result.hasMore
1776
+ });
1777
+ }).catch(() => {
1778
+ if (controller.signal.aborted) return;
1779
+ setRemoteSearch({
1780
+ query: normalizedQuery,
1781
+ status: "error",
1782
+ items: [],
1783
+ hasMore: false
1784
+ });
1785
+ });
1786
+ }, SEARCH_DEBOUNCE_MS);
1787
+ return () => {
1788
+ window.clearTimeout(timer);
1789
+ controller.abort();
1790
+ };
1791
+ }, [normalizedQuery, searchSessions]);
1792
+ const [renameTarget, setRenameTarget] = (0, react.useState)(null);
1793
+ const [renameDraft, setRenameDraft] = (0, react.useState)("");
1794
+ const [renaming, setRenaming] = (0, react.useState)(false);
1795
+ const [renameError, setRenameError] = (0, react.useState)(null);
1796
+ const renameTrimmed = renameDraft.trim();
1797
+ const renameDuplicate = renameTarget !== null && renameTrimmed !== "" && renameTrimmed !== renameTarget.currentTitle && workspaces.some((w) => w.title === renameTrimmed);
1798
+ const renameBlocked = renaming || renameTrimmed === "" || renameTarget === null || renameTrimmed === renameTarget.currentTitle || renameDuplicate;
1799
+ const closeRename = () => {
1800
+ if (renaming) return;
1801
+ setRenameTarget(null);
1802
+ setRenameError(null);
1803
+ };
1804
+ const confirmRename = () => {
1805
+ if (renameBlocked) return;
1806
+ setRenaming(true);
1807
+ setRenameError(null);
1808
+ renameWorkspace(renameTarget.workspaceId, renameTrimmed).then(() => {
1809
+ setRenaming(false);
1810
+ setRenameTarget(null);
1811
+ }).catch((reason) => {
1812
+ setRenaming(false);
1813
+ setRenameError(reason instanceof Error ? reason.message : String(reason));
1814
+ });
1815
+ };
1816
+ const [sessionRenameTarget, setSessionRenameTarget] = (0, react.useState)(null);
1817
+ const [sessionRenameDraft, setSessionRenameDraft] = (0, react.useState)("");
1818
+ const [sessionRenaming, setSessionRenaming] = (0, react.useState)(false);
1819
+ const [sessionRenameError, setSessionRenameError] = (0, react.useState)(null);
1820
+ const sessionRenameTrimmed = sessionRenameDraft.trim();
1821
+ const sessionRenameBlocked = sessionRenaming || sessionRenameTrimmed === "" || sessionRenameTarget === null;
1822
+ const closeSessionRename = () => {
1823
+ if (sessionRenaming) return;
1824
+ setSessionRenameTarget(null);
1825
+ setSessionRenameError(null);
1826
+ };
1827
+ const confirmSessionRename = () => {
1828
+ if (sessionRenameBlocked) return;
1829
+ setSessionRenaming(true);
1830
+ setSessionRenameError(null);
1831
+ renameSession(sessionRenameTarget.sessionId, sessionRenameTrimmed).then(() => {
1832
+ setSessionRenaming(false);
1833
+ setSessionRenameTarget(null);
1834
+ }).catch((reason) => {
1835
+ setSessionRenaming(false);
1836
+ setSessionRenameError(reason instanceof Error ? reason.message : String(reason));
1837
+ });
1838
+ };
1839
+ const onSessionRename = (sessionId, currentTitle) => {
1840
+ setSessionRenameTarget({
1841
+ sessionId,
1842
+ currentTitle
1843
+ });
1844
+ setSessionRenameDraft(currentTitle);
1845
+ setSessionRenameError(null);
1846
+ };
1847
+ const onSessionArchive = (sessionId) => {
1848
+ archiveSession(sessionId).catch((reason) => {
1849
+ console.warn("session archive rejected:", reason);
1850
+ });
1851
+ };
1852
+ const [deleteTarget, setDeleteTarget] = (0, react.useState)(null);
1853
+ const [deleting, setDeleting] = (0, react.useState)(false);
1854
+ const [deleteCommittedId, setDeleteCommittedId] = (0, react.useState)(null);
1855
+ const [deleteError, setDeleteError] = (0, react.useState)(null);
1856
+ (0, react.useEffect)(() => {
1857
+ if (deleteCommittedId === null || workspaces.some((workspace) => workspace.workspaceId === deleteCommittedId)) return;
1858
+ setDeleting(false);
1859
+ setDeleteCommittedId(null);
1860
+ setDeleteTarget(null);
1861
+ }, [deleteCommittedId, workspaces]);
1862
+ const closeDelete = () => {
1863
+ if (deleting) return;
1864
+ setDeleteTarget(null);
1865
+ setDeleteError(null);
1866
+ };
1867
+ const confirmDelete = () => {
1868
+ /* v8 ignore next -- the Modal is absent without a target and its button is disabled while deleting. */
1869
+ if (deleting || deleteTarget === null) return;
1870
+ setDeleting(true);
1871
+ setDeleteCommittedId(null);
1872
+ setDeleteError(null);
1873
+ deleteWorkspace(deleteTarget.workspaceId).then(() => {
1874
+ setDeleteCommittedId(deleteTarget.workspaceId);
1875
+ }).catch((reason) => {
1876
+ setDeleting(false);
1877
+ setDeleteError(reason instanceof Error ? reason.message : String(reason));
1878
+ });
1879
+ };
1880
+ return (0, react_jsx_runtime.jsxs)("div", {
1881
+ className: clsx(WorkspaceBrowser_module_css_default.root, !wide && WorkspaceBrowser_module_css_default.rail),
1882
+ children: [
1883
+ (0, react_jsx_runtime.jsxs)("div", {
1884
+ className: WorkspaceBrowser_module_css_default.sectionHeader,
1885
+ children: [
1886
+ wide && (0, react_jsx_runtime.jsx)("span", {
1887
+ className: clsx(WorkspaceBrowser_module_css_default.sectionLabel, WorkspaceBrowser_module_css_default.wide, searchExpanded && WorkspaceBrowser_module_css_default.sectionLabelHidden),
1888
+ children: groupBy === "flat" ? t("section.sessions") : t("section.workspaces")
1889
+ }),
1890
+ wide && (0, react_jsx_runtime.jsx)("div", {
1891
+ className: clsx(WorkspaceBrowser_module_css_default.searchSlot, searchExpanded && WorkspaceBrowser_module_css_default.searchSlotExpanded),
1892
+ children: (0, react_jsx_runtime.jsxs)("div", {
1893
+ ref: searchRoot,
1894
+ className: clsx(WorkspaceBrowser_module_css_default.search, searchExpanded && WorkspaceBrowser_module_css_default.searchExpanded),
1895
+ onClick: () => {
1896
+ setWsPickerOpen(false);
1897
+ setSearchExpanded(true);
1898
+ searchInput.current?.focus();
1899
+ },
1900
+ children: [
1901
+ (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
1902
+ label: t("search"),
1903
+ side: "bottom",
1904
+ delayMs: 500,
1905
+ disabled: searchExpanded,
1906
+ children: (0, react_jsx_runtime.jsx)("button", {
1907
+ type: "button",
1908
+ className: WorkspaceBrowser_module_css_default.searchButton,
1909
+ "aria-label": t("search.sessions.aria"),
1910
+ "aria-expanded": searchExpanded,
1911
+ onClick: () => {
1912
+ setWsPickerOpen(false);
1913
+ setSearchExpanded(true);
1914
+ },
1915
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconSearchOutline16, { size: searchExpanded ? 11 : 14 })
1916
+ })
1917
+ }),
1918
+ (0, react_jsx_runtime.jsx)("input", {
1919
+ ref: searchInput,
1920
+ className: WorkspaceBrowser_module_css_default.searchInput,
1921
+ type: "text",
1922
+ placeholder: t("search.placeholder"),
1923
+ maxLength: SEARCH_QUERY_MAX_CODE_UNITS,
1924
+ value: query,
1925
+ tabIndex: searchExpanded ? 0 : -1,
1926
+ onChange: (e) => {
1927
+ setQuery(sanitizeSearchQuery(e.target.value));
1928
+ },
1929
+ onKeyDown: (e) => {
1930
+ if (e.key !== "Escape") return;
1931
+ setQuery("");
1932
+ setSearchExpanded(false);
1933
+ }
1934
+ }),
1935
+ searchExpanded && (0, react_jsx_runtime.jsx)("button", {
1936
+ type: "button",
1937
+ className: WorkspaceBrowser_module_css_default.clearButton,
1938
+ "aria-label": t("search.clear"),
1939
+ onClick: (e) => {
1940
+ e.stopPropagation();
1941
+ setQuery("");
1942
+ setSearchExpanded(false);
1943
+ },
1944
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconCloseFill14, {})
1945
+ })
1946
+ ]
1947
+ })
1948
+ }),
1949
+ (0, react_jsx_runtime.jsxs)("div", {
1950
+ className: clsx(WorkspaceBrowser_module_css_default.headerActions, wide && searchExpanded && WorkspaceBrowser_module_css_default.headerActionsHidden),
1951
+ children: [wide && (0, react_jsx_runtime.jsx)(ViewOptionsMenu, {
1952
+ groupBy,
1953
+ orderBy,
1954
+ onGroupPick: (mode) => {
1955
+ actions.setGroupBy(mode);
1956
+ },
1957
+ onOrderPick: (mode) => {
1958
+ actions.setOrderBy(mode);
1959
+ },
1960
+ t
1961
+ }), directoryFlowAvailable && (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
1962
+ label: t("workspace.add"),
1963
+ side: "bottom",
1964
+ delayMs: 500,
1965
+ children: (0, react_jsx_runtime.jsx)("button", {
1966
+ ref: wsPlusRef,
1967
+ type: "button",
1968
+ className: WorkspaceBrowser_module_css_default.iconButton,
1969
+ "aria-label": t("workspace.add"),
1970
+ onClick: () => {
1971
+ setWsPickerOpen((v) => !v);
1972
+ },
1973
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconProjectAddOutline16, { size: wide ? 16 : 18 })
1974
+ })
1975
+ })]
1976
+ }),
1977
+ (0, react_jsx_runtime.jsx)(WorkspacePickFlow, {
1978
+ t,
1979
+ open: wsPickerOpen,
1980
+ anchorRef: wsPlusRef,
1981
+ useWorkspaces,
1982
+ createWorkspace,
1983
+ useDirectoryFlow,
1984
+ renderDirectoryFlow: (owner) => renderSlot("sidebar.workspaces.directoryFlow", owner),
1985
+ addOnly: true,
1986
+ side: "right",
1987
+ onPick: (workspaceId) => {
1988
+ setWsPickerOpen(false);
1989
+ startSession(workspaceId);
1990
+ },
1991
+ onClose: () => {
1992
+ setWsPickerOpen(false);
1993
+ }
1994
+ })
1995
+ ]
1996
+ }),
1997
+ !wide && (0, react_jsx_runtime.jsx)("div", {
1998
+ className: WorkspaceBrowser_module_css_default.search,
1999
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Tooltip, {
2000
+ label: t("search"),
2001
+ children: (0, react_jsx_runtime.jsx)("button", {
2002
+ type: "button",
2003
+ className: WorkspaceBrowser_module_css_default.searchButton,
2004
+ "aria-label": t("search.sessions.aria"),
2005
+ onClick: () => {
2006
+ setSearchExpanded(true);
2007
+ setSearchOnExpand(true);
2008
+ expandSidebar();
2009
+ },
2010
+ children: (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.IconSearchOutline16, { size: 18 })
2011
+ })
2012
+ })
2013
+ }),
2014
+ (0, react_jsx_runtime.jsx)("div", {
2015
+ className: WorkspaceBrowser_module_css_default.listArea,
2016
+ children: wide && (normalizedQuery !== "" ? (0, react_jsx_runtime.jsx)(SearchResults, {
2017
+ useSessions,
2018
+ open,
2019
+ workspaces,
2020
+ archivedSessionIds,
2021
+ query: normalizedQuery,
2022
+ remote: remoteSearch,
2023
+ resultLimit: searchResultLimit,
2024
+ t
2025
+ }) : groupBy === "flat" ? (0, react_jsx_runtime.jsx)(FlatList, {
2026
+ useSessions,
2027
+ open,
2028
+ forkSession,
2029
+ onSessionRename,
2030
+ onSessionArchive,
2031
+ archivedSessionIds,
2032
+ orderBy,
2033
+ sessionOrderByAccount,
2034
+ sessionUpdatedAtByAccount,
2035
+ syncSessionOrderAccount: actions.syncSessionOrderAccount,
2036
+ setSessionOrder: actions.setSessionOrder,
2037
+ t
2038
+ }) : (0, react_jsx_runtime.jsx)(SessionTree, {
2039
+ useSessions,
2040
+ onSessionRename,
2041
+ onSessionArchive,
2042
+ forkSession,
2043
+ workspaces,
2044
+ groupExpansion,
2045
+ setGroupExpanded: actions.setGroupExpanded,
2046
+ sessionOrderByAccount,
2047
+ sessionUpdatedAtByAccount,
2048
+ syncSessionOrderAccount: actions.syncSessionOrderAccount,
2049
+ setSessionOrder: actions.setSessionOrder,
2050
+ archivedSessionIds,
2051
+ startSession,
2052
+ open,
2053
+ insertWorkspaceBefore,
2054
+ insertSessionBefore,
2055
+ orderBy,
2056
+ home,
2057
+ t,
2058
+ onRenameRequest: (workspaceId, currentTitle) => {
2059
+ setRenameTarget({
2060
+ workspaceId,
2061
+ currentTitle
2062
+ });
2063
+ setRenameDraft(currentTitle);
2064
+ setRenameError(null);
2065
+ },
2066
+ onDeleteRequest: (workspaceId, title) => {
2067
+ setDeleteTarget({
2068
+ workspaceId,
2069
+ title
2070
+ });
2071
+ setDeleteError(null);
2072
+ }
2073
+ }))
2074
+ }),
2075
+ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, {
2076
+ open: renameTarget !== null,
2077
+ onClose: closeRename,
2078
+ closeLabel: t("close"),
2079
+ title: t("rename.workspace.title"),
2080
+ footer: (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
2081
+ variant: "outline",
2082
+ disabled: renaming,
2083
+ onClick: closeRename,
2084
+ children: t("cancel")
2085
+ }), (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
2086
+ variant: "primary",
2087
+ disabled: renameBlocked,
2088
+ onClick: confirmRename,
2089
+ children: t("rename")
2090
+ })] }),
2091
+ children: [
2092
+ (0, react_jsx_runtime.jsx)("input", {
2093
+ className: WorkspaceBrowser_module_css_default.renameInput,
2094
+ value: renameDraft,
2095
+ "aria-label": t("field.workspaceName"),
2096
+ autoFocus: true,
2097
+ disabled: renaming,
2098
+ onFocus: (e) => {
2099
+ e.target.select();
2100
+ },
2101
+ onChange: (e) => {
2102
+ setRenameDraft(e.target.value);
2103
+ setRenameError(null);
2104
+ },
2105
+ onCompositionStart: () => {
2106
+ composingRef.current = true;
2107
+ },
2108
+ onCompositionEnd: () => {
2109
+ composingRef.current = false;
2110
+ },
2111
+ onKeyDown: (e) => {
2112
+ if (e.key === "Enter" && !composingRef.current) {
2113
+ e.preventDefault();
2114
+ confirmRename();
2115
+ }
2116
+ }
2117
+ }),
2118
+ renameDuplicate && (0, react_jsx_runtime.jsx)("div", {
2119
+ className: WorkspaceBrowser_module_css_default.renameError,
2120
+ role: "alert",
2121
+ children: t("conflict.named", { name: renameTrimmed })
2122
+ }),
2123
+ renameError !== null && (0, react_jsx_runtime.jsx)("div", {
2124
+ className: WorkspaceBrowser_module_css_default.renameError,
2125
+ role: "alert",
2126
+ children: renameError
2127
+ })
2128
+ ]
2129
+ }),
2130
+ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, {
2131
+ open: sessionRenameTarget !== null,
2132
+ onClose: closeSessionRename,
2133
+ closeLabel: t("close"),
2134
+ title: t("rename.session.title"),
2135
+ footer: (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
2136
+ variant: "outline",
2137
+ disabled: sessionRenaming,
2138
+ onClick: closeSessionRename,
2139
+ children: t("cancel")
2140
+ }), (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
2141
+ variant: "primary",
2142
+ disabled: sessionRenameBlocked,
2143
+ onClick: confirmSessionRename,
2144
+ children: t("rename")
2145
+ })] }),
2146
+ children: [(0, react_jsx_runtime.jsx)("input", {
2147
+ className: WorkspaceBrowser_module_css_default.renameInput,
2148
+ value: sessionRenameDraft,
2149
+ "aria-label": t("field.sessionName"),
2150
+ autoFocus: true,
2151
+ disabled: sessionRenaming,
2152
+ onFocus: (e) => {
2153
+ e.target.select();
2154
+ },
2155
+ onChange: (e) => {
2156
+ setSessionRenameDraft(e.target.value);
2157
+ setSessionRenameError(null);
2158
+ },
2159
+ onCompositionStart: () => {
2160
+ composingRef.current = true;
2161
+ },
2162
+ onCompositionEnd: () => {
2163
+ composingRef.current = false;
2164
+ },
2165
+ onKeyDown: (e) => {
2166
+ if (e.key === "Enter" && !composingRef.current) {
2167
+ e.preventDefault();
2168
+ confirmSessionRename();
2169
+ }
2170
+ }
2171
+ }), sessionRenameError !== null && (0, react_jsx_runtime.jsx)("div", {
2172
+ className: WorkspaceBrowser_module_css_default.renameError,
2173
+ role: "alert",
2174
+ children: sessionRenameError
2175
+ })]
2176
+ }),
2177
+ (0, react_jsx_runtime.jsxs)(_deepseek_ai_dsh_client_ui_primitives.Modal, {
2178
+ open: deleteTarget !== null,
2179
+ onClose: closeDelete,
2180
+ closeLabel: t("close"),
2181
+ title: t("delete.workspace"),
2182
+ ...deleteTarget === null ? {} : { description: t("delete.desc", { name: deleteTarget.title }) },
2183
+ footer: (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [(0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
2184
+ variant: "outline",
2185
+ disabled: deleting,
2186
+ onClick: closeDelete,
2187
+ children: t("cancel")
2188
+ }), (0, react_jsx_runtime.jsx)(_deepseek_ai_dsh_client_ui_primitives.Button, {
2189
+ variant: "outline",
2190
+ className: WorkspaceBrowser_module_css_default.deleteAction,
2191
+ disabled: deleting,
2192
+ onClick: confirmDelete,
2193
+ children: t("delete.workspace")
2194
+ })] }),
2195
+ children: [deleting && (0, react_jsx_runtime.jsx)("div", {
2196
+ className: WorkspaceBrowser_module_css_default.deleteStatus,
2197
+ role: "status",
2198
+ children: t("delete.pending")
2199
+ }), deleteError !== null && (0, react_jsx_runtime.jsx)("div", {
2200
+ className: WorkspaceBrowser_module_css_default.renameError,
2201
+ role: "alert",
2202
+ children: deleteError
2203
+ })]
2204
+ })
2205
+ ]
2206
+ });
2207
+ }
2208
+ //#endregion
2209
+ //#region lib/types/client/locales.js
2210
+ /**
2211
+ * `workspace` namespace dictionaries: the browsing region (section header,
2212
+ * search, tree rows, dialogs) and the pick/add flow. Runtime failure
2213
+ * messages (wire error strings) pass through untranslated by policy.
2214
+ */
2215
+ /** Simplified Chinese dictionary (the key-set source of truth). */
2216
+ const zh = {
2217
+ "group.ungrouped": "未分组",
2218
+ "session.new": "新会话",
2219
+ "section.workspaces": "工作区",
2220
+ "section.sessions": "会话",
2221
+ "viewOptions.label": "视图选项",
2222
+ "groupBy.label": "分组方式",
2223
+ "groupBy.workspace": "按工作区",
2224
+ "groupBy.flat": "单列表",
2225
+ "orderBy.label": "排序方式",
2226
+ "orderBy.manual": "手动排序",
2227
+ "orderBy.updated": "最近更新",
2228
+ "sessions.expand": "展开其余 {n} 个会话",
2229
+ "sessions.collapse": "收起",
2230
+ "empty.none": "暂无会话",
2231
+ "empty.noMatches": "无匹配结果",
2232
+ "workspace.add": "添加工作区",
2233
+ "search.sessions.aria": "搜索会话",
2234
+ "search.placeholder": "搜索会话…",
2235
+ "search.clear": "清除搜索",
2236
+ "search.results.aria": "搜索结果",
2237
+ "search.pending": "正在搜索会话历史…",
2238
+ "search.unavailable": "内容搜索暂不可用,仅显示名称匹配。",
2239
+ "search.noMatches": "无匹配会话",
2240
+ "search.hasMore": "仅显示前 {n} 条结果,请缩小搜索范围。",
2241
+ "menu.addWorkspace": "添加工作区…",
2242
+ "picker.loading": "正在加载工作区…",
2243
+ "conflict.named": "已存在名为“{name}”的工作区。",
2244
+ "folderError.title": "无法打开文件夹",
2245
+ "folderError.retry": "重新选择",
2246
+ "rename": "重命名",
2247
+ "rename.workspace.title": "重命名工作区",
2248
+ "rename.session.title": "重命名会话",
2249
+ "field.workspaceName": "工作区名称",
2250
+ "field.sessionName": "会话名称",
2251
+ "delete.workspace": "删除工作区",
2252
+ "delete.desc": "将把“{name}”从工作区列表中移除。文件夹与会话记录会保留,其会话将显示在“未分组”下。",
2253
+ "delete.pending": "正在删除工作区…",
2254
+ "menu.fork": "分叉会话",
2255
+ "menu.archiveSession": "归档会话",
2256
+ "sessions.count.one": "{n} 个会话",
2257
+ "sessions.count.other": "{n} 个会话",
2258
+ "actions.workspace.aria": "工作区“{name}”的操作",
2259
+ "actions.session.aria": "会话“{name}”的操作",
2260
+ "actions.newSession.aria": "在“{name}”中新建会话",
2261
+ "status.running": "进行中",
2262
+ "status.subagentsRunning.one": "{n} 个子代理运行中",
2263
+ "status.subagentsRunning.other": "{n} 个子代理运行中",
2264
+ "status.idle": "空闲",
2265
+ "status.waitingApproval": "等待审批",
2266
+ "status.planReview": "计划待审",
2267
+ "status.waitingAnswer": "等待回答",
2268
+ "status.completed": "已完成",
2269
+ "hover.created": "创建于 {time}",
2270
+ "hover.copied": "已复制",
2271
+ "date.ymd": "{y}年{m}月{d}日",
2272
+ "time.now": "刚刚",
2273
+ "time.minutes": "{n}分钟",
2274
+ "time.hours": "{n}小时",
2275
+ "time.days": "{n}天",
2276
+ "time.months": "{n}个月",
2277
+ "time.years": "{n}年",
2278
+ "time.ago": "{t}前"
2279
+ };
2280
+ /** English dictionary, checked complete against the zh key set. */
2281
+ const en = {
2282
+ "group.ungrouped": "Ungrouped",
2283
+ "session.new": "New Session",
2284
+ "section.workspaces": "Workspaces",
2285
+ "section.sessions": "Sessions",
2286
+ "viewOptions.label": "View options",
2287
+ "groupBy.label": "Group by",
2288
+ "groupBy.workspace": "WorkSpace",
2289
+ "groupBy.flat": "In one list",
2290
+ "orderBy.label": "Order by",
2291
+ "orderBy.manual": "Manual",
2292
+ "orderBy.updated": "Last updated",
2293
+ "sessions.expand": "Show {n} more sessions",
2294
+ "sessions.collapse": "Show less",
2295
+ "empty.none": "No sessions yet",
2296
+ "empty.noMatches": "No matches",
2297
+ "workspace.add": "Add workspace",
2298
+ "search.sessions.aria": "Search sessions",
2299
+ "search.placeholder": "Search sessions...",
2300
+ "search.clear": "Clear search",
2301
+ "search.results.aria": "Search results",
2302
+ "search.pending": "Searching session history…",
2303
+ "search.unavailable": "Content search is temporarily unavailable. Showing name matches.",
2304
+ "search.noMatches": "No matching sessions",
2305
+ "search.hasMore": "Showing the first {n} results. Narrow your search.",
2306
+ "menu.addWorkspace": "Add workspace…",
2307
+ "picker.loading": "Loading workspaces…",
2308
+ "conflict.named": "A workspace named “{name}” already exists.",
2309
+ "folderError.title": "Couldn’t open folder",
2310
+ "folderError.retry": "Choose again",
2311
+ "rename": "Rename",
2312
+ "rename.workspace.title": "Rename workspace",
2313
+ "rename.session.title": "Rename session",
2314
+ "field.workspaceName": "Workspace name",
2315
+ "field.sessionName": "Session name",
2316
+ "delete.workspace": "Delete workspace",
2317
+ "delete.desc": "This removes “{name}” from the workspace list. The folder and session logs will be kept. Its sessions will appear under Ungrouped.",
2318
+ "delete.pending": "Deleting workspace…",
2319
+ "menu.fork": "Fork session",
2320
+ "menu.archiveSession": "Archive session",
2321
+ "sessions.count.one": "{n} session",
2322
+ "sessions.count.other": "{n} sessions",
2323
+ "actions.workspace.aria": "Workspace actions for {name}",
2324
+ "actions.session.aria": "Session actions for {name}",
2325
+ "actions.newSession.aria": "New session in {name}",
2326
+ "status.running": "Running",
2327
+ "status.subagentsRunning.one": "{n} subagent running",
2328
+ "status.subagentsRunning.other": "{n} subagents running",
2329
+ "status.idle": "Idle",
2330
+ "status.waitingApproval": "Waiting for approval",
2331
+ "status.planReview": "Plan awaiting review",
2332
+ "status.waitingAnswer": "Waiting for answer",
2333
+ "status.completed": "Completed",
2334
+ "hover.created": "Created {time}",
2335
+ "hover.copied": "Copied",
2336
+ "date.ymd": "{y}-{m}-{d}",
2337
+ "time.now": "now",
2338
+ "time.minutes": "{n}min",
2339
+ "time.hours": "{n}h",
2340
+ "time.days": "{n}d",
2341
+ "time.months": "{n}mo",
2342
+ "time.years": "{n}y",
2343
+ "time.ago": "{t} ago"
2344
+ };
2345
+ //#endregion
2346
+ //#region lib/types/client/index.js
2347
+ /** Dictionary namespace owned by this plugin. */
2348
+ const NS = "workspace";
2349
+ /**
2350
+ * Required services (cordis fiber inject). The target slots are declared by
2351
+ * the ui-sidebar / ui-conversation applies, whose activation order relative
2352
+ * to this one is NOT constrained: dsh.client.inject edges are informational
2353
+ * (loading/prefetch metadata, never apply sequencing) and neither owner
2354
+ * provides a waitable service. apply therefore depends on each slot
2355
+ * declaration through `slots.inject()` instead of assuming order.
2356
+ */
2357
+ const inject = [
2358
+ "slots",
2359
+ "sessions",
2360
+ "workspaces",
2361
+ "locale",
2362
+ "connection"
2363
+ ];
2364
+ /**
2365
+ * Register the browser and picker once their slot declarations are on the
2366
+ * ledger. Inject factories return plain callbacks; data reads use the
2367
+ * framework's global hooks.
2368
+ * @param ctx - client root context.
2369
+ */
2370
+ function apply(ctx) {
2371
+ const hostDescription = ctx.get("connection").hostDescription;
2372
+ ctx.effect(() => ctx.locale.register(NS, {
2373
+ zh,
2374
+ en
2375
+ }), "ui-workspace: dictionaries");
2376
+ const searchSessions = async (query, signal) => {
2377
+ const result = await ctx.sessions.search(query, signal);
2378
+ if (!result.ok) throw new Error(result.error.message);
2379
+ return result.value;
2380
+ };
2381
+ const flowSource = (hole) => ({
2382
+ getSnapshot: () => ctx.slots.entries(hole).length > 0,
2383
+ subscribe: (listener) => ctx.slots.subscribe(hole, listener)
2384
+ });
2385
+ const browserFlowSource = flowSource("sidebar.workspaces.directoryFlow");
2386
+ const pickerFlowSource = flowSource("conversation.hero.workspace.directoryFlow");
2387
+ const browserInjected = () => ({
2388
+ startSession: (workspaceId) => {
2389
+ ctx.workspaces.startSession(workspaceId);
2390
+ },
2391
+ open: (sessionId) => {
2392
+ ctx.sessions.open(sessionId);
2393
+ },
2394
+ searchSessions,
2395
+ searchResultLimit: ctx.sessions.searchResultLimit,
2396
+ renameSession: async (sessionId, title) => {
2397
+ const session = ctx.sessions.binding(sessionId)?.session;
2398
+ if (session === void 0) throw new Error(`unknown session "${sessionId}"`);
2399
+ const result = await session.rename(title);
2400
+ if (!result.ok) throw new Error(result.error.message);
2401
+ },
2402
+ forkSession: (sessionId) => {
2403
+ ctx.sessions.fork({
2404
+ sessionId,
2405
+ increaseTitle: true
2406
+ }).then((childId) => {
2407
+ ctx.sessions.open(childId);
2408
+ }).catch(() => {});
2409
+ },
2410
+ renameWorkspace: async (workspaceId, title) => {
2411
+ await ctx.workspaces.rename(workspaceId, title);
2412
+ },
2413
+ deleteWorkspace: async (workspaceId) => {
2414
+ await ctx.workspaces.delete(workspaceId);
2415
+ },
2416
+ insertWorkspaceBefore: async (workspaceId, beforeWorkspaceId) => {
2417
+ await ctx.workspaces.insertBefore(workspaceId, beforeWorkspaceId);
2418
+ },
2419
+ archiveSession: async (sessionId) => {
2420
+ await ctx.workspaces.archiveSession(sessionId);
2421
+ },
2422
+ insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => {
2423
+ await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId);
2424
+ },
2425
+ createWorkspace: (input) => ctx.workspaces.create(input),
2426
+ hooks: {
2427
+ directoryFlow: browserFlowSource,
2428
+ hostDescription
2429
+ }
2430
+ });
2431
+ const pickerInjected = () => ({
2432
+ createWorkspace: (input) => ctx.workspaces.create(input),
2433
+ hooks: { directoryFlow: pickerFlowSource }
2434
+ });
2435
+ ctx.slots.inject("sidebar.workspaces", () => ctx.slots.register({
2436
+ name: "sidebar.workspaces",
2437
+ children: { "sidebar.workspaces.directoryFlow": {
2438
+ kind: "single",
2439
+ scope: "root"
2440
+ } },
2441
+ store: createWorkspaceViewStore(),
2442
+ inject: browserInjected,
2443
+ locale: NS
2444
+ }, WorkspaceBrowser));
2445
+ ctx.slots.inject("conversation.hero.workspace", () => ctx.slots.register({
2446
+ name: "conversation.hero.workspace",
2447
+ children: { "conversation.hero.workspace.directoryFlow": {
2448
+ kind: "single",
2449
+ scope: "root"
2450
+ } },
2451
+ inject: pickerInjected,
2452
+ locale: NS
2453
+ }, WorkspacePicker));
2454
+ }
2455
+ //#endregion
2456
+ exports.apply = apply;
2457
+ exports.inject = inject;
2458
+ return module.exports;
2459
+ })(platformRequire);
2460
+ const require = (name) => name === "@deepseek-ai/dsh-client-ui-workspace" ? fixedWorkspaceUi : platformRequire(name);
2461
+ const module = { exports: {} };
2462
+ const exports = module.exports;
2463
+ var __create = Object.create;
2464
+ var __defProp = Object.defineProperty;
2465
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
2466
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2467
+ var __getProtoOf = Object.getPrototypeOf;
2468
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
2469
+ var __export = (target, all) => {
2470
+ for (var name2 in all)
2471
+ __defProp(target, name2, { get: all[name2], enumerable: true });
2472
+ };
2473
+ var __copyProps = (to, from, except, desc) => {
2474
+ if (from && typeof from === "object" || typeof from === "function") {
2475
+ for (let key of __getOwnPropNames(from))
2476
+ if (!__hasOwnProp.call(to, key) && key !== except)
2477
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
2478
+ }
2479
+ return to;
2480
+ };
2481
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
2482
+ // If the importer is in node compatibility mode or this is not an ESM
2483
+ // file that has been converted to a CommonJS file using a Babel-
2484
+ // compatible transform (i.e. "__esModule" has not been set), then set
2485
+ // "default" to the CommonJS "module.exports" for node compatibility.
2486
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
2487
+ mod
2488
+ ));
2489
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
2490
+
2491
+ // packages/execution/src/client/browser-entry.js
2492
+ var browser_entry_exports = {};
2493
+ __export(browser_entry_exports, {
2494
+ apply: () => apply,
2495
+ inject: () => inject,
2496
+ name: () => name
2497
+ });
2498
+ module.exports = __toCommonJS(browser_entry_exports);
2499
+ var import_react = __toESM(require("react"), 1);
2500
+ var import_dsh_client_ui_primitives = require("@deepseek-ai/dsh-client-ui-primitives");
2501
+ var workspaceUi = __toESM(require("@deepseek-ai/dsh-client-ui-workspace"), 1);
2502
+
2503
+ // packages/execution/src/action-presentation/model.js
2504
+ var DSH_ACTION_PRESENTATION_COMPATIBILITY = Object.freeze({
2505
+ dsh: "0.1.1-rc.2",
2506
+ uiPrimitives: "@deepseek-ai/dsh-client-ui-primitives@0.1.1-rc.2",
2507
+ presentation: "wsr.presentation@1.0.0"
2508
+ });
2509
+ var ROOT_KEYS = "correlation,data,kind,schemaVersion";
2510
+ var KINDS = /* @__PURE__ */ new Set([
2511
+ "command-accepted",
2512
+ "delivery-running",
2513
+ "delivery-list",
2514
+ "delivery-status",
2515
+ "action-output",
2516
+ "action-input-request",
2517
+ "terminal-result",
2518
+ "error"
2519
+ ]);
2520
+ var ACTION_STATES = /* @__PURE__ */ new Set(["running", "completed", "failed", "cancelled", "waiting", "recovering"]);
2521
+ var TERMINAL_OUTCOMES = /* @__PURE__ */ new Set(["SUCCEEDED", "FAILED", "CANCELLED"]);
2522
+ var DELIVERY_STATES = /* @__PURE__ */ new Set([
2523
+ "BOUND",
2524
+ "START_UNCERTAIN",
2525
+ "RUNNING_CORRELATED",
2526
+ "START_FAILED",
2527
+ "RESULT_UNRESOLVED",
2528
+ "TERMINAL_HANDLING",
2529
+ "RUNNING",
2530
+ "RECOVERING",
2531
+ "WAITING",
2532
+ "AWAITING_INPUT",
2533
+ "COMPLETED",
2534
+ "SUCCEEDED",
2535
+ "FAILED",
2536
+ "CANCELLED"
2537
+ ]);
2538
+ var MAX_PRESENTATION_BYTES = 4096;
2539
+ function deepFreeze(value, seen = /* @__PURE__ */ new Set()) {
2540
+ if (value === null || typeof value !== "object" || seen.has(value)) return value;
2541
+ seen.add(value);
2542
+ for (const child of Object.values(value)) deepFreeze(child, seen);
2543
+ return Object.freeze(value);
2544
+ }
2545
+ function invalidPresentation() {
2546
+ return deepFreeze({
2547
+ schemaVersion: DSH_ACTION_PRESENTATION_COMPATIBILITY.presentation,
2548
+ correlation: "presentation-invalid",
2549
+ kind: "error",
2550
+ data: { code: "WSR_PRESENTATION_INVALID", message: "WSR presentation unavailable" }
2551
+ });
2552
+ }
2553
+ function plainJson(value, seen = /* @__PURE__ */ new Set()) {
2554
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
2555
+ if (typeof value === "number") return Number.isFinite(value);
2556
+ if (typeof value !== "object" || seen.has(value)) return false;
2557
+ seen.add(value);
2558
+ if (Array.isArray(value)) return value.every((item) => plainJson(item, seen));
2559
+ if (Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return false;
2560
+ const descriptors = Object.getOwnPropertyDescriptors(value);
2561
+ return Reflect.ownKeys(value).every((key) => typeof key === "string" && descriptors[key] !== void 0 && "value" in descriptors[key] && plainJson(descriptors[key].value, seen));
2562
+ }
2563
+ function hasValidTypedData(value) {
2564
+ if (value.kind === "action-output") {
2565
+ const state = value.data.state === void 0 ? "completed" : value.data.state;
2566
+ const channel = value.data.channel === void 0 ? "action" : value.data.channel;
2567
+ return typeof state === "string" && ACTION_STATES.has(state) && (channel === "action" || channel === "tool");
2568
+ }
2569
+ if (value.kind === "terminal-result") {
2570
+ const outputValid = Object.hasOwn(value.data, "finalOutput") ? typeof value.data.finalOutput === "string" && value.data.finalOutput.length > 0 : typeof value.data.summary === "string" && value.data.summary.length > 0;
2571
+ return typeof value.data.outcome === "string" && TERMINAL_OUTCOMES.has(value.data.outcome) && outputValid;
2572
+ }
2573
+ if (value.kind === "delivery-running" || value.kind === "delivery-status") {
2574
+ return value.data.state === void 0 || typeof value.data.state === "string" && DELIVERY_STATES.has(value.data.state);
2575
+ }
2576
+ return true;
2577
+ }
2578
+ function parseExecutionPresentation(input) {
2579
+ let value = input;
2580
+ if (typeof input === "string") {
2581
+ if (input.length === 0 || new TextEncoder().encode(input).byteLength > MAX_PRESENTATION_BYTES) return invalidPresentation();
2582
+ try {
2583
+ value = JSON.parse(input);
2584
+ } catch {
2585
+ return invalidPresentation();
2586
+ }
2587
+ }
2588
+ if (value === null || typeof value !== "object" || Array.isArray(value) || Object.keys(value).sort().join(",") !== ROOT_KEYS || value.schemaVersion !== DSH_ACTION_PRESENTATION_COMPATIBILITY.presentation || typeof value.correlation !== "string" || value.correlation.length === 0 || !KINDS.has(value.kind) || value.data === null || typeof value.data !== "object" || Array.isArray(value.data) || !plainJson(value.data) || !hasValidTypedData(value)) return invalidPresentation();
2589
+ return deepFreeze(structuredClone(value));
2590
+ }
2591
+ function text(value, keys = ["text", "message", "question", "summary", "result"]) {
2592
+ if (typeof value === "string") return value;
2593
+ if (Array.isArray(value)) {
2594
+ const lines = value.map((item) => text(item, keys)).filter((item) => typeof item === "string" && item.length > 0);
2595
+ return lines.length === 0 ? void 0 : lines.join("\n\n");
2596
+ }
2597
+ if (value === null || typeof value !== "object") return void 0;
2598
+ for (const key of keys) {
2599
+ if (!Object.hasOwn(value, key)) continue;
2600
+ const nested = text(value[key], keys);
2601
+ if (nested !== void 0) return nested;
2602
+ }
2603
+ return void 0;
2604
+ }
2605
+ function normalizedLifecycle(value, fallback) {
2606
+ if (typeof value !== "string") return fallback;
2607
+ const normalized = value.toLowerCase().replaceAll("_", "-");
2608
+ if (["succeeded", "success", "done", "terminal"].includes(normalized)) return "completed";
2609
+ if (["failed", "error"].includes(normalized)) return "failed";
2610
+ if (["cancelled", "canceled"].includes(normalized)) return "cancelled";
2611
+ if (["waiting", "awaiting-input"].includes(normalized)) return "waiting";
2612
+ if (["start-failed"].includes(normalized)) return "failed";
2613
+ if (["recovering", "recovery", "running-correlated", "result-unresolved", "terminal-handling"].includes(normalized)) return "recovering";
2614
+ if (["running", "accepted", "start-uncertain", "bound"].includes(normalized)) return "running";
2615
+ return fallback;
2616
+ }
2617
+ var STATE_LABELS = Object.freeze({
2618
+ running: "Running",
2619
+ completed: "Completed",
2620
+ failed: "Failed",
2621
+ cancelled: "Cancelled",
2622
+ waiting: "Waiting for input",
2623
+ recovering: "Recovering"
2624
+ });
2625
+ function model(input) {
2626
+ return deepFreeze(input);
2627
+ }
2628
+ function projectExecutionPresentation(event) {
2629
+ const { correlation, data } = event;
2630
+ if (event.kind === "delivery-list") throw new TypeError("WSR_PRESENTATION_OUT_OF_SCOPE");
2631
+ if (event.kind === "terminal-result") {
2632
+ const state2 = normalizedLifecycle(data.outcome, "failed");
2633
+ const body = typeof data.finalOutput === "string" ? data.finalOutput : data.summary;
2634
+ return model({
2635
+ correlation,
2636
+ layer: "final",
2637
+ state: state2,
2638
+ title: "Final result",
2639
+ summary: data.outcome[0] + data.outcome.slice(1).toLowerCase(),
2640
+ body,
2641
+ defaultOpen: true,
2642
+ focusPolicy: "none",
2643
+ role: "article",
2644
+ compatibility: typeof data.finalOutput === "string" ? "current" : "legacy-summary"
2645
+ });
2646
+ }
2647
+ if (event.kind === "action-input-request") {
2648
+ return model({
2649
+ correlation,
2650
+ layer: "action",
2651
+ state: "waiting",
2652
+ title: typeof data.label === "string" ? data.label : "Workflow Action",
2653
+ summary: STATE_LABELS.waiting,
2654
+ body: text(data.prompt) ?? "Input required",
2655
+ defaultOpen: true,
2656
+ focusPolicy: "preserve",
2657
+ role: "status",
2658
+ compatibility: "current"
2659
+ });
2660
+ }
2661
+ if (event.kind === "action-output") {
2662
+ const state2 = data.state ?? "completed";
2663
+ return model({
2664
+ correlation,
2665
+ layer: data.channel === "tool" ? "tool" : "action",
2666
+ state: state2,
2667
+ title: typeof data.label === "string" ? data.label : "Workflow Action",
2668
+ summary: STATE_LABELS[state2],
2669
+ body: text(data.content) ?? "WSR content unavailable",
2670
+ defaultOpen: state2 !== "completed",
2671
+ focusPolicy: "none",
2672
+ role: "status",
2673
+ compatibility: "current"
2674
+ });
2675
+ }
2676
+ if (event.kind === "error") {
2677
+ return model({
2678
+ correlation,
2679
+ layer: "progress",
2680
+ state: "failed",
2681
+ title: "Workflow presentation",
2682
+ summary: typeof data.code === "string" ? data.code : "WSR_ERROR",
2683
+ body: typeof data.message === "string" ? data.message : "WSR presentation unavailable",
2684
+ defaultOpen: true,
2685
+ focusPolicy: "none",
2686
+ role: "alert",
2687
+ compatibility: "current"
2688
+ });
2689
+ }
2690
+ const state = event.kind === "delivery-running" ? normalizedLifecycle(data.state, "running") : normalizedLifecycle(data.state, event.kind === "command-accepted" ? "running" : "running");
2691
+ const deliveryId = typeof data.deliveryId === "string" ? data.deliveryId : void 0;
2692
+ return model({
2693
+ correlation,
2694
+ layer: "progress",
2695
+ state,
2696
+ title: "Workflow delivery",
2697
+ summary: `${STATE_LABELS[state]}${deliveryId === void 0 ? "" : ` \xB7 ${deliveryId}`}`,
2698
+ body: void 0,
2699
+ defaultOpen: state !== "completed",
2700
+ focusPolicy: "none",
2701
+ role: "status",
2702
+ compatibility: "current"
2703
+ });
2704
+ }
2705
+ function resolveDisclosureOpen({ current, previousState, nextState, containsFocus }) {
2706
+ if (nextState === "waiting") return true;
2707
+ if (nextState === "completed" && previousState !== "completed") return containsFocus ? true : false;
2708
+ if (["running", "recovering", "failed", "cancelled"].includes(nextState) && nextState !== previousState) return true;
2709
+ return current;
2710
+ }
2711
+ function createExecutionPresentationDefinition() {
2712
+ return Object.freeze({
2713
+ kind: "wsr-execution-presentation",
2714
+ target: "chat",
2715
+ match(event) {
2716
+ if (event?.type === "command/run" && event.data?.name === "wsr" && event.data?.source?.kind === "plugin" && event.data?.source?.plugin === "workflow-execution" && typeof event.data?.commandId === "string") {
2717
+ return { id: event.data.commandId, role: "start" };
2718
+ }
2719
+ return event?.type === "command/done" && typeof event.data?.commandId === "string" ? { id: event.data.commandId, role: "update" } : null;
2720
+ },
2721
+ start(_context, match) {
2722
+ return Object.freeze({ seq: match.event.seq, presentation: void 0 });
2723
+ },
2724
+ update(context, match) {
2725
+ const event = parseExecutionPresentation(match.event?.data?.text);
2726
+ if (event.kind === "delivery-list") {
2727
+ return Object.freeze({ ...context.state, presentation: void 0 });
2728
+ }
2729
+ return Object.freeze({ ...context.state, presentation: projectExecutionPresentation(event) });
2730
+ },
2731
+ buildViewNode(context) {
2732
+ if (context.state?.presentation === void 0) return null;
2733
+ return Object.freeze({
2734
+ key: context.key,
2735
+ kind: "wsr-execution-presentation",
2736
+ id: context.id,
2737
+ target: "chat",
2738
+ anchorSeq: context.state.seq,
2739
+ location: context.start?.location ?? { kind: "unresolved" },
2740
+ visibility: "visible",
2741
+ data: context.state.presentation
2742
+ });
2743
+ }
2744
+ });
2745
+ }
2746
+
2747
+ // packages/execution/src/action-presentation/view.js
2748
+ var DOT_STATE = Object.freeze({
2749
+ running: "ongoing",
2750
+ recovering: "ongoing",
2751
+ completed: "done",
2752
+ waiting: "warning",
2753
+ failed: "error",
2754
+ cancelled: "error"
2755
+ });
2756
+ function createActionPresentationView({ React: React2, DisclosureRow: DisclosureRow2, MessageText: MessageText2, StateDot: StateDot2, observe = () => void 0 }) {
2757
+ if (typeof DisclosureRow2 !== "function") throw new TypeError("DSH_DISCLOSURE_ROW_REQUIRED");
2758
+ return function WsrExecutionPresentationView({ node }) {
2759
+ const presentation = node.data;
2760
+ const [open, setOpen] = React2.useState(presentation.defaultOpen);
2761
+ const bodyRef = React2.useRef(null);
2762
+ const previousState = React2.useRef(presentation.state);
2763
+ React2.useEffect(() => {
2764
+ setOpen((current) => resolveDisclosureOpen({
2765
+ current,
2766
+ previousState: previousState.current,
2767
+ nextState: presentation.state,
2768
+ containsFocus: typeof document !== "undefined" && bodyRef.current !== null && bodyRef.current.contains(document.activeElement)
2769
+ }));
2770
+ previousState.current = presentation.state;
2771
+ }, [presentation.state]);
2772
+ observe(presentation);
2773
+ if (presentation.layer === "final") {
2774
+ return React2.createElement("article", {
2775
+ "data-wsr-presentation": "true",
2776
+ "data-wsr-layer": "final",
2777
+ "data-wsr-state": presentation.state,
2778
+ "data-wsr-correlation": presentation.correlation,
2779
+ "data-wsr-chat-role": "assistant",
2780
+ "data-wsr-compatibility": presentation.compatibility,
2781
+ "aria-label": presentation.title
2782
+ }, React2.createElement(MessageText2, { text: presentation.body }));
2783
+ }
2784
+ const waiting = presentation.state === "waiting";
2785
+ const expandable = presentation.body !== void 0 && !waiting;
2786
+ const body = presentation.body === void 0 ? void 0 : React2.createElement("div", {
2787
+ ref: bodyRef,
2788
+ "data-wsr-presentation": "true",
2789
+ "data-wsr-layer": presentation.layer,
2790
+ "data-wsr-state": presentation.state,
2791
+ "data-wsr-correlation": presentation.correlation,
2792
+ "data-wsr-action-input": waiting ? "true" : void 0,
2793
+ role: waiting ? "group" : void 0,
2794
+ tabIndex: waiting ? 0 : void 0,
2795
+ "aria-label": waiting ? presentation.summary : void 0,
2796
+ "aria-live": waiting ? "polite" : void 0
2797
+ }, React2.createElement("pre", {
2798
+ style: { margin: 0, maxHeight: "20rem", overflow: "auto", whiteSpace: "pre-wrap", wordBreak: "break-word" }
2799
+ }, presentation.body));
2800
+ return React2.createElement(DisclosureRow2, {
2801
+ icon: React2.createElement(StateDot2, { state: DOT_STATE[presentation.state], size: 10 }),
2802
+ title: presentation.title,
2803
+ open: waiting ? true : open,
2804
+ expandable,
2805
+ onToggle: waiting ? () => void 0 : () => setOpen((current) => !current),
2806
+ expandOnRowClick: expandable,
2807
+ // The locked primitive animates its hover-preview icon without a
2808
+ // reduced-motion branch. Keeping that optional preview off preserves the
2809
+ // same keyboard disclosure while making WSR rows motion-free.
2810
+ previewChevron: false,
2811
+ keepContentWhenOpen: true,
2812
+ collapsedContent: React2.createElement("span", {
2813
+ role: presentation.role,
2814
+ "aria-live": ["running", "recovering", "waiting"].includes(presentation.state) ? "polite" : void 0
2815
+ }, presentation.summary)
2816
+ }, body);
2817
+ };
2818
+ }
2819
+ function registerActionPresentation(ctx, View) {
2820
+ ctx.conversationEvents.register(createExecutionPresentationDefinition());
2821
+ ctx.slots.inject("conversation.chat.node", () => ctx.slots.register({
2822
+ name: "conversation.chat.node",
2823
+ key: "wsr-execution-presentation"
2824
+ }, View));
2825
+ }
2826
+
2827
+ // packages/execution/src/client/delivery/control-plane-port.js
2828
+ var CHANNEL = "/wsr-execution";
2829
+ function createStore(initial) {
2830
+ let snapshot = initial;
2831
+ const listeners = /* @__PURE__ */ new Set();
2832
+ return Object.freeze({
2833
+ getSnapshot: () => snapshot,
2834
+ subscribe(listener) {
2835
+ listeners.add(listener);
2836
+ return () => listeners.delete(listener);
2837
+ },
2838
+ publish(value) {
2839
+ snapshot = Object.freeze(value);
2840
+ for (const listener of [...listeners]) listener();
2841
+ }
2842
+ });
2843
+ }
2844
+ function message(error) {
2845
+ return typeof error?.message === "string" && error.message.length > 0 ? error.message : "Delivery control plane unavailable";
2846
+ }
2847
+ function createDeliveryControlPlaneClient(rpc) {
2848
+ if (typeof rpc?.call !== "function") throw new TypeError("DSH_CONNECTION_RPC_REQUIRED");
2849
+ const inventory = createStore(Object.freeze({ kind: "loading" }));
2850
+ const sessions = /* @__PURE__ */ new Map();
2851
+ const read = async (endpoint, payload) => {
2852
+ const result = await rpc.call(CHANNEL, endpoint, payload);
2853
+ if (result?.ok !== true) throw new Error(message(result?.error));
2854
+ return result.value;
2855
+ };
2856
+ const client = {
2857
+ inventory,
2858
+ async refresh() {
2859
+ try {
2860
+ const value = await read("inventory/read", {});
2861
+ inventory.publish({ kind: "ready", snapshot: value });
2862
+ for (const source of sessions.values()) void source.refresh();
2863
+ } catch (error) {
2864
+ const previous = inventory.getSnapshot();
2865
+ inventory.publish({
2866
+ kind: previous.kind === "ready" ? "reconnecting" : "error",
2867
+ message: message(error),
2868
+ ...previous.kind === "ready" ? { snapshot: previous.snapshot } : {}
2869
+ });
2870
+ }
2871
+ },
2872
+ bindSession(sessionCorrelation) {
2873
+ if (typeof sessionCorrelation !== "string" || sessionCorrelation.length === 0 || sessionCorrelation.length > 512) {
2874
+ throw new TypeError("SESSION_CORRELATION_INVALID");
2875
+ }
2876
+ if (sessions.has(sessionCorrelation)) return sessions.get(sessionCorrelation);
2877
+ const store = createStore(Object.freeze({ kind: "loading" }));
2878
+ const source = Object.freeze({
2879
+ getSnapshot: store.getSnapshot,
2880
+ subscribe: store.subscribe,
2881
+ async refresh() {
2882
+ try {
2883
+ store.publish({ kind: "ready", view: await read("session/read", { sessionCorrelation }) });
2884
+ } catch (error) {
2885
+ store.publish({ kind: "error", code: "DELIVERY_PROJECTION_UNAVAILABLE", message: message(error) });
2886
+ }
2887
+ }
2888
+ });
2889
+ sessions.set(sessionCorrelation, source);
2890
+ return source;
2891
+ }
2892
+ };
2893
+ return Object.freeze(client);
2894
+ }
2895
+
2896
+ // packages/execution/src/client/delivery/session-delivery-view.js
2897
+ var DELIVERY_VIEW_ID = "delivery";
2898
+ var DELIVERY_VIEW_ORDER = 20;
2899
+ var SHA256 = /^sha256:[0-9a-f]{64}$/u;
2900
+ var LIFECYCLES = /* @__PURE__ */ new Set([
2901
+ "BOUND",
2902
+ "START_UNCERTAIN",
2903
+ "RUNNING_CORRELATED",
2904
+ "START_FAILED",
2905
+ "RESULT_UNRESOLVED",
2906
+ "TERMINAL_HANDLING",
2907
+ "TERMINAL"
2908
+ ]);
2909
+ function nonEmpty(value) {
2910
+ return typeof value === "string" && value.length > 0;
2911
+ }
2912
+ function validDelivery(delivery, sessionCorrelation) {
2913
+ return delivery !== null && typeof delivery === "object" && !Array.isArray(delivery) && nonEmpty(delivery.deliveryId) && SHA256.test(delivery.deliveryBindingIdentity) && nonEmpty(delivery.task?.identity) && nonEmpty(delivery.workflow?.identity) && nonEmpty(delivery.workflow?.packageName) && nonEmpty(delivery.workflow?.exactPackageVersion) && SHA256.test(delivery.workflow?.packageDigest) && nonEmpty(delivery.workflow?.snapshotIdentity) && SHA256.test(delivery.workflow?.snapshotDigest) && LIFECYCLES.has(delivery.lifecycle) && delivery.navigation?.sessionCorrelation === sessionCorrelation && delivery.detached === false && typeof delivery.recoverable === "boolean" && Number.isSafeInteger(delivery.timing?.startedAt) && Number.isSafeInteger(delivery.timing?.updatedAt) && Number.isSafeInteger(delivery.timing?.elapsedMs) && delivery.timing.elapsedMs >= 0;
2914
+ }
2915
+ function duration(value) {
2916
+ const seconds = Math.floor(value / 1e3);
2917
+ if (seconds < 60) return `${seconds}.${String(value % 1e3).padStart(3, "0")}s`;
2918
+ return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;
2919
+ }
2920
+ function safeSnapshot(source) {
2921
+ try {
2922
+ return source.getSnapshot();
2923
+ } catch {
2924
+ return { kind: "error", code: "DELIVERY_PROJECTION_UNAVAILABLE", message: "Execution projection unavailable" };
2925
+ }
2926
+ }
2927
+ function safeSubscribe(source, notify) {
2928
+ try {
2929
+ const dispose = source.subscribe(notify);
2930
+ return typeof dispose === "function" ? dispose : () => void 0;
2931
+ } catch {
2932
+ return () => void 0;
2933
+ }
2934
+ }
2935
+ function pair(React2, label, value) {
2936
+ return [
2937
+ React2.createElement("dt", { key: `${label}-label` }, label),
2938
+ React2.createElement("dd", { key: `${label}-value` }, value)
2939
+ ];
2940
+ }
2941
+ function statePanel(React2, role, code, message2) {
2942
+ return React2.createElement(
2943
+ "section",
2944
+ {
2945
+ "aria-labelledby": "wsr-delivery-view-title",
2946
+ "aria-live": role === "alert" ? "assertive" : "polite",
2947
+ "data-wsr-delivery-view": "true",
2948
+ role
2949
+ },
2950
+ React2.createElement("h2", { id: "wsr-delivery-view-title" }, "Delivery"),
2951
+ React2.createElement("p", null, message2),
2952
+ code === void 0 ? null : React2.createElement("code", null, code)
2953
+ );
2954
+ }
2955
+ function createSessionDeliveryView(React2) {
2956
+ if (typeof React2?.createElement !== "function" || typeof React2?.useSyncExternalStore !== "function") {
2957
+ throw new TypeError("DELIVERY_VIEW_REACT_INVALID");
2958
+ }
2959
+ return function SessionDeliveryView({ sessionId, source }) {
2960
+ const state = React2.useSyncExternalStore(
2961
+ (notify) => safeSubscribe(source, notify),
2962
+ () => safeSnapshot(source),
2963
+ () => safeSnapshot(source)
2964
+ );
2965
+ if (state.kind === "loading") return statePanel(React2, "status", void 0, "Loading Delivery\u2026");
2966
+ if (state.kind === "error") return statePanel(React2, "alert", state.code ?? "DELIVERY_PROJECTION_UNAVAILABLE", state.message ?? "Execution projection unavailable");
2967
+ const view = state.view;
2968
+ if (state.kind !== "ready" || view?.sessionCorrelation !== sessionId) {
2969
+ return statePanel(React2, "alert", "DELIVERY_PROJECTION_CORRUPT", "Delivery projection invalid");
2970
+ }
2971
+ if (view.kind === "UNBOUND") return statePanel(React2, "status", void 0, "No Delivery bound to this Session");
2972
+ if (view.kind !== "BOUND" || !validDelivery(view.delivery, sessionId)) {
2973
+ return statePanel(React2, "alert", "DELIVERY_PROJECTION_CORRUPT", "Delivery projection invalid");
2974
+ }
2975
+ const delivery = view.delivery;
2976
+ const failed = delivery.terminal?.outcome === "FAILED" || delivery.error !== null;
2977
+ const identityRows = [
2978
+ ...pair(React2, "Delivery", delivery.deliveryId),
2979
+ ...pair(React2, "Task", delivery.task.displayName ?? delivery.task.identity),
2980
+ ...pair(React2, "Workflow", delivery.workflow.identity),
2981
+ ...pair(React2, "Package", `${delivery.workflow.packageName}@${delivery.workflow.exactPackageVersion}`),
2982
+ ...pair(React2, "Package digest", delivery.workflow.packageDigest),
2983
+ ...pair(React2, "Snapshot", delivery.workflow.snapshotIdentity),
2984
+ ...pair(React2, "Snapshot digest", delivery.workflow.snapshotDigest),
2985
+ ...pair(React2, "Binding", delivery.deliveryBindingIdentity)
2986
+ ];
2987
+ const lifecycleRows = [
2988
+ ...pair(React2, "Lifecycle", delivery.lifecycle),
2989
+ ...pair(React2, "Recoverable", delivery.recoverable ? "yes" : "no"),
2990
+ ...delivery.current === null ? [] : pair(React2, delivery.current.kind === "ACTION" ? "Current Action" : "Current Intervention", delivery.current.identity),
2991
+ ...pair(React2, "Started", new Date(delivery.timing.startedAt).toISOString()),
2992
+ ...pair(React2, "Elapsed", duration(delivery.timing.elapsedMs)),
2993
+ ...delivery.terminal === null ? [] : [
2994
+ ...pair(React2, "Ended", new Date(delivery.terminal.finishedAt).toISOString()),
2995
+ ...pair(React2, "Outcome", delivery.terminal.outcome)
2996
+ ],
2997
+ ...delivery.error === null ? [] : pair(React2, "Error", delivery.error.code)
2998
+ ];
2999
+ return React2.createElement(
3000
+ "section",
3001
+ {
3002
+ "aria-labelledby": "wsr-delivery-view-title",
3003
+ "aria-live": failed ? "assertive" : "polite",
3004
+ "data-wsr-delivery-id": delivery.deliveryId,
3005
+ "data-wsr-delivery-view": "true",
3006
+ role: failed ? "alert" : "region"
3007
+ },
3008
+ React2.createElement("h2", { id: "wsr-delivery-view-title" }, "Delivery"),
3009
+ React2.createElement("dl", { "aria-label": "Delivery identity" }, identityRows),
3010
+ React2.createElement("dl", { "aria-label": "Delivery lifecycle" }, lifecycleRows)
3011
+ );
3012
+ };
3013
+ }
3014
+ function registerSessionDeliveryView(ctx, options) {
3015
+ if (typeof ctx?.slots?.inject !== "function" || typeof ctx?.slots?.register !== "function" || typeof options?.bindProjection !== "function") throw new TypeError("DELIVERY_VIEW_REGISTRATION_INVALID");
3016
+ const View = createSessionDeliveryView(options.React);
3017
+ ctx.slots.inject("conversation.view", () => ctx.slots.register({
3018
+ name: "conversation.view",
3019
+ id: DELIVERY_VIEW_ID,
3020
+ order: DELIVERY_VIEW_ORDER,
3021
+ label: "Delivery",
3022
+ inject: (sessionId) => ({ source: options.bindProjection(sessionId) })
3023
+ }, View));
3024
+ }
3025
+
3026
+ // packages/execution/src/client/delivery-inventory/model.js
3027
+ var CONTROL_PLANE_SCHEMA = "execution.delivery-control-plane@1.0.0";
3028
+ var LIFECYCLES2 = /* @__PURE__ */ new Set([
3029
+ "BOUND",
3030
+ "START_UNCERTAIN",
3031
+ "RUNNING_CORRELATED",
3032
+ "START_FAILED",
3033
+ "RESULT_UNRESOLVED",
3034
+ "TERMINAL_HANDLING",
3035
+ "TERMINAL"
3036
+ ]);
3037
+ function errorView(label = "Delivery inventory unavailable") {
3038
+ return Object.freeze({ kind: "error", role: "alert", label, rows: Object.freeze([]) });
3039
+ }
3040
+ function validString(value) {
3041
+ return typeof value === "string" && value.length > 0 && value.length <= 512;
3042
+ }
3043
+ function lifecycleLabel(delivery) {
3044
+ if (delivery.lifecycle === "TERMINAL") return delivery.terminal?.outcome ?? "Terminal";
3045
+ return delivery.lifecycle.toLowerCase().replaceAll("_", " ").replace(/^./u, (value) => value.toUpperCase());
3046
+ }
3047
+ function rowsFrom(deliveries, selectedSessionId) {
3048
+ if (!Array.isArray(deliveries)) return void 0;
3049
+ const identities = /* @__PURE__ */ new Set();
3050
+ const rows = [];
3051
+ for (const delivery of deliveries) {
3052
+ const sessionCorrelation = delivery?.navigation?.sessionCorrelation ?? null;
3053
+ if (delivery === null || typeof delivery !== "object" || Array.isArray(delivery) || !validString(delivery.deliveryId) || identities.has(delivery.deliveryId) || !LIFECYCLES2.has(delivery.lifecycle) || typeof delivery.detached !== "boolean" || typeof delivery.recoverable !== "boolean" || !validString(delivery.task?.identity) || !(delivery.task.displayName === null || validString(delivery.task.displayName)) || !(sessionCorrelation === null || validString(sessionCorrelation))) return void 0;
3054
+ identities.add(delivery.deliveryId);
3055
+ rows.push(Object.freeze({
3056
+ deliveryId: delivery.deliveryId,
3057
+ label: delivery.task.displayName ?? delivery.task.identity,
3058
+ statusLabel: lifecycleLabel(delivery),
3059
+ sessionId: sessionCorrelation,
3060
+ availability: sessionCorrelation !== null ? "bound" : delivery.recoverable ? "recoverable" : "detached",
3061
+ selected: sessionCorrelation !== null && sessionCorrelation === selectedSessionId
3062
+ }));
3063
+ }
3064
+ rows.sort((left, right) => left.deliveryId.localeCompare(right.deliveryId));
3065
+ return Object.freeze(rows);
3066
+ }
3067
+ function projectDeliveryInventory(state, { selectedSessionId } = {}) {
3068
+ if (state?.kind === "loading") return Object.freeze({ kind: "loading", role: "status", label: "Loading Deliveries", rows: Object.freeze([]) });
3069
+ if (state?.kind === "error") return errorView(validString(state.message) ? state.message : void 0);
3070
+ if (!(/* @__PURE__ */ new Set(["ready", "reconnecting"])).has(state?.kind)) return errorView();
3071
+ const snapshot = state.snapshot;
3072
+ if (snapshot === null || typeof snapshot !== "object" || Array.isArray(snapshot) || snapshot.schemaVersion !== CONTROL_PLANE_SCHEMA || !Number.isSafeInteger(snapshot.generation) || snapshot.generation < 1) return errorView();
3073
+ const rows = rowsFrom(snapshot.deliveries, selectedSessionId);
3074
+ if (rows === void 0) return errorView();
3075
+ if (state.kind === "reconnecting") return Object.freeze({ kind: "reconnecting", role: "status", label: "Reconnecting to Delivery inventory", rows });
3076
+ if (rows.length === 0) return Object.freeze({ kind: "empty", role: "status", label: "No Deliveries", rows });
3077
+ return Object.freeze({ kind: "ready", role: "list", label: "Deliveries", rows });
3078
+ }
3079
+
3080
+ // packages/execution/src/client/delivery-inventory/sidebar.js
3081
+ var STYLE_ID = "dsh-wsr-execution-delivery-inventory";
3082
+ var CSS = ".wsr-sidebar-resources{min-height:0;flex:1;display:flex;flex-direction:column;gap:4px}.wsr-sidebar-resource{min-height:0;display:flex;flex-direction:column}.wsr-sidebar-resource:first-child{flex:1}.wsr-sidebar-resource-header{box-sizing:border-box;width:100%;height:36px;cursor:pointer;color:var(--dsw-alias-label-tertiary);background:transparent;border:0;border-radius:8px;display:flex;align-items:center;gap:6px;padding:0 8px;font-size:13px;text-align:left}.wsr-sidebar-resource-header:hover{background:var(--dsw-alias-interactive-bg-hover)}.wsr-delivery-row{box-sizing:border-box;width:100%;height:32px;cursor:pointer;color:var(--dsw-alias-label-primary);background:transparent;border:0;border-radius:8px;display:flex;align-items:center;gap:6px;padding:0 8px;font-size:14px;line-height:20px;text-align:left}.wsr-delivery-row:hover,.wsr-delivery-row[aria-current=page]{background:var(--dsw-alias-interactive-bg-hover)}.wsr-delivery-row:disabled{cursor:default}.wsr-delivery-row>span:first-child{text-overflow:ellipsis;white-space:nowrap;min-width:0;overflow:hidden;flex:1}.wsr-delivery-status{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:20px}.wsr-delivery-status-recoverable{color:var(--dsw-alias-state-warning-primary)}";
3083
+ function installStyle() {
3084
+ if (typeof document === "undefined" || document.getElementById(STYLE_ID) !== null) return;
3085
+ const tag = document.createElement("style");
3086
+ tag.id = STYLE_ID;
3087
+ tag.dataset.plugin = "dsh-wsr-execution";
3088
+ tag.textContent = CSS;
3089
+ document.head.append(tag);
3090
+ }
3091
+ function persisted(key) {
3092
+ try {
3093
+ return typeof localStorage === "undefined" || localStorage.getItem(key) !== "false";
3094
+ } catch {
3095
+ return true;
3096
+ }
3097
+ }
3098
+ function persist(key, value) {
3099
+ try {
3100
+ if (typeof localStorage !== "undefined") localStorage.setItem(key, String(value));
3101
+ } catch {
3102
+ }
3103
+ }
3104
+ function createSidebarResources(React2, WorkspaceBrowser, inventory) {
3105
+ return function WsrSidebarResources(props) {
3106
+ const [workspaceExpanded, setWorkspaceExpanded] = React2.useState(() => persisted("wsr.sidebar.workspace.expanded.v1"));
3107
+ const [deliveryExpanded, setDeliveryExpanded] = React2.useState(() => persisted("wsr.sidebar.delivery.expanded.v1"));
3108
+ const selectedSessionId = props.useSessions((state2) => state2.current);
3109
+ const state = React2.useSyncExternalStore(inventory.subscribe, inventory.getSnapshot, inventory.getSnapshot);
3110
+ const view = React2.useMemo(() => projectDeliveryInventory(state, { selectedSessionId }), [state, selectedSessionId]);
3111
+ const toggle = (kind) => {
3112
+ if (kind === "workspace") {
3113
+ const next = !workspaceExpanded;
3114
+ setWorkspaceExpanded(next);
3115
+ persist("wsr.sidebar.workspace.expanded.v1", next);
3116
+ } else {
3117
+ const next = !deliveryExpanded;
3118
+ setDeliveryExpanded(next);
3119
+ persist("wsr.sidebar.delivery.expanded.v1", next);
3120
+ }
3121
+ };
3122
+ const header = (id, label, expanded, kind) => React2.createElement("button", {
3123
+ type: "button",
3124
+ className: "wsr-sidebar-resource-header",
3125
+ "aria-controls": id,
3126
+ "aria-expanded": expanded,
3127
+ onClick: () => toggle(kind),
3128
+ onKeyDown: (event) => {
3129
+ if (event.key !== "Enter" && event.key !== " ") return;
3130
+ event.preventDefault();
3131
+ toggle(kind);
3132
+ }
3133
+ }, React2.createElement("span", { "aria-hidden": "true" }, expanded ? "\u25BE" : "\u25B8"), label);
3134
+ return React2.createElement(
3135
+ "div",
3136
+ { className: "wsr-sidebar-resources", "data-wsr-sidebar-resources": "true" },
3137
+ React2.createElement(
3138
+ "section",
3139
+ { className: "wsr-sidebar-resource", "aria-label": "Workspace" },
3140
+ header("wsr-sidebar-workspace", "Workspace", workspaceExpanded, "workspace"),
3141
+ workspaceExpanded && React2.createElement("div", { id: "wsr-sidebar-workspace" }, React2.createElement(WorkspaceBrowser, props))
3142
+ ),
3143
+ React2.createElement(
3144
+ "section",
3145
+ { className: "wsr-sidebar-resource", "aria-label": "Delivery" },
3146
+ header("wsr-sidebar-delivery", "Delivery", deliveryExpanded, "delivery"),
3147
+ deliveryExpanded && React2.createElement("div", {
3148
+ id: "wsr-sidebar-delivery",
3149
+ role: view.kind === "error" ? "alert" : "region",
3150
+ "aria-live": "polite"
3151
+ }, view.kind === "ready" ? React2.createElement("div", { role: "list", "aria-label": "Deliveries" }, view.rows.map((row) => React2.createElement("button", {
3152
+ key: row.deliveryId,
3153
+ type: "button",
3154
+ role: "listitem",
3155
+ className: "wsr-delivery-row",
3156
+ "aria-current": row.selected ? "page" : void 0,
3157
+ "aria-label": `${row.label}, ${row.statusLabel}`,
3158
+ disabled: row.sessionId === null,
3159
+ onClick: row.sessionId === null ? void 0 : () => props.open(row.sessionId)
3160
+ }, React2.createElement("span", null, row.label), React2.createElement("span", {
3161
+ className: `wsr-delivery-status wsr-delivery-status-${row.availability}`
3162
+ }, row.statusLabel)))) : React2.createElement("div", { role: view.role }, view.label))
3163
+ )
3164
+ );
3165
+ };
3166
+ }
3167
+ function applyDeliverySidebar(ctx, { React: React2, workspaceUi: workspaceUi2, inventory }) {
3168
+ installStyle();
3169
+ const originalSlots = ctx.slots;
3170
+ const slots = Object.create(originalSlots);
3171
+ slots.register = (definition, component) => definition?.name === "sidebar.workspaces" ? originalSlots.register(definition, createSidebarResources(React2, component, inventory)) : originalSlots.register(definition, component);
3172
+ slots.inject = (name2, factory) => originalSlots.inject(name2, factory);
3173
+ const forked = new Proxy(ctx, { get(target, property) {
3174
+ return property === "slots" ? slots : Reflect.get(target, property);
3175
+ } });
3176
+ return workspaceUi2.apply(forked);
3177
+ }
3178
+
3179
+ // packages/execution/src/client/browser-entry.js
3180
+ var name = "wsr-execution-client";
3181
+ var inject = Object.freeze([
3182
+ "connection",
3183
+ "conversationEvents",
3184
+ "sessions",
3185
+ "slots",
3186
+ "workspaces",
3187
+ "locale"
3188
+ ]);
3189
+ function apply(ctx) {
3190
+ const controlPlane = createDeliveryControlPlaneClient(ctx.connection.rpc);
3191
+ const refresh = () => {
3192
+ void controlPlane.refresh();
3193
+ };
3194
+ refresh();
3195
+ const timer = setInterval(refresh, 2e3);
3196
+ ctx.effect(() => () => clearInterval(timer), "wsr-execution: control-plane refresh");
3197
+ applyDeliverySidebar(ctx, { React: import_react.default, workspaceUi, inventory: controlPlane.inventory });
3198
+ registerSessionDeliveryView(ctx, {
3199
+ React: import_react.default,
3200
+ bindProjection(sessionId) {
3201
+ const source = controlPlane.bindSession(String(sessionId));
3202
+ void source.refresh();
3203
+ return source;
3204
+ }
3205
+ });
3206
+ registerActionPresentation(ctx, createActionPresentationView({ React: import_react.default, DisclosureRow: import_dsh_client_ui_primitives.DisclosureRow, MessageText: import_dsh_client_ui_primitives.MessageText, StateDot: import_dsh_client_ui_primitives.StateDot }));
3207
+ }
3208
+
3209
+ return module.exports;
3210
+ },
3211
+ });