@aiti-ai/ext-shared 0.1.13 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,363 @@
1
+ /**
2
+ * PathBreadcrumb — a path bar with Windows Explorer behavior:
3
+ *
4
+ * - Display mode: every folder segment is a button (click = navigate to that level),
5
+ * the free space to their right is an "edit" hot area, and a copy button sits at the end.
6
+ * - Edit mode: the same field becomes a text input, selected as a whole (copy/paste as
7
+ * usual). Enter commits, Escape reverts (and only reverts: it never bubbles out to close
8
+ * the dialog), blur commits as Explorer does. Alt+D / Ctrl+L / F2 / Enter or typing any
9
+ * printable character enters edit mode, so "open the picker and type a path" still works.
10
+ *
11
+ * Pure split logic lives in ./path-crumbs.ts (unit tested); this file is presentation plus
12
+ * focus/commit plumbing. Consumers: directory pickers that want the bar (directory-picker).
13
+ */
14
+ import { useCallback, useEffect, useRef, useState, type CSSProperties } from "react";
15
+ import { splitPathSegments } from "./path-crumbs";
16
+
17
+ export interface PathBreadcrumbProps {
18
+ /** The current (resolved) folder — what the bar shows in display mode. */
19
+ value: string;
20
+ /** Accessible name of the bar (e.g. "Directory path"). */
21
+ label: string;
22
+ /** Accessible name/tooltip of the edit hot area. */
23
+ editLabel: string;
24
+ /** Optional hint under the edit hot area's tooltip. */
25
+ editHint?: string;
26
+ /** Accessible name/tooltip of the copy button. */
27
+ copyLabel: string;
28
+ /** Shown for ~1.2s after a successful copy. */
29
+ copiedLabel: string;
30
+ placeholder?: string;
31
+ /** Busy: segments and the edit hot area stop responding (the field stays readable). */
32
+ disabled?: boolean;
33
+ /** Focus the bar on mount (typing then enters edit mode directly). */
34
+ autoFocus?: boolean;
35
+ /** Navigate to an absolute path (segment click, Enter in edit mode, blur commit). */
36
+ onNavigate: (path: string) => void;
37
+ /** Lets the dialog disable its own actions while the field is being edited. */
38
+ onEditingChange?: (editing: boolean) => void;
39
+ style?: CSSProperties;
40
+ }
41
+
42
+ const BOX: CSSProperties = {
43
+ display: "flex",
44
+ alignItems: "center",
45
+ gap: 1,
46
+ minWidth: 0,
47
+ height: 36,
48
+ padding: "0 4px 0 6px",
49
+ border: "1px solid var(--border)",
50
+ borderRadius: 6,
51
+ background: "var(--bg-panel)",
52
+ color: "var(--text)",
53
+ fontFamily: "var(--font-mono)",
54
+ fontSize: 12,
55
+ boxSizing: "border-box",
56
+ };
57
+
58
+ const SEGMENT: CSSProperties = {
59
+ minWidth: 22,
60
+ maxWidth: 240,
61
+ height: 24,
62
+ padding: "0 4px",
63
+ border: 0,
64
+ borderRadius: 4,
65
+ background: "none",
66
+ color: "var(--text-muted)",
67
+ font: "inherit",
68
+ cursor: "pointer",
69
+ overflow: "hidden",
70
+ textOverflow: "ellipsis",
71
+ whiteSpace: "nowrap",
72
+ };
73
+
74
+ const ICON_BUTTON: CSSProperties = {
75
+ flexShrink: 0,
76
+ width: 24,
77
+ height: 24,
78
+ padding: 0,
79
+ display: "flex",
80
+ alignItems: "center",
81
+ justifyContent: "center",
82
+ border: 0,
83
+ borderRadius: 4,
84
+ background: "none",
85
+ color: "var(--text-dim)",
86
+ cursor: "pointer",
87
+ };
88
+
89
+ function CopyIcon() {
90
+ return (
91
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.3" aria-hidden="true">
92
+ <rect x="5.5" y="5.5" width="8" height="8" rx="1.2" />
93
+ <path d="M10.5 5.5v-1a1 1 0 0 0-1-1h-7a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1h1" />
94
+ </svg>
95
+ );
96
+ }
97
+
98
+ function CheckIcon() {
99
+ return (
100
+ <svg width="12" height="12" viewBox="0 0 16 16" fill="none" stroke="var(--accent)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
101
+ <polyline points="2.5 8.5 6 12 13.5 4" />
102
+ </svg>
103
+ );
104
+ }
105
+
106
+ /** Clipboard write with a pre-secure-context fallback (the picker must also work over plain http).
107
+ * Returns false when both paths failed, so the caller can fall back to selecting the text. */
108
+ async function writeClipboard(text: string): Promise<boolean> {
109
+ try {
110
+ if (navigator.clipboard?.writeText) {
111
+ await navigator.clipboard.writeText(text);
112
+ return true;
113
+ }
114
+ } catch {
115
+ /* fall through to execCommand */
116
+ }
117
+ const area = document.createElement("textarea");
118
+ area.value = text;
119
+ area.setAttribute("readonly", "");
120
+ area.style.position = "fixed";
121
+ area.style.top = "-1000px";
122
+ area.style.opacity = "0";
123
+ document.body.appendChild(area);
124
+ try {
125
+ area.select();
126
+ return document.execCommand("copy");
127
+ } catch {
128
+ return false;
129
+ } finally {
130
+ area.remove();
131
+ }
132
+ }
133
+
134
+ export function PathBreadcrumb(props: PathBreadcrumbProps) {
135
+ const { value, disabled = false, onNavigate } = props;
136
+ const [editing, setEditingState] = useState(false);
137
+ const [draft, setDraft] = useState("");
138
+ const [copied, setCopied] = useState(false);
139
+ const inputRef = useRef<HTMLInputElement | null>(null);
140
+ const hotRef = useRef<HTMLButtonElement | null>(null);
141
+ const editingRef = useRef(false);
142
+ const draftRef = useRef("");
143
+ const copyTimerRef = useRef<number | null>(null);
144
+ const mountedRef = useRef(true);
145
+ const propsRef = useRef(props);
146
+ propsRef.current = props;
147
+
148
+ const setEditing = useCallback((on: boolean) => {
149
+ editingRef.current = on;
150
+ setEditingState(on);
151
+ propsRef.current.onEditingChange?.(on);
152
+ }, []);
153
+
154
+ const enterEdit = useCallback((seed?: string) => {
155
+ if (propsRef.current.disabled) return;
156
+ // A printable character replaces the whole path (the field's content is selected, as in
157
+ // Explorer's address bar); Enter/Alt+D/Ctrl+L/first click just select it all.
158
+ const next = seed !== undefined ? seed : propsRef.current.value;
159
+ draftRef.current = next;
160
+ setDraft(next);
161
+ setEditing(true);
162
+ }, [setEditing]);
163
+
164
+ const commitEdit = useCallback(() => {
165
+ if (!editingRef.current) return;
166
+ const next = draftRef.current.trim();
167
+ setEditing(false);
168
+ if (next && next !== propsRef.current.value) propsRef.current.onNavigate(next);
169
+ }, [setEditing]);
170
+
171
+ const cancelEdit = useCallback(() => {
172
+ if (!editingRef.current) return;
173
+ setEditing(false);
174
+ }, [setEditing]);
175
+
176
+ // Focus and select the whole path once the input exists (Explorer: the address bar
177
+ // content is selected, so typing replaces it and Ctrl+C copies it).
178
+ useEffect(() => {
179
+ if (!editing) return;
180
+ const field = inputRef.current;
181
+ if (!field) return;
182
+ field.focus();
183
+ field.select();
184
+ }, [editing]);
185
+
186
+ useEffect(() => {
187
+ if (!editing && props.autoFocus) hotRef.current?.focus({ preventScroll: true });
188
+ }, [editing, props.autoFocus]);
189
+
190
+ useEffect(() => {
191
+ mountedRef.current = true;
192
+ return () => {
193
+ mountedRef.current = false;
194
+ if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current);
195
+ };
196
+ }, []);
197
+
198
+ const copyPath = useCallback(() => {
199
+ if (!propsRef.current.value) return;
200
+ void writeClipboard(propsRef.current.value).then((ok) => {
201
+ if (!mountedRef.current) return;
202
+ // Clipboard blocked (insecure origin / permission): open the field selected so the
203
+ // user can copy with the keyboard instead of the button doing nothing.
204
+ if (!ok) {
205
+ enterEdit();
206
+ return;
207
+ }
208
+ setCopied(true);
209
+ if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current);
210
+ copyTimerRef.current = window.setTimeout(() => {
211
+ if (mountedRef.current) setCopied(false);
212
+ }, 1200);
213
+ });
214
+ }, [enterEdit]);
215
+
216
+ const handleBarKeyDown = (event: {
217
+ key: string;
218
+ altKey: boolean;
219
+ ctrlKey: boolean;
220
+ metaKey: boolean;
221
+ preventDefault: () => void;
222
+ }) => {
223
+ if (editingRef.current || propsRef.current.disabled) return;
224
+ if (event.altKey && (event.key === "d" || event.key === "D")) {
225
+ event.preventDefault();
226
+ enterEdit();
227
+ return;
228
+ }
229
+ if ((event.ctrlKey || event.metaKey) && (event.key === "l" || event.key === "L")) {
230
+ event.preventDefault();
231
+ enterEdit();
232
+ return;
233
+ }
234
+ if (event.key === "Enter" || event.key === "F2") {
235
+ event.preventDefault();
236
+ enterEdit();
237
+ return;
238
+ }
239
+ // Type-to-edit: one printable character starts the edit with that character, keeping
240
+ // the picker's "open it and type a path" muscle memory without an always-on input.
241
+ if (event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) {
242
+ event.preventDefault();
243
+ enterEdit(event.key);
244
+ }
245
+ };
246
+
247
+ const split = splitPathSegments(value);
248
+ const copyTitle = copied ? props.copiedLabel : props.copyLabel;
249
+
250
+ return (
251
+ <div
252
+ className="path-breadcrumb"
253
+ role="group"
254
+ aria-label={props.label}
255
+ onKeyDown={handleBarKeyDown}
256
+ style={{ ...BOX, ...props.style }}
257
+ data-editing={editing ? "1" : undefined}
258
+ >
259
+ {editing ? (
260
+ <input
261
+ ref={inputRef}
262
+ className="path-breadcrumb-input"
263
+ type="text"
264
+ value={draft}
265
+ placeholder={props.placeholder}
266
+ autoComplete="off"
267
+ spellCheck={false}
268
+ aria-label={props.label}
269
+ onChange={(event) => {
270
+ draftRef.current = event.target.value;
271
+ setDraft(event.target.value);
272
+ }}
273
+ onKeyDown={(event) => {
274
+ if (event.nativeEvent.isComposing || event.keyCode === 229) return;
275
+ if (event.key === "Enter") {
276
+ event.preventDefault();
277
+ event.stopPropagation();
278
+ commitEdit();
279
+ return;
280
+ }
281
+ if (event.key === "Escape") {
282
+ // Edit mode's own Escape: revert and stay in the picker (never close it).
283
+ event.preventDefault();
284
+ event.stopPropagation();
285
+ cancelEdit();
286
+ }
287
+ }}
288
+ onBlur={commitEdit}
289
+ style={{ minWidth: 0, flex: 1, height: 28, padding: "0 8px", border: 0, outline: "none", background: "transparent", color: "var(--text)", fontFamily: "var(--font-mono)", fontSize: 12 }}
290
+ />
291
+ ) : value ? (
292
+ <>
293
+ {split.root && (
294
+ <button
295
+ type="button"
296
+ className="path-breadcrumb-segment is-root"
297
+ title={split.root.path}
298
+ disabled={disabled}
299
+ onClick={() => { if (split.root && split.root.path !== value) onNavigate(split.root.path); }}
300
+ style={{ ...SEGMENT, flexShrink: 0, color: "var(--text-muted)" }}
301
+ >
302
+ {split.root.label}
303
+ </button>
304
+ )}
305
+ {split.segments.map((segment, index) => {
306
+ const last = index === split.segments.length - 1;
307
+ // The root crumb already ends with the separator ("/" or "C:"): do not print it twice.
308
+ const showSep = split.root ? !(index === 0 && split.root.path.endsWith(split.sep)) : false;
309
+ return (
310
+ <span key={segment.path} style={{ display: "inline-flex", alignItems: "center", minWidth: 0, flexShrink: last ? 1 : 100 }}>
311
+ {showSep ? <span aria-hidden="true" style={{ flexShrink: 0, color: "var(--text-dim)" }}>{split.sep}</span> : null}
312
+ <button
313
+ type="button"
314
+ className={`path-breadcrumb-segment${last ? " is-current" : ""}`}
315
+ title={segment.path}
316
+ disabled={disabled}
317
+ onClick={() => { if (segment.path !== value) onNavigate(segment.path); }}
318
+ style={{ ...SEGMENT, color: last ? "var(--text)" : "var(--text-muted)", fontWeight: last ? 600 : 400, maxWidth: last ? undefined : 180 }}
319
+ >
320
+ {segment.label}
321
+ </button>
322
+ </span>
323
+ );
324
+ })}
325
+ <button
326
+ type="button"
327
+ ref={hotRef}
328
+ className="path-breadcrumb-edit-hot"
329
+ aria-label={props.editLabel}
330
+ title={props.editHint ?? props.editLabel}
331
+ autoFocus={props.autoFocus}
332
+ onClick={() => enterEdit()}
333
+ style={{ flex: 1, minWidth: 18, height: "100%", padding: 0, border: 0, background: "none", cursor: "text" }}
334
+ />
335
+ </>
336
+ ) : (
337
+ <button
338
+ type="button"
339
+ ref={hotRef}
340
+ className="path-breadcrumb-edit-hot"
341
+ aria-label={props.editLabel}
342
+ title={props.editHint ?? props.editLabel}
343
+ autoFocus={props.autoFocus}
344
+ onClick={() => enterEdit()}
345
+ style={{ flex: 1, minWidth: 18, height: "100%", padding: "0 8px", border: 0, background: "none", color: "var(--text-dim)", font: "inherit", textAlign: "left", cursor: "text" }}
346
+ >
347
+ {props.placeholder}
348
+ </button>
349
+ )}
350
+ <button
351
+ type="button"
352
+ className="path-breadcrumb-copy"
353
+ aria-label={copyTitle}
354
+ title={copyTitle}
355
+ disabled={disabled || !value || editing}
356
+ onClick={copyPath}
357
+ style={{ ...ICON_BUTTON, cursor: disabled || !value || editing ? "default" : "pointer", opacity: disabled || !value ? 0.5 : 1 }}
358
+ >
359
+ {copied ? <CheckIcon /> : <CopyIcon />}
360
+ </button>
361
+ </div>
362
+ );
363
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * path-crumbs tests — breadcrumb splitting is the only place that decides what a
3
+ * clickable folder segment is; the picker must stay correct on POSIX, Windows drive
4
+ * and UNC paths (the server may run on another platform than the browser).
5
+ */
6
+ import assert from "node:assert/strict";
7
+ import test from "node:test";
8
+ import { parentOfPath, splitPathSegments } from "./path-crumbs.ts";
9
+
10
+ test("POSIX absolute path: root plus cumulative segments", () => {
11
+ assert.deepEqual(splitPathSegments("/home/alice/projects"), {
12
+ sep: "/",
13
+ root: { label: "/", path: "/" },
14
+ segments: [
15
+ { label: "home", path: "/home" },
16
+ { label: "alice", path: "/home/alice" },
17
+ { label: "projects", path: "/home/alice/projects" },
18
+ ],
19
+ });
20
+ });
21
+
22
+ test("POSIX: trailing and duplicated separators do not create empty segments", () => {
23
+ const trailing = splitPathSegments("/a/b/");
24
+ assert.deepEqual(trailing.segments.map((s) => s.label), ["a", "b"]);
25
+ const duplicated = splitPathSegments("/a//b");
26
+ assert.deepEqual(duplicated.segments.map((s) => s.path), ["/a", "/a/b"]);
27
+ });
28
+
29
+ test("filesystem root and empty path", () => {
30
+ assert.deepEqual(splitPathSegments("/"), { sep: "/", root: { label: "/", path: "/" }, segments: [] });
31
+ assert.deepEqual(splitPathSegments(""), { sep: "/", root: null, segments: [] });
32
+ });
33
+
34
+ test("relative path: no root, cumulative segments still navigate the same levels", () => {
35
+ assert.deepEqual(splitPathSegments("home/wind"), {
36
+ sep: "/",
37
+ root: null,
38
+ segments: [
39
+ { label: "home", path: "home" },
40
+ { label: "wind", path: "home/wind" },
41
+ ],
42
+ });
43
+ });
44
+
45
+ test("Windows drive: drive root crumb, backslash separators", () => {
46
+ assert.deepEqual(splitPathSegments("C:\\Users\\me"), {
47
+ sep: "\\",
48
+ root: { label: "C:", path: "C:\\" },
49
+ segments: [
50
+ { label: "Users", path: "C:\\Users" },
51
+ { label: "me", path: "C:\\Users\\me" },
52
+ ],
53
+ });
54
+ });
55
+
56
+ test("Windows with forward slashes / duplicated separators / bare drive", () => {
57
+ const forward = splitPathSegments("C:/Users/me/");
58
+ assert.equal(forward.sep, "\\");
59
+ assert.deepEqual(forward.segments.map((s) => s.path), ["C:\\Users", "C:\\Users\\me"]);
60
+ assert.deepEqual(splitPathSegments("C:\\\\Users"), splitPathSegments("C:\\Users"));
61
+ assert.deepEqual(splitPathSegments("C:\\"), { sep: "\\", root: { label: "C:", path: "C:\\" }, segments: [] });
62
+ assert.deepEqual(splitPathSegments("C:"), { sep: "\\", root: { label: "C:", path: "C:\\" }, segments: [] });
63
+ });
64
+
65
+ test("UNC path: server/share is one root crumb", () => {
66
+ assert.deepEqual(splitPathSegments("\\\\server\\share\\team\\docs"), {
67
+ sep: "\\",
68
+ root: { label: "\\\\server\\share", path: "\\\\server\\share" },
69
+ segments: [
70
+ { label: "team", path: "\\\\server\\share\\team" },
71
+ { label: "docs", path: "\\\\server\\share\\team\\docs" },
72
+ ],
73
+ });
74
+ assert.deepEqual(splitPathSegments("\\\\server\\share"), {
75
+ sep: "\\",
76
+ root: { label: "\\\\server\\share", path: "\\\\server\\share" },
77
+ segments: [],
78
+ });
79
+ });
80
+
81
+ test("parentOfPath: one level up, never above a filesystem root", () => {
82
+ assert.equal(parentOfPath("/a/b/c"), "/a/b");
83
+ assert.equal(parentOfPath("/a"), "/");
84
+ assert.equal(parentOfPath("/"), null);
85
+ assert.equal(parentOfPath("C:\\a\\b"), "C:\\a");
86
+ assert.equal(parentOfPath("C:\\a"), "C:\\");
87
+ assert.equal(parentOfPath("C:\\"), null);
88
+ assert.equal(parentOfPath("\\\\server\\share\\a"), "\\\\server\\share");
89
+ assert.equal(parentOfPath("\\\\server\\share"), null);
90
+ assert.equal(parentOfPath(""), null);
91
+ });
package/path-crumbs.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Path crumbs — split an absolute path into clickable segments (Windows Explorer style).
3
+ *
4
+ * Pure, platform-agnostic: the path string decides the platform (POSIX `/a/b`, Windows
5
+ * drive `C:\a\b`, UNC `\\server\share\a`), never the caller's OS — the picker shows paths
6
+ * produced by the server, which may run on another platform.
7
+ *
8
+ * Consumers: extensions/_shared/path-breadcrumb.tsx (directory pickers that want a
9
+ * breadcrumb bar with an in-place edit mode).
10
+ */
11
+
12
+ export interface PathCrumb {
13
+ /** Text shown on the segment (a single folder name, the drive, the UNC root or "/"). */
14
+ label: string;
15
+ /** Full path up to and including this segment (what clicking it navigates to). */
16
+ path: string;
17
+ }
18
+
19
+ export interface PathSplit {
20
+ /** Separator the path itself uses, for rendering between segments. */
21
+ sep: string;
22
+ /** Root segment ("/" on POSIX, "C:" on Windows, "\\\\server\\share" on UNC); null for a relative path. */
23
+ root: PathCrumb | null;
24
+ /** Segments below the root, in path order. */
25
+ segments: PathCrumb[];
26
+ }
27
+
28
+ const DRIVE_RE = /^[a-zA-Z]:/;
29
+
30
+ function isWindowsPath(value: string): boolean {
31
+ if (value.startsWith("\\\\")) return true; // UNC
32
+ if (DRIVE_RE.test(value)) return true; // C:\…, C:/…, bare C:
33
+ // A backslash-only path that does not look like POSIX.
34
+ return !value.startsWith("/") && value.includes("\\") && !value.includes("/");
35
+ }
36
+
37
+ function splitPosix(value: string): PathSplit {
38
+ const absolute = value.startsWith("/");
39
+ const parts = value.split("/").filter(Boolean);
40
+ let acc = "";
41
+ const segments: PathCrumb[] = [];
42
+ for (const part of parts) {
43
+ acc = acc ? `${acc}/${part}` : absolute ? `/${part}` : part;
44
+ segments.push({ label: part, path: acc });
45
+ }
46
+ // The root is a segment of its own only for absolute paths (and never duplicated by
47
+ // an empty first part: filter(Boolean) above already dropped it).
48
+ return { sep: "/", root: absolute ? { label: "/", path: "/" } : null, segments };
49
+ }
50
+
51
+ function splitWindows(value: string): PathSplit {
52
+ // Keep the UNC prefix intact: collapsing separators first would turn \\server into \server.
53
+ const unc = value.startsWith("\\\\");
54
+ const normalized = unc
55
+ ? "\\\\" + value.slice(2).replace(/[\\/]+/g, "\\")
56
+ : value.replace(/[\\/]+/g, "\\");
57
+ let root: PathCrumb | null = null;
58
+ let acc = "";
59
+ let rest = normalized;
60
+ if (unc) {
61
+ // UNC: \\server\share is the root ("This PC" > server > share collapses to one crumb).
62
+ const parts = normalized.slice(2).split("\\").filter(Boolean);
63
+ const server = parts.shift() ?? "";
64
+ const share = parts.shift() ?? "";
65
+ const rootPath = share ? `\\\\${server}\\${share}` : server ? `\\\\${server}` : "\\\\";
66
+ root = { label: rootPath, path: rootPath };
67
+ acc = rootPath;
68
+ rest = parts.length > 0 ? "\\" + parts.join("\\") : "";
69
+ } else {
70
+ const drive = DRIVE_RE.exec(normalized)?.[0] ?? null;
71
+ if (drive) {
72
+ const rootPath = `${drive}\\`;
73
+ root = { label: drive, path: rootPath };
74
+ acc = drive;
75
+ rest = normalized.slice(drive.length);
76
+ }
77
+ }
78
+ const parts = rest.split("\\").filter(Boolean);
79
+ const segments: PathCrumb[] = [];
80
+ for (const part of parts) {
81
+ acc = acc ? `${acc}\\${part}` : part;
82
+ segments.push({ label: part, path: acc });
83
+ }
84
+ return { sep: "\\", root, segments };
85
+ }
86
+
87
+ /** Split a path into breadcrumb segments (root + folder segments). */
88
+ export function splitPathSegments(input: string): PathSplit {
89
+ const value = typeof input === "string" ? input : "";
90
+ if (!value) return { sep: "/", root: null, segments: [] };
91
+ return isWindowsPath(value) ? splitWindows(value) : splitPosix(value);
92
+ }
93
+
94
+ /** The parent folder the "up" button navigates to (null at a filesystem root). */
95
+ export function parentOfPath(input: string): string | null {
96
+ const value = typeof input === "string" ? input : "";
97
+ if (!value) return null;
98
+ const { sep, root, segments } = splitPathSegments(value);
99
+ if (segments.length === 0) return null;
100
+ if (segments.length === 1) return root ? root.path : null;
101
+ return segments[segments.length - 2].path;
102
+ }
@@ -50,12 +50,13 @@ test("wire:request/response id 关联 + 错误帧 reject", async () => {
50
50
  const p = h.request({ type: "get_state" });
51
51
  await later();
52
52
  assert.equal(child.frames()[0].type, "get_state");
53
- feed(h, { id: "r1", type: "response", command: "?", success: true, data: { ok: 1 } });
53
+ // Ids carry a per-instance salt (2026-11-22): read the id off the wire instead of assuming a format.
54
+ feed(h, { id: child.frames()[0].id, type: "response", command: "?", success: true, data: { ok: 1 } });
54
55
  assert.deepEqual(await p, { ok: 1 });
55
56
 
56
57
  const p2 = h.request({ type: "get_state" });
57
58
  await later();
58
- feed(h, { id: "r2", type: "response", command: "get_state", success: false, error: "boom" });
59
+ feed(h, { id: child.frames()[1].id, type: "response", command: "get_state", success: false, error: "boom" });
59
60
  await assert.rejects(p2, /boom/);
60
61
  });
61
62
 
@@ -156,7 +157,7 @@ test("wire:request 超时 reject + 响应/死亡清定时器(审查 P1-4 回
156
157
  // 正常响应路径不受超时影响
157
158
  const p = h.request({ type: "get_state" }, { timeoutMs: 5_000 });
158
159
  await later();
159
- feed(h, { id: "r2", type: "response", command: "get_state", success: true, data: { ok: 1 } });
160
+ feed(h, { id: child.frames()[1].id, type: "response", command: "get_state", success: true, data: { ok: 1 } });
160
161
  assert.deepEqual(await p, { ok: 1 });
161
162
  });
162
163
 
@@ -59,6 +59,19 @@ export function lineReader(
59
59
 
60
60
  export type HostEventListener = (event: Record<string, unknown>) => void;
61
61
 
62
+ /** Frame-level trace (request/response correlation, disposition included) — lost-message
63
+ * forensics (2026-11-22 steer-loss). Default: on outside production builds; force with
64
+ * PI_FORK_RPC_DEBUG=1, force off with =0. One line per frame, never logs message text. */
65
+ function traceWire(line: string): void {
66
+ const flag = process.env.PI_FORK_RPC_DEBUG;
67
+ const enabled = flag === "1" || flag === "true"
68
+ ? true
69
+ : flag === "0" || flag === "false"
70
+ ? false
71
+ : process.env.NODE_ENV !== "production";
72
+ if (enabled) console.log(`[fork-rpc-wire] ${line}`);
73
+ }
74
+
62
75
  interface PendingRequest {
63
76
  resolve(v: unknown): void;
64
77
  reject(e: Error): void;
@@ -79,6 +92,12 @@ export class RpcChildHost {
79
92
  protected child: ChildProcess;
80
93
  protected pending = new Map<string, PendingRequest>();
81
94
  protected seq = 0;
95
+ /** Per-instance id salt: an attach replays the wrapper journal into this wire —
96
+ * the OLD handle's responses ("r1", "r2", …) would collide with this wire's
97
+ * fresh ids and resolve pending requests with stale acks (2026-11-22
98
+ * steer-loss forensics: replayed and live frames interleaved in the same
99
+ * millisecond window). The salt makes replayed ids unmatchable. */
100
+ private seqSalt = Math.floor(Math.random() * 0xffffffff).toString(36);
82
101
  protected aliveFlag = true;
83
102
  private listeners = new Set<HostEventListener>();
84
103
  private detachReader: (() => void) | null = null;
@@ -99,6 +118,14 @@ export class RpcChildHost {
99
118
  child.stdout?.on("error", (err: Error) => this.markDead(`stdout error: ${err.message}`));
100
119
  child.stderr?.on("error", (err: Error) => console.log(`[rpc-child] stderr error: ${err.message}`));
101
120
  child.stdin?.on("error", (err: Error) => console.log(`[rpc-child] stdin error: ${err.message}`));
121
+ // Wrapper facades (SocketChild) report the real cause on "dropped" before the
122
+ // synthetic exit — "superseded" (single-writer slot taken by a newer client),
123
+ // "socket closed", or the socket error message. Listen first so markDead carries
124
+ // a diagnosable reason instead of the generic "process exited (signal)"
125
+ // (markDead is idempotent; the later exit event is a no-op).
126
+ (child as unknown as { once: (ev: string, cb: (reason: unknown) => void) => unknown }).once("dropped", (reason) => {
127
+ if (typeof reason === "string" && reason) this.markDead(reason);
128
+ });
102
129
  child.once("exit", (code) => this.markDead(`process exited (${code ?? "signal"})`));
103
130
  child.once("error", (err) => this.markDead(`process error: ${err.message}`));
104
131
  }
@@ -128,13 +155,15 @@ export class RpcChildHost {
128
155
  if (!this.aliveFlag || !this.child.stdin?.writable) {
129
156
  return Promise.reject(new Error("[rpc-child] not running"));
130
157
  }
131
- const id = `r${++this.seq}`;
158
+ const id = `r${this.seqSalt}-${++this.seq}`;
159
+ traceWire(`→ #${id} ${String(command.type ?? "?")}${command.streamingBehavior ? `:${String(command.streamingBehavior)}` : ""}`);
132
160
  return new Promise<T>((resolve, reject) => {
133
161
  const pending: PendingRequest = { resolve: resolve as (v: unknown) => void, reject };
134
162
  const timeoutMs = opts?.timeoutMs;
135
163
  if (timeoutMs && timeoutMs > 0) {
136
164
  const timer = setTimeout(() => {
137
165
  this.pending.delete(id);
166
+ traceWire(`⏱ #${id} ${String(command.type ?? "?")} timeout after ${timeoutMs}ms`);
138
167
  reject(new Error(`[rpc-child] timeout: ${String(command.type ?? "?")} after ${timeoutMs}ms`));
139
168
  }, timeoutMs);
140
169
  timer.unref?.();
@@ -145,6 +174,7 @@ export class RpcChildHost {
145
174
  this.child.stdin!.write(JSON.stringify({ ...command, id }) + "\n");
146
175
  } catch (e) {
147
176
  this.pending.delete(id);
177
+ traceWire(`✗ #${id} ${String(command.type ?? "?")} stdin write failed`);
148
178
  if (pending.timer) clearTimeout(pending.timer);
149
179
  reject(new Error(`[rpc-child] write failed: ${e instanceof Error ? e.message : String(e)}`));
150
180
  }
@@ -171,9 +201,16 @@ export class RpcChildHost {
171
201
  }
172
202
  if (msg.type === "response" && typeof msg.id === "string") {
173
203
  const p = this.pending.get(msg.id);
174
- if (!p) return;
204
+ if (!p) {
205
+ // Replayed-journal response with no live pending (attach replay) — trace
206
+ // at debug level so lost-message forensics can tell replay apart from live.
207
+ traceWire(`← #${msg.id} response (no pending: replay or stale)`);
208
+ return;
209
+ }
175
210
  this.pending.delete(msg.id);
176
211
  if (p.timer) clearTimeout(p.timer);
212
+ const data = msg.data as Record<string, unknown> | undefined;
213
+ traceWire(`← #${msg.id} ${String(msg.command ?? "?")} ok=${msg.success === true}${data && typeof data === "object" && "disposition" in data ? ` disposition=${String((data as { disposition?: unknown }).disposition)}` : ""}`);
177
214
  if (msg.success === true) p.resolve(msg.data);
178
215
  else p.reject(new Error(String(msg.error ?? "request failed")));
179
216
  return;