dsh-open-in-dsh 0.3.5 → 0.3.7

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/README.md CHANGED
@@ -45,6 +45,7 @@ pwsh -File "$env:USERPROFILE\.dsh\profiles\<profile>\node_modules\dsh-open-in-ds
45
45
  - `-Action status`:只查看当前注册与解析结果;`-Action uninstall`:移除。
46
46
  - 不带 `-Port` / `-App` 就是自动:桌面版只把「每次点击时现场发现端口」这件事写进动词(存的是 `0`),并记住应用路径;没有桌面版时退回 `dsh web`(3080)+ 浏览器 URL。也可以显式钉住:`-Port 3080 -App <exe 路径>`。
47
47
  - 写入两个 HKCU 动词:`Directory\shell\DSHOpen`(右键文件夹)与 `Directory\Background\shell\DSHOpen`(右键文件夹空白处)。
48
+ - **Windows 11 26H2(build 26200/26300,KB5127936 起)**:新版资源管理器右键菜单把第三方入口统一收进「应用扩展」子菜单,且只收录打包的 `IExplorerCommand` 扩展;传统注册表动词不再出现在新菜单里。DSH 这条动词仍在,只是要走经典菜单——**Shift+右键**,或在 设置 → 个性化 → 上下文菜单 → 其他选项 打开「显示更多选项」让右键默认走经典菜单。要直接进「应用扩展」得做 MSIX/sparse package,不在本插件范围内。
48
49
  - 装完重启一次资源管理器:Explorer 按进程缓存右键菜单,不重启看不到新条目。
49
50
 
50
51
  **macOS**
package/lib/client.js CHANGED
@@ -438,6 +438,9 @@ window.__ModuleLoader__.load({
438
438
  // so the instance is captured through an injection of its own.
439
439
  ctx.inject(['uiWorkspace'], (scoped) => {
440
440
  uiWorkspace = scoped.get('uiWorkspace');
441
+ return () => {
442
+ uiWorkspace = null;
443
+ };
441
444
  });
442
445
  // Menu labels come from the package's locale files, inlined into this
443
446
  // bundle at build time: a right-click never waits on a dictionary fetch.
@@ -689,6 +692,11 @@ window.__ModuleLoader__.load({
689
692
  readyState: source === null ? null : source.readyState,
690
693
  }),
691
694
  };
695
+ ctx.effect(() => () => {
696
+ if (typeof window !== 'undefined' && '__dshOpenIn' in window) {
697
+ delete window.__dshOpenIn;
698
+ }
699
+ }, 'dsh-open-in-dsh: debug hook');
692
700
  }
693
701
  return { inject: ['workspaces', 'sessions', 'contextMenus', 'locale', 'slots'], apply };
694
702
  }
package/lib/index.js CHANGED
@@ -40,6 +40,7 @@
40
40
  import { execFile } from 'node:child_process';
41
41
  import { chmodSync, existsSync, mkdirSync, readdirSync, statSync, unlinkSync } from 'node:fs';
42
42
  import { createServer } from 'node:http';
43
+ import { createConnection } from 'node:net';
43
44
  import { homedir } from 'node:os';
44
45
  import { dirname, isAbsolute, join, resolve } from 'node:path';
45
46
  import z from '@deepseek-ai/schemastery';
@@ -344,7 +345,6 @@ export function apply(ctx, rawConfig = {}) {
344
345
  host.effect(() => host.webServer.register({
345
346
  kind: 'exact',
346
347
  path: ROUTE_EVENTS,
347
- auth: 'anonymous',
348
348
  handler: createEventsHandler(ctx, hub, allowNonLoopback),
349
349
  }), 'dsh-open-in-dsh: events route');
350
350
  host.effect(() => host.webServer.register({
@@ -356,19 +356,16 @@ export function apply(ctx, rawConfig = {}) {
356
356
  host.effect(() => host.webServer.register({
357
357
  kind: 'exact',
358
358
  path: ROUTE_APPS,
359
- auth: 'anonymous',
360
359
  handler: createAppsHandler(allowNonLoopback),
361
360
  }), 'dsh-open-in-dsh: apps route');
362
361
  host.effect(() => host.webServer.register({
363
362
  kind: 'exact',
364
363
  path: ROUTE_OPEN_WITH,
365
- auth: 'anonymous',
366
364
  handler: createOpenWithHandler(ctx, allowNonLoopback),
367
365
  }), 'dsh-open-in-dsh: open-with route');
368
366
  host.effect(() => host.webServer.register({
369
367
  kind: 'exact',
370
368
  path: ROUTE_OPEN_SESSION,
371
- auth: 'anonymous',
372
369
  handler: createOpenSessionHandler(ctx, allowNonLoopback, {
373
370
  resolveCwd: (sessionId) => resolveSessionCwd(sessionId, { live: createLiveCwdReader(ctx) }),
374
371
  }),
@@ -401,8 +398,8 @@ export function createHub(options = {}) {
401
398
  ? Number(options.backlogTtlMs)
402
399
  : DEFAULT_BACKLOG_TTL_MS;
403
400
  const now = typeof options.now === 'function' ? options.now : () => Date.now();
404
- /** Live `text/event-stream` responses, each one an open DSH page. */
405
- const streams = new Set();
401
+ /** Live `text/event-stream` responses with their heartbeat/detach disposers. */
402
+ const streams = new Map();
406
403
  /** Newest-last request rows, bounded and time-filtered on read. */
407
404
  const backlog = [];
408
405
  /** When a page last attached or detached; 0 until the first one ever. */
@@ -420,7 +417,7 @@ export function createHub(options = {}) {
420
417
  while (backlog.length > MAX_BACKLOG)
421
418
  backlog.shift();
422
419
  const frame = sseFrame('request', entry);
423
- for (const stream of streams)
420
+ for (const stream of streams.keys())
424
421
  write(stream, frame);
425
422
  return entry;
426
423
  }
@@ -440,7 +437,6 @@ export function createHub(options = {}) {
440
437
  * @returns a disposer that detaches and stops the heartbeat.
441
438
  */
442
439
  function subscribe(response) {
443
- streams.add(response);
444
440
  lastSeenAt = now();
445
441
  const beat = setInterval(() => write(response, ': ping\n\n'), HEARTBEAT_MS);
446
442
  if (typeof beat.unref === 'function')
@@ -454,6 +450,7 @@ export function createHub(options = {}) {
454
450
  streams.delete(response);
455
451
  lastSeenAt = now();
456
452
  };
453
+ streams.set(response, stop);
457
454
  response.on('close', stop);
458
455
  response.on('error', stop);
459
456
  return stop;
@@ -464,8 +461,13 @@ export function createHub(options = {}) {
464
461
  }
465
462
  /** Drop every follower; called when the plugin unloads. */
466
463
  function close() {
467
- for (const stream of streams)
468
- write(stream, '');
464
+ for (const [stream, stop] of Array.from(streams.entries())) {
465
+ stop();
466
+ try {
467
+ stream.end?.();
468
+ }
469
+ catch { }
470
+ }
469
471
  streams.clear();
470
472
  }
471
473
  return {
@@ -513,10 +515,12 @@ export function expectsPage(hub, now = Date.now()) {
513
515
  * @param socketPath - absolute socket path; empty disables the transport.
514
516
  * @returns disposer that closes the server and removes the socket file.
515
517
  */
516
- function startHandoffSocket(ctx, hub, allowNonLoopback, socketPath) {
518
+ export function startHandoffSocket(ctx, hub, allowNonLoopback, socketPath) {
517
519
  const path = typeof socketPath === 'string' ? socketPath.trim() : '';
518
520
  if (path === '')
519
521
  return () => { };
522
+ if (process.platform === 'win32' && path === DEFAULT_SOCKET_PATH)
523
+ return () => { };
520
524
  if (!isAbsolute(path)) {
521
525
  ctx.logger?.warn?.('dsh-open-in-dsh: socketPath is not absolute, handoff socket disabled: %s', path);
522
526
  return () => { };
@@ -548,23 +552,50 @@ function startHandoffSocket(ctx, hub, allowNonLoopback, socketPath) {
548
552
  });
549
553
  let closed = false;
550
554
  let replaced = false;
555
+ let listening = false;
551
556
  server.on('error', (error) => {
552
557
  if (closed)
553
558
  return;
554
- // A crashed host leaves the file behind. A live one never lets us bind, so
555
- // the stale file is safe to replace exactly once.
559
+ // Probe before unlinking: only a stale dead socket file may be replaced.
556
560
  if (error?.code === 'EADDRINUSE' && !replaced) {
557
- replaced = true;
558
- try {
559
- unlinkSync(path);
560
- }
561
- catch { }
562
- server.listen(path);
561
+ const probe = createConnection(path);
562
+ if (typeof probe.unref === 'function')
563
+ probe.unref();
564
+ let handled = false;
565
+ probe.once('connect', () => {
566
+ if (handled)
567
+ return;
568
+ handled = true;
569
+ probe.end();
570
+ if (closed)
571
+ return;
572
+ ctx.logger?.warn?.('dsh-open-in-dsh: handoff socket already active (%s)', path);
573
+ });
574
+ probe.on('error', (probeError) => {
575
+ if (handled)
576
+ return;
577
+ handled = true;
578
+ probe.destroy();
579
+ if (closed)
580
+ return;
581
+ if (probeError?.code === 'ECONNREFUSED' || probeError?.code === 'ENOENT') {
582
+ replaced = true;
583
+ try {
584
+ unlinkSync(path);
585
+ }
586
+ catch { }
587
+ if (!closed)
588
+ server.listen(path);
589
+ return;
590
+ }
591
+ ctx.logger?.warn?.('dsh-open-in-dsh: handoff socket failed (%s): %s', path, messageOf(probeError));
592
+ });
563
593
  return;
564
594
  }
565
595
  ctx.logger?.warn?.('dsh-open-in-dsh: handoff socket failed (%s): %s', path, messageOf(error));
566
596
  });
567
597
  server.on('listening', () => {
598
+ listening = true;
568
599
  try {
569
600
  // The file mode is the access policy: only this user may hand paths over.
570
601
  chmodSync(path, 0o600);
@@ -587,10 +618,12 @@ function startHandoffSocket(ctx, hub, allowNonLoopback, socketPath) {
587
618
  server.close();
588
619
  }
589
620
  catch { }
590
- try {
591
- unlinkSync(path);
621
+ if (listening) {
622
+ try {
623
+ unlinkSync(path);
624
+ }
625
+ catch { }
592
626
  }
593
- catch { }
594
627
  };
595
628
  }
596
629
  /**
@@ -1108,11 +1141,15 @@ function write(stream, text) {
1108
1141
  export function directoryPath(value) {
1109
1142
  if (typeof value !== 'string')
1110
1143
  return null;
1144
+ if (value.includes('\0'))
1145
+ return null;
1111
1146
  let text = value.trim().replace(/^"|"$/g, '');
1112
1147
  if (text === '')
1113
1148
  return null;
1114
1149
  if (/^[A-Za-z]:$/.test(text))
1115
1150
  text = `${text}\\`;
1151
+ if (!isAbsolute(text) && !/^[A-Za-z]:[\\/]/.test(text))
1152
+ return null;
1116
1153
  if (text.length > 3)
1117
1154
  text = text.replace(/[\\/]+$/, '');
1118
1155
  try {
@@ -32,6 +32,7 @@ export type ReadDirFn = (path: string, options: {
32
32
  /** What an SSE follower must offer the hub; a `ServerResponse` does. */
33
33
  export interface EventStream {
34
34
  write(text: string): unknown;
35
+ end?(): unknown;
35
36
  on(event: string, listener: () => void): unknown;
36
37
  }
37
38
  /** One incoming HTTP request handler, as `webServer.register` takes it. */
@@ -41,11 +42,10 @@ export type WebAuthPolicy = 'anonymous' | 'required' | 'deny';
41
42
  /**
42
43
  * The exact-route row this plugin registers.
43
44
  *
44
- * Every route here is a loopback-fenced callback for this machine's own
45
- * launcher scripts (Finder/Explorer, macOS `open` helper) rather than a page
46
- * fetch, so each one declares `auth: 'anonymous'`: DSH 0.2.2-rc.2 made
47
- * `required` the default and the TCP launchers have no cookie to present
48
- * (`401`). The handlers keep their own loopback + same-origin fences.
45
+ * The launcher callbacks (`/open`, `/status`) declare `auth: 'anonymous'`
46
+ * because external Finder/Explorer scripts have no browser session cookie.
47
+ * Browser-only endpoints (`/events`, `/apps`, `/open-with`, `/open-session`)
48
+ * omit `auth` so DSH 0.2.2-rc.2+'s default `'required'` cookie gate stays active.
49
49
  */
50
50
  export interface ExactRoute {
51
51
  kind: 'exact';
@@ -390,6 +390,28 @@ export declare function createHub(options?: HubOptions): Hub;
390
390
  * @returns true when the launcher should wait rather than open a window.
391
391
  */
392
392
  export declare function expectsPage(hub: Hub, now?: number): boolean;
393
+ /**
394
+ * Serve the launcher's open route on a Unix domain socket.
395
+ *
396
+ * Why a second transport: on macOS nothing outside the Electron renderer can
397
+ * reach the Desktop shell's web server (it rejects those requests before route
398
+ * matching), and 2.0.19 removed the `--dsh-desktop-workspace` launch argument
399
+ * that used to carry a folder into the app — passing it now makes Chromium's own
400
+ * option parser exit with "bad option". A socket owned by this user, mode 0600,
401
+ * is the one channel the Finder Quick Action shares with the running app.
402
+ *
403
+ * The request shape is the HTTP route's on purpose: one handler, two transports,
404
+ * so the launcher reuses its JSON body and the page never learns which one
405
+ * delivered the path. A request that arrives after a cold start is still
406
+ * replayable through the hub's backlog, exactly like the port version.
407
+ *
408
+ * @param ctx - host plugin context, for logs.
409
+ * @param hub - the shared request hub.
410
+ * @param allowNonLoopback - kept for symmetry; a socket peer is always local.
411
+ * @param socketPath - absolute socket path; empty disables the transport.
412
+ * @returns disposer that closes the server and removes the socket file.
413
+ */
414
+ export declare function startHandoffSocket(ctx: HostContext, hub: Hub, allowNonLoopback: boolean, socketPath: string | undefined): () => void;
393
415
  /**
394
416
  * Build the menu's availability route.
395
417
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-open-in-dsh",
3
- "version": "0.3.5",
3
+ "version": "0.3.7",
4
4
  "private": false,
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -19,11 +19,11 @@
19
19
  "default": "./lib/client.js"
20
20
  },
21
21
  "./package.json": "./package.json",
22
- "./locale/*.json": "./locale/*.json"
22
+ "./locale/*.json": "./locale/*.json",
23
+ "./icon": "./assets/icon.svg"
23
24
  },
24
25
  "files": [
25
26
  "lib",
26
- "client",
27
27
  "scripts",
28
28
  "assets",
29
29
  "locale",
@@ -42,11 +42,8 @@
42
42
  "node": ">=24",
43
43
  "dsh": "^0.2.1-rc.2 || ^0.2.2-alpha.2 || ^0.2.3-alpha.1"
44
44
  },
45
- "dependencies": {
46
- "@deepseek-ai/schemastery": "^3.18.5"
47
- },
48
45
  "peerDependencies": {
49
- "@deepseek-ai/schemastery": "^3.18.5",
46
+ "@deepseek-ai/schemastery": "^3.18.5 || ^3.18.6-alpha.1",
50
47
  "dsh-session-ops": ">=0.1.0"
51
48
  },
52
49
  "keywords": [
@@ -15,11 +15,17 @@
15
15
  HKCU, not HKLM: nothing here needs elevation, and a per-user verb is the
16
16
  right blast radius for a personal tool.
17
17
 
18
- Windows 11: measured on build 26200, a classic verb registered this way does
19
- appear in the trimmed top-level menu (next to PowerShell 7 and VS Code), not
20
- only under "显示更多选项". No MSIX sparse package or `IExplorerCommand` is
21
- needed for this machine's build. Explorer caches context menus per process,
22
- so restart the shell once after installing.
18
+ Windows 11 26H2 (build 26200/26300 with KB5127936, 2026-10-28) redesigned
19
+ the Explorer context menu. A plain right-click now shows a compact menu whose
20
+ only third-party slot is the "应用扩展" submenu, and that submenu lists
21
+ packaged IExplorerCommand extensions only. A classic `Directory\shell` verb
22
+ like this one is therefore NOT shown there; it stays reachable from the
23
+ classic menu -- Shift+right-click, or right-click then 显示更多选项 after
24
+ enabling it in 设置 -> 个性化 -> 上下文菜单 -> 其他选项. Surfacing in the new
25
+ menu would need an MSIX/sparse package implementing IExplorerCommand, which
26
+ is out of scope for this script.
27
+ Explorer caches context menus per process, so restart the shell once after
28
+ installing.
23
29
 
24
30
  .PARAMETER Action
25
31
  install, uninstall, or status.
@@ -222,5 +228,7 @@ if ($verbApp -ne '') {
222
228
  }
223
229
  if (Test-Path -LiteralPath $iconPath) { Write-Output " icon: $iconPath" }
224
230
  Write-Output ''
225
- Write-Output 'Windows 11: restart Explorer (or sign out and back in) once so the'
226
- Write-Output 'shell rebuilds its context-menu cache, then right-click any folder.'
231
+ Write-Output 'Windows 11 26H2+: the compact menu keeps classic verbs out of the top'
232
+ Write-Output 'level. Use Shift+right-click, or enable 设置 -> 个性化 -> 上下文菜单 ->'
233
+ Write-Output '其他选项 -> 显示更多选项 to make right-click open the classic menu.'
234
+ Write-Output 'Restart Explorer once so the shell rebuilds its context-menu cache.'
@@ -1,4 +1,4 @@
1
- <#
1
+ <#
2
2
  .SYNOPSIS
3
3
  Explorer verb launcher: hand one folder to the running DSH host.
4
4
 
@@ -297,8 +297,9 @@ $script:lastError = ''
297
297
  <# POST the folder; $null when nothing accepted it. #>
298
298
  function Send-Open([int]$HostPort) {
299
299
  try {
300
+ $bytes = [System.Text.Encoding]::UTF8.GetBytes($payload)
300
301
  return (Invoke-RestMethod -Uri "http://127.0.0.1:$HostPort/dsh-open-in-dsh/api/v1/open" `
301
- -Method Post -ContentType 'application/json' -Body $payload -TimeoutSec 5)
302
+ -Method Post -ContentType 'application/json; charset=utf-8' -Body $bytes -TimeoutSec 5)
302
303
  } catch {
303
304
  $script:lastError = $_.Exception.Message
304
305
  return $null
@@ -1,44 +0,0 @@
1
- /**
2
- * Ambient browser globals for the DSH client bundle.
3
- *
4
- * `client/index.ts` is a classic script, not a module: it has no import/export,
5
- * so `tsc` emits it as-is and `scripts/build-client.mts` splices the emitted
6
- * text into the body of the factory `window.__ModuleLoader__.load({ id,
7
- * factory })` registers. This file only describes the globals that contract
8
- * itself puts on `window`; DOM types come from the `DOM` lib.
9
- */
10
-
11
- /** One lazy module registration accepted by `window.__ModuleLoader__.load`. */
12
- interface DshModuleLoaderRegistration {
13
- /** Package name the bundle registers under (`dsh-open-in-dsh`). */
14
- id: string
15
- /** Runs once on first require; its return value is the module's exports. */
16
- factory: (require: (id: string) => unknown) => unknown
17
- }
18
-
19
- /** The devtools/console surface the browser half exposes for troubleshooting. */
20
- interface DshOpenInDebug {
21
- /** The Host route the stream follows. */
22
- route: string
23
- /** Make one folder the current Workspace (and land in a blank Session). */
24
- open: (path: string) => Promise<void>
25
- /** Ask the Host to launch one allowlisted app on a path. */
26
- openWith: (app: string, path: string) => Promise<void>
27
- /** A snapshot of the stream state, for `console.log(__dshOpenIn.status())`. */
28
- status: () => {
29
- lastSeq: number
30
- /** The live synced setting: read from the Host reference on each call. */
31
- settings: { alwaysNewSession: boolean }
32
- uiWorkspace: boolean
33
- readyState: number | null
34
- }
35
- }
36
-
37
- interface Window {
38
- /** The DSH client module system: executes plugin bundles as classic scripts. */
39
- __ModuleLoader__: {
40
- load(registration: DshModuleLoaderRegistration): void
41
- }
42
- /** Troubleshooting hook, callable from the devtools console. */
43
- __dshOpenIn: DshOpenInDebug
44
- }
package/client/index.ts DELETED
@@ -1,736 +0,0 @@
1
- /**
2
- * `dsh-open-in-dsh` browser half.
3
- *
4
- * Shipped as the package's `./client` bundle: the DSH client module system
5
- * loads it as a `window.__ModuleLoader__.load({ id, factory })` script, calls
6
- * `factory(require)`, and mounts the exported plugin (`apply`) into the browser
7
- * Cordis tree.
8
- *
9
- * What it does: follow the host half's request stream, and for every folder the
10
- * Explorer verb announced, make that folder the current Workspace and land in a
11
- * blank Session. All three steps are the Client's own services — the same ones
12
- * the sidebar calls — so grouping, ordering and the "current Session" store
13
- * behave exactly as they do for a click:
14
- *
15
- * ctx.workspaces.create({ path }) register-or-resolve by path
16
- * ctx.sessions.create({ workspaceId }) a fresh blank Session
17
- * ctx.uiWorkspace.openSession(sessionId) select it and show its Conversation
18
- *
19
- * The stream is SSE for one reason: Chrome throttles a hidden page's timers to
20
- * once a minute, and right after a right-click this page is hidden behind
21
- * Explorer. A pushed frame still runs.
22
- *
23
- * @module dsh-open-in-dsh/client
24
- */
25
-
26
- /**
27
- * Parse one SSE `data:` payload.
28
- * @param text - raw frame data.
29
- * @returns the parsed object, or null when the frame is not readable JSON.
30
- */
31
- function parseFrame(text) {
32
- try {
33
- const value = JSON.parse(text)
34
- return value !== null && typeof value === 'object' ? value : null
35
- } catch {
36
- return null
37
- }
38
- }
39
-
40
- /**
41
- * One field of this plugin's Host config, as the kernel syncs it.
42
- *
43
- * Mirrors `SyncedConfigRef<T>` from `@deepseek-ai/dsh-client-config/types`
44
- * without importing it: the browser half is spliced into a classic script by
45
- * `scripts/build-client.mts` and carries no package dependency of its own. A
46
- * field can read `undefined` — the Host may keep a value it cannot project, or
47
- * run a build from before this code — so every read handles absence.
48
- */
49
- interface SyncedConfigRef<T> {
50
- get(): T | undefined
51
- }
52
-
53
- /**
54
- * This plugin's top-level volatile Config fields, as `apply` receives them.
55
- *
56
- * Mirrors `SyncedConfig<OpenInDshConfig>`. Only `alwaysNewSession` is volatile:
57
- * the Host reads it out of the graph row into a reference, and a later config
58
- * write updates that reference in place while the page stays loaded.
59
- */
60
- interface SyncedConfig {
61
- alwaysNewSession?: SyncedConfigRef<boolean>
62
- }
63
-
64
- /** Dictionary namespace owned by this plugin. */
65
- const NS = 'dsh-open-in-dsh'
66
-
67
- /**
68
- * Menu labels. scripts/build-client.mts replaces the marker below with the
69
- * "menu" objects from locale/zh.json and locale/en.json, so the shipped bundle
70
- * and the package's locale files cannot drift.
71
- */
72
- const MENU_DICTIONARIES = /* @menu-dictionaries */ { zh: {}, en: {} }
73
-
74
- /** The Host's open-with route; carried by hand in lib/index.js. */
75
- const ROUTE_OPEN_WITH = '/dsh-open-in-dsh/api/v1/open-with'
76
-
77
- /** The Host's availability route; carried by hand in lib/index.js. */
78
- const ROUTE_APPS = '/dsh-open-in-dsh/api/v1/apps'
79
-
80
- /**
81
- * The Host's Session route; carried by hand in lib/index.js.
82
- *
83
- * The Session-scoped entry (the sidebar row menu) only ever knows a session
84
- * id. This route is where the Host turns that id into a directory, so the
85
- * browser half never guesses a cwd and never sends one.
86
- */
87
- const ROUTE_OPEN_SESSION = '/dsh-open-in-dsh/api/v1/open-session'
88
-
89
- /**
90
- * Menu order. The Host reports the subset this platform can launch; this list
91
- * decides how the actions stack when it reports several.
92
- */
93
- const MENU_APP_ORDER = ['qspace', 'finder', 'vscode', 'warp', 'terminal', 'explorer']
94
-
95
- /**
96
- * Whether a path is absolute in either spelling the Host accepts.
97
- * @param value - the path to classify.
98
- * @returns true for a POSIX, drive-letter or UNC absolute path.
99
- */
100
- function isAbsolutePath(value) {
101
- if (value.startsWith('/')) return true
102
- if (value.length >= 3 && value[1] === ':' && (value[2] === '/' || value[2] === '\\')) return true
103
- return value.startsWith('\\\\')
104
- }
105
-
106
- /**
107
- * Resolve a Workspace-relative path against the Session directory.
108
- * @param cwd - the Session's workspace root, when known.
109
- * @param path - absolute or Workspace-relative path.
110
- * @returns an absolute path, or null when a relative path has no root.
111
- */
112
- function resolveWorkspacePath(cwd, path) {
113
- if (isAbsolutePath(path)) return path
114
- if (typeof cwd !== 'string' || cwd === '') return null
115
- const separator = cwd.includes('\\') ? '\\' : '/'
116
- return cwd.replace(/[/\\]+$/, '') + separator + path.replace(/^(?:\.?[/\\])+/, '')
117
- }
118
-
119
- /**
120
- * The directory that contains a file, in either path spelling.
121
- *
122
- * A document preview only knows the file it is showing, and an application
123
- * launched with `open -a` on a file runs the file rather than showing its
124
- * folder. The containing directory is therefore what the action opens.
125
- *
126
- * @param path - absolute or relative file path.
127
- * @returns the containing directory, or null when there is none to name.
128
- */
129
- function parentDirectory(path) {
130
- if (typeof path !== 'string') return null
131
- const text = path.trim().replace(/[/\\]+$/, '')
132
- if (text === '') return null
133
- const cut = Math.max(text.lastIndexOf('/'), text.lastIndexOf('\\'))
134
- if (cut < 0) return null
135
- // '/a.md' belongs to '/', not to ''.
136
- if (cut === 0) return text.slice(0, 1)
137
- const head = text.slice(0, cut)
138
- // 'C:\a.md' belongs to 'C:\', not to 'C:'.
139
- if (/^[A-Za-z]:$/.test(head)) return head + '\\'
140
- return head
141
- }
142
-
143
- /**
144
- * Read one external module the way the Client module table offers it.
145
- *
146
- * The bundle is loaded by `window.__ModuleLoader__`, whose `require` resolves
147
- * the platform seed ('react' among them). Nothing is installed for this: the
148
- * plugin declares no React dependency, and a composition whose seed cannot
149
- * answer simply gets no rendered controls instead of a bundle that fails to
150
- * load.
151
- *
152
- * @param require - the loader-provided require.
153
- * @param id - the module id to read.
154
- * @returns the module, or null when it is unavailable.
155
- */
156
- function tryRequire(require, id) {
157
- try {
158
- const value = typeof require === 'function' ? require(id) : null
159
- return value === null || value === undefined ? null : value
160
- } catch {
161
- return null
162
- }
163
- }
164
-
165
- /**
166
- * Read the injected availability hook. A composition that did not bind it (a
167
- * slot rendered outside this plugin's inject face) hides the control instead
168
- * of crashing the entry.
169
- * @param props - slot props.
170
- * @returns true when QSpace can be launched here.
171
- */
172
- function readAvailability(props) {
173
- if (typeof props.useQspaceAvailable !== 'function') return false
174
- return props.useQspaceAvailable((value) => value) === true
175
- }
176
-
177
- /** The element factory a usable React ships; null when the seed has none. */
178
- function elementFactory(React) {
179
- return React !== null && typeof React.createElement === 'function' ? React.createElement : null
180
- }
181
-
182
- /** Shared look for the two buttons; DSH theme variables only, no stylesheet. */
183
- const QSPACE_BUTTON_STYLE = Object.freeze({
184
- display: 'inline-flex',
185
- alignItems: 'center',
186
- flex: 'none',
187
- height: '22px',
188
- padding: '0 6px',
189
- font: 'inherit',
190
- fontSize: '11px',
191
- lineHeight: '16px',
192
- color: 'var(--dsw-alias-label-secondary)',
193
- background: 'transparent',
194
- border: '0.5px solid var(--dsw-alias-border-l4)',
195
- borderRadius: 'var(--dsw-radius-sm, 4px)',
196
- cursor: 'pointer',
197
- whiteSpace: 'nowrap',
198
- })
199
-
200
- /**
201
- * Page-lifetime "is QSpace installed" answer, bound as a slot hook.
202
- *
203
- * The Host probes the bundle once per process life, so this store asks at most
204
- * once: a failed answer is left unresolved and retried by the next mount,
205
- * because one lost request must not hide the control for the whole page.
206
- *
207
- * @param read - the availability reader (see `createAppsReader`).
208
- * @returns an observable source for `inject({ hooks: { qspaceAvailable } })`.
209
- */
210
- function createAvailability(read) {
211
- let state = null
212
- let loading = null
213
- const listeners = new Set<() => void>()
214
- const publish = (next) => {
215
- if (next === state) return
216
- state = next
217
- for (const listener of [...listeners]) {
218
- try {
219
- listener()
220
- } catch {
221
- // A throwing subscriber is a renderer problem, not an availability one.
222
- }
223
- }
224
- }
225
- const refresh = () => {
226
- if (state !== null) return loading ?? Promise.resolve()
227
- if (loading === null) {
228
- loading = Promise.resolve()
229
- .then(read)
230
- .then((ids) => {
231
- if (Array.isArray(ids)) publish(ids.includes('qspace'))
232
- })
233
- .catch(() => {})
234
- .finally(() => {
235
- loading = null
236
- })
237
- }
238
- return loading
239
- }
240
- return {
241
- getSnapshot: () => state === true,
242
- subscribe(listener) {
243
- listeners.add(listener)
244
- refresh()
245
- return () => {
246
- listeners.delete(listener)
247
- }
248
- },
249
- refresh,
250
- close() {
251
- listeners.clear()
252
- },
253
- }
254
- }
255
-
256
- /**
257
- * Read the Host's availability answer into an ordered id list.
258
- * @param payload - the Host response body.
259
- * @returns allowlisted ids the Host reported, in menu order.
260
- */
261
- function appIdsFrom(payload) {
262
- if (payload === null || typeof payload !== 'object' || !Array.isArray(payload.apps)) return []
263
- const reported = payload.apps.filter((id) => typeof id === 'string')
264
- return MENU_APP_ORDER.filter((id) => reported.includes(id))
265
- }
266
-
267
- /**
268
- * Lazy, page-lifetime availability reader.
269
- *
270
- * A successful answer is cached; a failed one is retried on the next menu
271
- * opening, so one lost request does not hide the menu until a reload.
272
- *
273
- * @returns a function resolving the allowlisted ids for this platform.
274
- */
275
- function createAppsReader() {
276
- let cached = null
277
- let pending = null
278
- return async () => {
279
- if (cached !== null) return cached
280
- if (pending === null) {
281
- pending = (async () => {
282
- try {
283
- const response = await fetch(ROUTE_APPS, { headers: { accept: 'application/json' }, cache: 'no-store' })
284
- if (!response.ok) return []
285
- const ids = appIdsFrom(await response.json())
286
- if (ids.length > 0) cached = ids
287
- return ids
288
- } catch {
289
- return []
290
- } finally {
291
- pending = null
292
- }
293
- })()
294
- }
295
- return pending
296
- }
297
- }
298
-
299
- /**
300
- * Build the localized open-with actions for one target.
301
- * @param options - resolved app ids, absolute path, translate seat and launcher.
302
- * @returns the context-menu action array.
303
- */
304
- function createMenuActions(options) {
305
- return options.apps.map((app) => ({
306
- id: 'open-with.' + app,
307
- label: options.translate('menu.' + app),
308
- failureLabel: options.translate('menu.failed'),
309
- run: () => options.launch(app, options.absolutePath),
310
- }))
311
- }
312
-
313
- /**
314
- * Build the document-preview action: "open the folder that holds this file in
315
- * QSpace".
316
- *
317
- * The component is a plain function of its slot props, with no state of its
318
- * own: QSpace availability arrives as an injected hook (a snapshot source), so
319
- * a render never starts a request, and a Host that cannot launch QSpace never
320
- * shows the control at all.
321
- *
322
- * @param React - the seed React module (`require('react')`).
323
- * @param deps - `{openWith, fail}`: the Host launcher and the failure toast.
324
- * @returns the slot component for `sidebar.right.tab.document.actions`.
325
- */
326
- function createDocumentAction(React, deps) {
327
- const h = elementFactory(React)
328
- /**
329
- * @param props - slot props: `absolutePath`, `useQspaceAvailable`, `t`.
330
- * @returns the action button, or null when there is nothing to open.
331
- */
332
- function QspaceDocumentAction(props) {
333
- if (h === null) return null
334
- const available = readAvailability(props)
335
- const path = typeof props.absolutePath === 'string' ? props.absolutePath : ''
336
- if (available !== true || path === '') return null
337
- const directory = parentDirectory(path)
338
- if (directory === null) return null
339
- const label = props.t('menu.qspaceDocument')
340
- return h(
341
- 'button',
342
- {
343
- type: 'button',
344
- 'data-dsh-open-in-dsh': 'document',
345
- // The title says which folder, because the label has to stay short.
346
- title: directory,
347
- 'aria-label': label,
348
- style: QSPACE_BUTTON_STYLE,
349
- onClick: () => {
350
- Promise.resolve()
351
- .then(() => deps.openWith('qspace', directory))
352
- .catch(() => deps.fail())
353
- },
354
- },
355
- label,
356
- )
357
- }
358
- return QspaceDocumentAction
359
- }
360
-
361
- /** Test and troubleshooting surface; not part of the plugin API. */
362
- const __internals = {
363
- appIdsFrom,
364
- createMenuActions,
365
- resolveWorkspacePath,
366
- isAbsolutePath,
367
- parentDirectory,
368
- createAvailability,
369
- createDocumentAction,
370
- MENU_APP_ORDER,
371
- }
372
-
373
- /**
374
- * Build the browser plugin.
375
- * @param require - the Client module table's require, for the platform seed
376
- * React the two rendered controls are built with (no dependency is added for
377
- * it; a composition without the seed simply renders no controls).
378
- * @returns the Cordis plugin export (`inject` + `apply`).
379
- */
380
- function createPlugin(require) {
381
- const React = tryRequire(require, 'react')
382
- /** Hand-mirrored in `lib/index.js`; the two halves cannot import each other. */
383
- const EVENTS_PATH = '/dsh-open-in-dsh/api/v1/events'
384
-
385
- /**
386
- * Highest request sequence this window already handled.
387
- *
388
- * Kept in `sessionStorage` so a reload does not re-open the folder the user
389
- * opened a moment ago, and scoped to the window so a second DSH window is
390
- * free to handle the same backlog.
391
- */
392
- const SEQ_KEY = 'dsh-open-in-dsh:seq'
393
-
394
- /**
395
- * Read the stored sequence.
396
- * @returns the stored sequence, or 0.
397
- */
398
- function readSeq() {
399
- try {
400
- const value = Number.parseInt(window.sessionStorage.getItem(SEQ_KEY) ?? '', 10)
401
- return Number.isFinite(value) && value > 0 ? value : 0
402
- } catch {
403
- return 0
404
- }
405
- }
406
-
407
- /**
408
- * Store the sequence.
409
- * @param value - the sequence to remember.
410
- */
411
- function writeSeq(value) {
412
- try {
413
- window.sessionStorage.setItem(SEQ_KEY, String(value))
414
- } catch {
415
- // A browser with storage disabled still works: it just replays on reload.
416
- }
417
- }
418
-
419
- /** Ask the OS for the foreground. Usually ignored without a user gesture. */
420
- function focusWindow() {
421
- try {
422
- window.focus()
423
- } catch {
424
- // Nothing to do; the folder is open either way.
425
- }
426
- }
427
-
428
- /**
429
- * Whether a request should land in a brand-new Session.
430
- *
431
- * Read at the moment of use, never captured: the Host commits a config write
432
- * into the synced reference in place, and the plugin is not remounted for it,
433
- * so a value read once at mount would stay stale for the life of the page.
434
- * Absent means the shipped default (`false`: reuse the Workspace's blank
435
- * Session).
436
- *
437
- * @param config - the synced Config `apply` received.
438
- * @returns true when every announced folder opens in a new blank Session.
439
- */
440
- function readAlwaysNewSession(config: SyncedConfig): boolean {
441
- return config.alwaysNewSession?.get() === true
442
- }
443
-
444
- /**
445
- * Mount the plugin.
446
- * @param ctx - browser plugin context, with `workspaces` and `sessions`.
447
- * @param config - the Host's synced volatile Config, handed over by the
448
- * kernel (empty object when the row has none).
449
- */
450
- function apply(ctx, config: SyncedConfig = {}) {
451
- let lastSeq = readSeq()
452
- let source = null
453
- let uiWorkspace = null
454
-
455
- // Soft dependency: navigation is the last step, and a composition without
456
- // `dsh-client-ui-workspace` should still register the Workspace and Session
457
- // rather than refuse to load. `ctx.get` alone would not be dependable here,
458
- // so the instance is captured through an injection of its own.
459
- ctx.inject(['uiWorkspace'], (scoped) => {
460
- uiWorkspace = scoped.get('uiWorkspace')
461
- })
462
-
463
- // Menu labels come from the package's locale files, inlined into this
464
- // bundle at build time: a right-click never waits on a dictionary fetch.
465
- ctx.effect(() => ctx.locale.register(NS, MENU_DICTIONARIES), 'dsh-open-in-dsh: menu dictionaries')
466
- const t = ctx.locale.bind(NS)
467
-
468
- /** Availability: one probe per page (the Host caches per process life). */
469
- const apps = createAppsReader()
470
-
471
- /**
472
- * Absolute path for a captured file or directory target.
473
- * @param target - the menu target value: { sessionId, path }.
474
- * @returns the absolute path, or null when it cannot be resolved.
475
- */
476
- const absolutePathFor = (target) => {
477
- const path = target !== null && typeof target === 'object' && typeof target.path === 'string' ? target.path : ''
478
- if (path === '') return null
479
- const cwd = ctx.sessions.list.getSnapshot().byId[target.sessionId]?.cwd
480
- return resolveWorkspacePath(cwd, path)
481
- }
482
-
483
- /**
484
- * Ask the Host to launch one allowlisted app on a path.
485
- *
486
- * The Host owns the command: this half can only name an id it received from
487
- * the availability route, and the Host revalidates both the id and the path
488
- * before spawning anything.
489
- *
490
- * @param app - allowlisted app id.
491
- * @param path - absolute, validated path.
492
- * @returns completion; rejects when the Host refuses or cannot launch.
493
- */
494
- const launch = async (app, path) => {
495
- const response = await fetch(ROUTE_OPEN_WITH, {
496
- method: 'POST',
497
- headers: { 'content-type': 'application/json' },
498
- body: JSON.stringify({ path: path, app: app }),
499
- })
500
- let payload = null
501
- try {
502
- payload = await response.json()
503
- } catch {
504
- payload = null
505
- }
506
- if (!response.ok || payload === null || payload.ok !== true) {
507
- const reason = payload !== null && typeof payload.reason === 'string' ? payload.reason : 'http-' + String(response.status)
508
- throw new Error('dsh-open-in-dsh: open-with ' + app + ' failed (' + reason + ')')
509
- }
510
- }
511
-
512
- /**
513
- * Resolve the open-with actions for one captured file or directory.
514
- * @param target - the menu target value: { sessionId, path }.
515
- * @param signal - the provider's cancellation signal.
516
- * @returns the action array; empty when there is nothing to offer.
517
- */
518
- const resolveActions = async (target, signal) => {
519
- const absolutePath = absolutePathFor(target)
520
- if (absolutePath === null) return []
521
- const ids = await apps()
522
- if (signal?.aborted) return []
523
- return createMenuActions({ apps: ids, absolutePath: absolutePath, translate: t, launch: launch })
524
- }
525
-
526
- ctx.effect(
527
- () => ctx.contextMenus.register({ id: 'open-with.file', target: 'file', order: 200, resolve: resolveActions }),
528
- 'dsh-open-in-dsh: file menu',
529
- )
530
- ctx.effect(
531
- () => ctx.contextMenus.register({ id: 'open-with.directory', target: 'directory', order: 200, resolve: resolveActions }),
532
- 'dsh-open-in-dsh: directory menu',
533
- )
534
-
535
- /** One QSpace availability answer per page, shared by the rendered controls. */
536
- const qspace = createAvailability(apps)
537
- ctx.effect(() => () => qspace.close(), 'dsh-open-in-dsh: qspace availability')
538
-
539
- /** The failure toast; the same string the menu actions use as `failureLabel`. */
540
- const notifyFailure = () => {
541
- try {
542
- ctx.contextMenus.notify(t('menu.failed'))
543
- } catch {
544
- // No menu overlay in this composition; the rejection is already logged.
545
- }
546
- }
547
-
548
- /**
549
- * Ask the Host to open one Session's working directory.
550
- *
551
- * The session id is all this half sends: the Host owns the id-to-cwd
552
- * resolution so the browser never invents a path for a Session it is not
553
- * currently showing.
554
- *
555
- * @param app - allowlisted app id.
556
- * @param sessionId - the Session to open.
557
- * @returns completion; rejects when the Host has no cwd or cannot launch.
558
- */
559
- const openSession = async (app, sessionId) => {
560
- const response = await fetch(ROUTE_OPEN_SESSION, {
561
- method: 'POST',
562
- headers: { 'content-type': 'application/json' },
563
- body: JSON.stringify({ sessionId: sessionId, app: app }),
564
- })
565
- let payload = null
566
- try {
567
- payload = await response.json()
568
- } catch {
569
- payload = null
570
- }
571
- if (!response.ok || payload === null || payload.ok !== true) {
572
- const reason = payload !== null && typeof payload.reason === 'string' ? payload.reason : 'http-' + String(response.status)
573
- throw new Error('dsh-open-in-dsh: open-session ' + app + ' failed (' + reason + ')')
574
- }
575
- }
576
-
577
- /**
578
- * Resolve the Session row menu's contribution.
579
- *
580
- * Nothing is offered when QSpace cannot be launched; a Session the Client
581
- * knows no cwd for still gets a row, disabled with the reason, because a
582
- * disappearing item reads as a broken menu.
583
- *
584
- * @param target - the menu target value: `{sessionId, displayTitle}`.
585
- * @param signal - the provider's cancellation signal.
586
- * @returns the action array; empty when there is nothing to offer.
587
- */
588
- const resolveSessionActions = async (target, signal) => {
589
- const sessionId =
590
- target !== null && typeof target === 'object' && typeof target.sessionId === 'string' ? target.sessionId : ''
591
- if (sessionId === '') return []
592
- const ids = await apps()
593
- if (signal?.aborted) return []
594
- if (!ids.includes('qspace')) return []
595
- const cwd = ctx.sessions.list.getSnapshot().byId[sessionId]?.cwd
596
- if (typeof cwd !== 'string' || cwd === '') {
597
- return [{ id: 'qspace', label: t('menu.sessionNoCwd'), disabled: true }]
598
- }
599
- return [
600
- {
601
- id: 'qspace',
602
- label: t('menu.qspaceSession'),
603
- failureLabel: t('menu.failed'),
604
- run: () => openSession('qspace', sessionId),
605
- },
606
- ]
607
- }
608
-
609
- ctx.effect(
610
- () =>
611
- ctx.contextMenus.register({
612
- id: 'open-with.session',
613
- target: 'session',
614
- // Below the workspace plugin's own rows, above its footer actions.
615
- order: 510,
616
- // A Session's cwd and the active locale both decide what this row
617
- // says, so a row already on screen must not keep a stale answer.
618
- observe: () => [ctx.sessions.list, ctx.locale],
619
- resolve: resolveSessionActions,
620
- }),
621
- 'dsh-open-in-dsh: session menu',
622
- )
623
-
624
- // The one rendered entry. `slots.inject` waits for the declaration, so a
625
- // composition without the document preview simply never asks for it.
626
- const documentAction = createDocumentAction(React, { openWith: launch, fail: notifyFailure })
627
- ctx.slots.inject('sidebar.right.tab.document.actions', () =>
628
- ctx.slots.register(
629
- {
630
- name: 'sidebar.right.tab.document.actions',
631
- id: 'open-with.qspace',
632
- order: 10,
633
- locale: NS,
634
- inject: () => ({ hooks: { qspaceAvailable: qspace } }),
635
- },
636
- documentAction,
637
- ),
638
- )
639
- /**
640
- * Apply one announced folder.
641
- *
642
- * Order matters: the Workspace must exist on the Host before a Session can
643
- * name it, and `sessions.create` is what publishes the sidebar row, so the
644
- * Session is created through the Client rather than assumed.
645
- *
646
- * @param path - the canonical directory path.
647
- * @returns completion.
648
- */
649
- const openFolder = async (path) => {
650
- const workspace = await ctx.workspaces.create({ path })
651
-
652
- // Read after the Workspace await: a config write may arrive while this
653
- // request is in flight, and the newest value is the one the user expects.
654
- if (!readAlwaysNewSession(config)) {
655
- if (uiWorkspace !== null) await uiWorkspace.openWorkspace(workspace.workspaceId)
656
- return
657
- }
658
-
659
- const sessionId = await ctx.sessions.create({ workspaceId: workspace.workspaceId })
660
- if (uiWorkspace !== null) uiWorkspace.openSession(sessionId)
661
- }
662
-
663
- /**
664
- * Handle one request frame.
665
- *
666
- * `seq <= lastSeq` is the whole de-duplication: the stream replays what a
667
- * page missed, and EventSource reconnects with the same URL, so the same
668
- * frame can arrive twice.
669
- *
670
- * @param payload - the parsed frame.
671
- */
672
- const handle = (payload) => {
673
- if (payload === null) return
674
- if (!Number.isInteger(payload.seq) || payload.seq <= lastSeq) return
675
- if (typeof payload.path !== 'string' || payload.path.length === 0) return
676
- lastSeq = payload.seq
677
- writeSeq(lastSeq)
678
- openFolder(payload.path)
679
- .then(focusWindow)
680
- .catch((reason) => {
681
- // A refused path is the user's to see, and the Workspace notice is
682
- // the Client's channel for it; this half only logs.
683
- console.warn('dsh-open-in-dsh: could not open', payload.path, reason)
684
- })
685
- }
686
-
687
- /**
688
- * Open the stream, replaying only what this window has not handled.
689
- *
690
- * `since` travels in the URL, so a reconnect after a host restart would
691
- * still carry a sequence the new host has already passed — and would then
692
- * miss every backlog row published in the gap. `hello` reports that rewind,
693
- * and the stream is rebuilt from zero when it happens.
694
- */
695
- const connect = () => {
696
- source = new EventSource(`${EVENTS_PATH}?since=${lastSeq}`)
697
-
698
- source.addEventListener('hello', (event) => {
699
- const payload = parseFrame(event.data)
700
- if (payload === null) return
701
- // Config is not carried by the frame: the synced reference is already
702
- // live. `hello` only reports the sequence.
703
- if (Number.isInteger(payload.seq) && payload.seq < lastSeq) {
704
- lastSeq = 0
705
- writeSeq(0)
706
- source.close()
707
- connect()
708
- }
709
- })
710
-
711
- // Not `open`: EventSource owns that event name for connection state.
712
- source.addEventListener('request', (event) => handle(parseFrame(event.data)))
713
- }
714
-
715
- connect()
716
- ctx.effect(() => () => source?.close(), 'dsh-open-in-dsh: request stream')
717
-
718
- // Troubleshooting hook, callable from the devtools console:
719
- // await __dshOpenIn.open('D:\\project')
720
- // __dshOpenIn.status()
721
- window.__dshOpenIn = {
722
- route: EVENTS_PATH,
723
- open: openFolder,
724
- openWith: launch,
725
- status: () => ({
726
- lastSeq,
727
- // Read live, like every other consumer of the synced field.
728
- settings: { alwaysNewSession: readAlwaysNewSession(config) },
729
- uiWorkspace: uiWorkspace !== null,
730
- readyState: source === null ? null : source.readyState,
731
- }),
732
- }
733
- }
734
-
735
- return { inject: ['workspaces', 'sessions', 'contextMenus', 'locale', 'slots'], apply }
736
- }