dsh-computer-use-ljl454 3.1.0 → 3.1.1

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/INSTALL.md CHANGED
@@ -3,7 +3,7 @@
3
3
  在 Harness 的插件安装框输入 `dsh-computer-use-ljl454`,或在可使用 dsh 命令的终端执行:
4
4
 
5
5
  ```powershell
6
- dsh plugin --profile desktop add dsh-computer-use-ljl454@3.1.0
6
+ dsh plugin --profile desktop add dsh-computer-use-ljl454@3.1.1
7
7
  ```
8
8
 
9
9
  安装后完整退出并重新打开 Harness,在需要控制电脑的会话开启「电脑操作」。
@@ -13,7 +13,7 @@ dsh plugin --profile desktop add dsh-computer-use-ljl454@3.1.0
13
13
  ## 普通 npm 下载
14
14
 
15
15
  ```powershell
16
- npm install dsh-computer-use-ljl454@3.1.0
16
+ npm install dsh-computer-use-ljl454@3.1.1
17
17
  ```
18
18
 
19
19
  普通 npm install 只把文件放进当前项目,不会自动登记 Harness profile。要在 Harness 使用,请用上面的 dsh plugin add 或插件安装框。
package/README.md CHANGED
@@ -1,13 +1,13 @@
1
1
  # dsh-computer-use-ljl454
2
2
 
3
- DeepSeek Harness 的 Windows 电脑操作插件,版本 3.1.0。
3
+ DeepSeek Harness 的 Windows 电脑操作插件,版本 3.1.1。
4
4
 
5
5
  ## 安装到 Harness
6
6
 
7
7
  在 Harness 的插件安装框输入 `dsh-computer-use-ljl454`,或在可使用 dsh 命令的终端执行:
8
8
 
9
9
  ```powershell
10
- dsh plugin --profile desktop add dsh-computer-use-ljl454@3.1.0
10
+ dsh plugin --profile desktop add dsh-computer-use-ljl454@3.1.1
11
11
  ```
12
12
 
13
13
  安装后完整退出并重新打开 Harness,在需要控制电脑的会话开启「电脑操作」。
@@ -17,7 +17,7 @@ dsh plugin --profile desktop add dsh-computer-use-ljl454@3.1.0
17
17
  ## 普通 npm 下载
18
18
 
19
19
  ```powershell
20
- npm install dsh-computer-use-ljl454@3.1.0
20
+ npm install dsh-computer-use-ljl454@3.1.1
21
21
  ```
22
22
 
23
23
  普通 npm install 只把文件放进当前项目,不会自动登记 Harness profile。要在 Harness 使用,请用上面的 dsh plugin add 或插件安装框。
package/client.js CHANGED
@@ -1177,6 +1177,7 @@ window.__ModuleLoader__.load({
1177
1177
  controlOwner: typeof control.lease?.owner === 'string' ? control.lease.owner : '',
1178
1178
  inFlight: Number.isFinite(control.inFlight) ? Number(control.inFlight) : 0,
1179
1179
  backgroundBrowser: bg,
1180
+ appBackground: payload.appBackground ?? null,
1180
1181
  // 复核第 2 条:进度来自 worker 自己的 v3 事件。没有事件时这里是 null,芯片照旧只显示"执行中"。
1181
1182
  progress: progressFrom(control.progress),
1182
1183
  // Whether the *last switch attempt* failed. Kept separate from `phase` because the two
@@ -2640,7 +2641,7 @@ window.__ModuleLoader__.load({
2640
2641
  }, '停止') : null),
2641
2642
  stopError ? React.createElement('p', { className: 'dsh-cu-fx-error', role: 'status' }, stopError) : null,
2642
2643
  sessionId ? React.createElement('div', { className: 'dsh-cu-session-card' },
2643
- React.createElement(ExecutionModeSelect, { sessionId, inherited: status.subagents?.delegated === true, onStateChange }),
2644
+ React.createElement(ExecutionModeSelect, { sessionId, inherited: status.subagents?.delegated === true, onStateChange, appBackground: status.appBackground }),
2644
2645
  React.createElement(SubagentSessionControl, { status, onStateChange })) : null,
2645
2646
  React.createElement(HostApprovalsPanel, { key: sessionId, sessionId }),
2646
2647
  React.createElement(UpdateControls),
@@ -2921,6 +2922,71 @@ window.__ModuleLoader__.load({
2921
2922
  } }, '重试') : null);
2922
2923
  }
2923
2924
 
2925
+ const appBackgroundLabels = {
2926
+ checking: '检测中', ready: '已就绪', needs_setup: '待配置',
2927
+ needs_admin_restart: '需管理员启动', unsupported: '本机不支持',
2928
+ };
2929
+
2930
+ function useAppBackgroundSetup(initial, load) {
2931
+ const [report, setReport] = React.useState(null);
2932
+ const [busy, setBusy] = React.useState(false);
2933
+ const [notice, setNotice] = React.useState('');
2934
+ React.useEffect(() => {
2935
+ if (!load) {
2936
+ setReport(initial);
2937
+ return;
2938
+ }
2939
+ const controller = new AbortController();
2940
+ fetch(`${ROUTE}/child-session/readiness`, { signal: controller.signal }).then(async response => {
2941
+ const value = await readJson(response);
2942
+ if (!response.ok || !value?.ok) throw replyFailure(response, value, '应用后台检测失败');
2943
+ if (!controller.signal.aborted) setReport(value.appBackground);
2944
+ }).catch(error => { if (!controller.signal.aborted) setNotice(error.message); });
2945
+ return () => controller.abort();
2946
+ }, [load, initial]);
2947
+ async function configure(action) {
2948
+ setBusy(true);
2949
+ setNotice('');
2950
+ try {
2951
+ const response = await fetch(`${ROUTE}/child-session/${action ? 'setup' : 'readiness?refresh=1'}`, action ? {
2952
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action }),
2953
+ } : undefined);
2954
+ const value = await readJson(response);
2955
+ if (value?.appBackground) setReport(value.appBackground);
2956
+ if (!response.ok || !value?.ok) {
2957
+ setNotice(value?.message || replyFailure(response, value, '应用后台配置失败').message);
2958
+ }
2959
+ } catch (error) { setNotice(error.message); }
2960
+ finally { setBusy(false); }
2961
+ }
2962
+ return { report: report ?? initial, busy, notice, configure };
2963
+ }
2964
+
2965
+ function AppBackgroundSettings() {
2966
+ const { report, busy, notice, configure } = useAppBackgroundSetup(null, true);
2967
+ const status = report?.status ?? 'checking';
2968
+ const canSetup = status === 'needs_setup' && report.inAdminGroup !== false;
2969
+ const canDisable = status !== 'unsupported' && report?.childSessionsEnabled && report.inAdminGroup !== false;
2970
+ const button = (label, action) => h('button', { type: 'button', className: 'dsh-cu-panel-btn', disabled: busy,
2971
+ onClick: () => { void configure(action); } }, label);
2972
+ return h('section', { className: 'dsh-cu-settings-section' },
2973
+ h('h3', null, '执行模式与后台环境'),
2974
+ settingRow('网页后台', '已就绪 · 浏览网页不占用主桌面键鼠'),
2975
+ settingRow('主桌面模式', '已就绪 · 后台自动模式下的写操作会请求许可,按 Esc 可急停'),
2976
+ settingRow('应用后台(进阶隔离)', appBackgroundLabels[status]),
2977
+ report?.supportedByBuild ? h('ul', { className: 'dsh-cu-fx-note' },
2978
+ h('li', null, `Windows 子会话:${report.childSessionsEnabled ? '已开启' : '未开启'}`),
2979
+ h('li', null, `TermService:${report.termServiceStartType === 'Disabled' ? '已禁用' : report.termServiceStatus === 'Running' ? '运行中' : report.termServiceStartType === 'Unknown' ? '状态未知' : '按需可用'}`),
2980
+ h('li', null, `运行权限:${report.isElevated ? '管理员' : '普通权限'}`)) : null,
2981
+ h('p', { className: 'dsh-cu-fx-note' }, report?.message || '正在检测应用后台环境…'),
2982
+ canSetup ? h('p', { className: 'dsh-cu-fx-note' }, 'Windows 会请求一次管理员授权。配置仅开启本机子会话和按需启动 TermService,不会开放外部远程桌面。') : null,
2983
+ status === 'needs_setup' && report.inAdminGroup === false ? h('p', { className: 'dsh-cu-fx-note' }, '当前 Windows 账号不属于管理员组。') : null,
2984
+ canSetup ? button('一键配置应用后台(需管理员授权)', 'enable') : null,
2985
+ button('重新检测'),
2986
+ canDisable ? button('关闭子会话', 'disable') : null,
2987
+ notice ? h('p', { className: 'dsh-cu-fx-note', role: 'status' }, notice) : null);
2988
+ }
2989
+
2924
2990
  function ComputerUseSettings() {
2925
2991
  const [section, setSection] = React.useState('general');
2926
2992
  const sections = [['general', '常规与权限'], ['appearance', '外观与覆盖层'], ['status', '状态与更新'], ['pet', '桌面宠物']];
@@ -2928,7 +2994,7 @@ window.__ModuleLoader__.load({
2928
2994
  h('div', { className: 'dsh-cu-settings-nav', role: 'group', 'aria-label': '电脑控制插件设置' },
2929
2995
  ...sections.map(([id, label]) => h('button', { type: 'button', key: id, 'aria-pressed': section === id,
2930
2996
  onClick: () => setSection(id) }, label))),
2931
- section === 'general' ? h(SubagentSettings) : null,
2997
+ section === 'general' ? h(React.Fragment, null, h(AppBackgroundSettings), h(SubagentSettings)) : null,
2932
2998
  section === 'pet' ? h(PetSettingsSlot) :
2933
2999
  section === 'status' ? h(DiagnosticsSettingsSection) : h(AnimationSettingsSlot, { section }),
2934
3000
  );
@@ -2957,10 +3023,11 @@ window.__ModuleLoader__.load({
2957
3023
  error ? h('p', { className: 'dsh-cu-fx-error', role: 'status' }, error) : null);
2958
3024
  }
2959
3025
 
2960
- function ExecutionModeSelect({ sessionId, inherited, onStateChange }) {
3026
+ function ExecutionModeSelect({ sessionId, inherited, onStateChange, appBackground }) {
2961
3027
  const [mode, setMode] = React.useState('');
2962
3028
  const [busy, setBusy] = React.useState(false);
2963
3029
  const [error, setError] = React.useState('');
3030
+ const setup = useAppBackgroundSetup(appBackground, false);
2964
3031
  React.useEffect(() => {
2965
3032
  let alive = true;
2966
3033
  requestState(sessionId).then(value => { if (alive) setMode(value.mode?.mode || 'legacy'); })
@@ -2976,12 +3043,20 @@ window.__ModuleLoader__.load({
2976
3043
  } catch (failure) { setError(failure.message); }
2977
3044
  finally { setBusy(false); }
2978
3045
  }
2979
- const choices = [['background', '后台自动'], ['web-background', '网页后台'], ['app-background', '应用后台'],
3046
+ const appReady = setup.report?.status === 'ready';
3047
+ const choices = [['background', '后台自动(推荐)'], ['web-background', '网页后台'], ['app-background', appReady ? '应用后台(进阶隔离)' : '应用后台(需先配置)'],
2980
3048
  ['attached', '附着浏览器'], ['legacy', '主桌面模式']];
2981
3049
  return h(React.Fragment, null,
2982
3050
  settingRow('执行模式', inherited ? '跟随父会话' : '', h('select', { value: mode, disabled: busy || !mode || inherited,
2983
3051
  onChange: event => { void choose(event.target.value); } },
2984
3052
  ...choices.map(([value, label]) => h('option', { key: value, value }, label)))),
3053
+ mode === 'background' ? h('p', { className: 'dsh-cu-fx-note' }, appReady ? '网页与支持的应用均走后台。' : '网页走后台,桌面应用经主桌面审批。') : null,
3054
+ mode === 'app-background' && !appReady && !inherited ? h(React.Fragment, null,
3055
+ h('p', { className: 'dsh-cu-fx-note' }, setup.report?.message || '正在检测应用后台环境。'),
3056
+ setup.report?.status === 'needs_setup' && setup.report.inAdminGroup !== false ? h('button', { type: 'button', className: 'dsh-cu-panel-btn',
3057
+ disabled: setup.busy, onClick: () => { void setup.configure('enable'); } }, '一键配置(需管理员授权)') : null,
3058
+ h('button', { type: 'button', className: 'dsh-cu-panel-btn', disabled: busy, onClick: () => { void choose('legacy'); } }, '改用主桌面模式'),
3059
+ setup.notice ? h('p', { className: 'dsh-cu-fx-note', role: 'status' }, setup.notice) : null) : null,
2985
3060
  error ? h('p', { className: 'dsh-cu-fx-error', role: 'status' }, error) : null);
2986
3061
  }
2987
3062
 
package/index.js CHANGED
@@ -117,6 +117,7 @@ import { createAppSessions } from './internal/app-session.mjs';
117
117
  import { resolveWin32App } from './internal/background-apps.mjs';
118
118
  import { isBackgroundGuiRequest, isBackgroundLaunchRequest, blocksBackgroundShell } from './internal/background-shell-guard.mjs';
119
119
  import { createAppSessionTool } from './internal/app-session-tool.mjs';
120
+ import { createChildSessionReadiness, shouldAdvertiseAppBackground, shouldUseForegroundFallback } from './internal/child-session-readiness.mjs';
120
121
  import { gateForeground, needsMainDesktop, surfaceFor, foregroundRefusal, foregroundOutput, markForegroundReceipt, dispatchRefusal, modeAvailability } from './internal/background-gate.mjs';
121
122
  // 第二阶段:无头实例生命周期、CDP 探针、严格派发许可、子会话能力探针。
122
123
  import { createHeadlessInstances } from './internal/headless-instance.mjs';
@@ -742,12 +743,27 @@ export function apply(ctx, config = {}) {
742
743
  const attempt = isolatedAppTasks.get(owner);
743
744
  return attempt?.taskId === taskIdOf(exec) ? attempt : null;
744
745
  }
746
+ const childSessionReadiness = createChildSessionReadiness({
747
+ exe: join(PACKAGE_ROOT, 'native', 'child-session-setup', 'build', 'child-session-setup.exe'),
748
+ onChange: () => {
749
+ visibility.syncAll();
750
+ ctx.emit?.('system-prompt/change');
751
+ },
752
+ });
753
+ const appBackgroundReady = () => childSessionReadiness.current().status === 'ready';
754
+ function desktopFallback(exec) {
755
+ const attempt = appTaskFor(exec);
756
+ return shouldUseForegroundFallback(modes?.mode(exec?.agent?.session?.id), childSessionReadiness.current().status,
757
+ attempt?.opening || (attempt?.environmentId && idlePilot.owns(attempt.environmentId)));
758
+ }
745
759
  function forceBackgroundFor(exec) {
760
+ if (modes?.mode(exec?.agent?.session?.id) === 'legacy') return false;
746
761
  return isBackgroundGuiRequest(backgroundRequestText(exec)) || !!appTaskFor(exec);
747
762
  }
748
763
  function backgroundRouteIssue(exec, name, args) {
749
764
  if (!name.startsWith('computer_') && name !== 'app_launch') return null;
750
765
  if (surfaceFor(name) !== 'desktop') return null;
766
+ if (modes?.mode(exec?.agent?.session?.id) === 'legacy' || desktopFallback(exec)) return null;
751
767
  if ((name === 'computer_launch' || name === 'app_launch') && args?.foreground !== true) return null;
752
768
  const attempt = appTaskFor(exec);
753
769
  if (!attempt && !isBackgroundLaunchRequest(backgroundRequestText(exec))) return null;
@@ -762,7 +778,9 @@ export function apply(ctx, config = {}) {
762
778
  const isolatedLaunch = isBackgroundLaunchRequest(backgroundRequestText(exec)) || !!appTaskFor(exec);
763
779
  if (blocksBackgroundShell(exec.name, exec.arguments, isolatedLaunch) && forceBackgroundFor(exec)) {
764
780
  return {
765
- reason:'本轮应用用 computer_app_session,网页用无头 computer_browser。保存后台应用截图可传 computer_app_session 的 watch 与 save_path。',
781
+ reason: desktopFallback(exec)
782
+ ? '网页使用无头 computer_browser。桌面应用使用电脑操作工具,首次写入会向用户请求主桌面许可。'
783
+ : '本轮应用用 computer_app_session,网页用无头 computer_browser。保存后台应用截图可传 computer_app_session 的 watch 与 save_path。',
766
784
  info:{name:'BackgroundGuiToolGuard',code:'BACKGROUND_GUI_SHELL_BLOCKED'},
767
785
  };
768
786
  }
@@ -784,6 +802,9 @@ export function apply(ctx, config = {}) {
784
802
  if (!isAppBackground(resolved.mode)) {
785
803
  return '当前会话处于「网页后台」模式:网页使用无头 computer_browser(省略 profile_mode 即默认 persistent 持久保存登录与 Cookie,除非用户明确要求无痕/清空否则勿传 temporary)。不要调用 computer_app_session;仅在确需使用主桌面时走当前对话的前台批准。';
786
804
  }
805
+ if (resolved.mode === 'background' && !appBackgroundReady()) {
806
+ return '当前为「后台自动」。网页用无头 computer_browser,默认保留浏览器资料。桌面应用直接用 computer_launch、computer_windows、computer_ui、computer_ui_action 或 computer_actions。观察自动放行,首次写入由系统向用户请求主桌面许可。获本任务持续许可后可合并连续确定的步骤。暂不调用 computer_app_session。';
807
+ }
787
808
  return '后台应用使用 computer_app_session(op=open, app=应用名),省略 diagnostics。只在返回已核验的 environmentId 后用同一工具 watch/step;不能用 computer_windows、computer_ui_action 或最小化的主桌面窗口代替。网页使用无头 computer_browser(省略 profile_mode 即默认 persistent 持久保存登录与 Cookie,除非用户明确要求无痕/清空否则勿传 temporary)。后台资料默认保留,主桌面原实例保留。后台失败请如实报告。仅在确需使用主桌面时走当前对话的前台批准。';
788
809
  },
789
810
  });
@@ -831,7 +852,7 @@ export function apply(ctx, config = {}) {
831
852
  deniedToolsForAgent: agent => {
832
853
  if (!modes) return [];
833
854
  const currentMode = modes.mode(agent?.session?.id);
834
- return isAppBackground(currentMode) ? [] : ['computer_app_session'];
855
+ return shouldAdvertiseAppBackground(currentMode, childSessionReadiness.current().status) ? [] : ['computer_app_session'];
835
856
  },
836
857
  logger: ctx.logger,
837
858
  onSessionDisposed: (sessionId) => {
@@ -3215,7 +3236,7 @@ export function apply(ctx, config = {}) {
3215
3236
  const needsPermission = strict && needsMainDesktop({ tool, args, kind }).required;
3216
3237
  const persistentApproval = needsPermission && foregroundApprovals.summary(sessionId).grants
3217
3238
  .some(grant => grant.taskId === taskId && grant.generation === generation);
3218
- if (needsPermission && (taskId === 'task' || (args?.steps?.length > 1 && !persistentApproval))) {
3239
+ if (needsPermission && (taskId === 'task' || (args?.steps?.length > 1 && !persistentApproval && !desktopFallback(exec)))) {
3219
3240
  throw Object.assign(new Error('前台操作需要绑定当前任务,以单步派发。'), { code: 'FOREGROUND_STEP_REQUIRED', delivery: 'not_sent' });
3220
3241
  }
3221
3242
  const step = args?.steps?.[0];
@@ -3244,6 +3265,7 @@ export function apply(ctx, config = {}) {
3244
3265
  approvals: foregroundApprovals,
3245
3266
  forceBackground,
3246
3267
  backgroundFailure: appTaskFor(exec)?.foregroundReason,
3268
+ foregroundReason: desktopFallback(exec) ? '本机应用后台暂不可用,可在「设置 → 电脑控制插件 → 常规与权限」查看环境状态' : '',
3247
3269
  sessionId,
3248
3270
  taskId: foregroundTaskOf(exec),
3249
3271
  generation,
@@ -3293,6 +3315,8 @@ export function apply(ctx, config = {}) {
3293
3315
  const mode = modes.resolve(id);
3294
3316
  if (!mode.strictBackground && !forceBackgroundFor(exec)) return null;
3295
3317
  if (args?.foreground === true) return null;
3318
+ if (mode.mode === 'background') await childSessionReadiness.read();
3319
+ if (desktopFallback(exec)) return null;
3296
3320
  if (!isAppBackground(mode.mode)) {
3297
3321
  return {status:'unsupported', note:'这轮要求后台应用操作。请使用当前会话的「后台(自动)」或「应用后台」模式。'};
3298
3322
  }
@@ -5932,6 +5956,7 @@ export function apply(ctx, config = {}) {
5932
5956
  return holder;
5933
5957
  },
5934
5958
  tryAcquire(kind, sessionId, opening = false) {
5959
+ if (childSessionReadiness.disabling) return false;
5935
5960
  if (holder && isStale()) holder = null;
5936
5961
  if (holder && (holder.kind !== kind || holder.sessionId !== sessionId)) return false;
5937
5962
  holder = { kind, sessionId, opening };
@@ -6406,7 +6431,8 @@ export function apply(ctx, config = {}) {
6406
6431
  return str;
6407
6432
  }
6408
6433
  async function tryLaunchChildGpuBrowser({ key, launchGeneration, resolved, startArgs, budget, signal }) {
6409
- if (process.platform !== 'win32' || config?.backgroundBrowserEngine === 'headless' || !existsSync(streamerExe)) {
6434
+ if (process.platform !== 'win32' || config?.backgroundBrowserEngine === 'headless' || !existsSync(streamerExe) ||
6435
+ (await childSessionReadiness.read()).status !== 'ready') {
6410
6436
  return null;
6411
6437
  }
6412
6438
  if (!childSessionLease.tryAcquire('browser', key, true)) {
@@ -6696,6 +6722,7 @@ export function apply(ctx, config = {}) {
6696
6722
  // 回收失败不该影响插件启动:留着记录,等下一次 recycle 或人工处理。
6697
6723
  }
6698
6724
  });
6725
+ ctx.effect(() => deferStartupWork(() => childSessionReadiness.read(), 0), 'computer-use: application background readiness');
6699
6726
  async function identifyManagedBrowser(plan, profileEndpoint, signal) {
6700
6727
  if (!profileEndpoint?.endpoint || !BROWSER_CAPABLE) return null;
6701
6728
  const { discoverEndpoint } = await loadBrowserRuntime();
@@ -7297,7 +7324,7 @@ export function apply(ctx, config = {}) {
7297
7324
  ctx, config, name, VERSION, WORKER_PROTOCOL, REQUIRED_WORKER_CAPABILITIES, ROUTE, shotRoot, actionTimeoutMs, imageDetailDefault, autoScaleForCapture, appPolicy, instanceId, sessions, isEnabled, execution, endIndicatorScope, withCaptureExclusion, captureService, lifecycle, artifacts, writeLease, writeLog, modes, taskIdOf, windowMemory, guardWindow, refs, hostFrames, hostElements, elementAuthorityMode, captureCache, observationLanes, registryMode, restartBackend, requireGrant, metrics, windowSnapshots, assertFrameUsable, mouseGlideEnabled, foregroundCursor, foregroundGlideSteps, glideForegroundCursor, dispatchFrameAction, mintElementTokens, nextReusedFrameId, noteFrameGeometry, callContextOf, registeredToolNames, defineGatedTracedTool, withInteractionPreset, safeRegister, PROFILE_COOLDOWN_MS, capabilityForHwnd, capabilityNote, targetHwndFor, registerDeliverable, enforceAppPolicy, call, cancelSessionCalls, stopChildren, revokeSession, capture, reportAttachment, markObservation, normalizeTextTarget, managedBrowsers, headless, taskbarViews, childSessionLease, headlessCloseHooks, isProcessAlive, defaultProfileRoot, persistentProfileIdentityFor, browserStreamHub, tryLaunchChildGpuBrowser, closeManagedHeadless, openHeadlessViewer, identifyManagedBrowser, managedBrowserFor, browserWindowStore, browserWindowOp, browserSessionFor, disposeBrowserSessionsFor, eyeCheckForGame,
7298
7325
  });
7299
7326
  if (typeof ctx.tools?.register === 'function') {
7300
- backgroundAppTool = defineGatedTracedTool(createAppSessionTool({ appSessions: appSessionsWired, modes, taskIdOf, ops: environmentOpsWired, stepRunner: runStep, resolveGuest }));
7327
+ backgroundAppTool = defineGatedTracedTool(createAppSessionTool({ appSessions: appSessionsWired, modes, taskIdOf, ops: environmentOpsWired, stepRunner: runStep, resolveGuest, readiness: childSessionReadiness }));
7301
7328
  safeRegister(backgroundAppTool);
7302
7329
  }
7303
7330
 
@@ -7427,6 +7454,7 @@ export function apply(ctx, config = {}) {
7427
7454
  // 后台执行模式:模式、代次与能力表。`app.stepGate` 恒为 false 是桌面 v5 的事实,写在这里是为了让
7428
7455
  // 面板与客户端不必猜;`desktop.escCapture` 为 false 表示纯后台任务不建立主桌面的 Esc 捕获范围。
7429
7456
  mode: modes.snapshot(sessionId),
7457
+ appBackground: childSessionReadiness.current(),
7430
7458
  // 能力表 + 当前模式的**限制清单**:开一个后台模式时,用户应该看得见它还没做到什么。
7431
7459
  // `endpointStrictness` 回答"严格模式下为什么连不上":缺本会话记录时这里会给出原因与被跳过的来源。
7432
7460
  background: {
@@ -7649,6 +7677,8 @@ export function apply(ctx, config = {}) {
7649
7677
  // control, and a profile that gains or replaces its web server re-registers
7650
7678
  // these routes without restarting the plugin.
7651
7679
  mountWebRoutes({
7680
+ childSessionReadiness,
7681
+ childSessionLease,
7652
7682
  state: rtState,
7653
7683
  ctx, config, VERSION, ROUTE, SUPPORTED, UNSUPPORTED_REASON, readJsonBody, sendJson, instance, releaseCheck, host, updates, defaultEnabled, visualPreferences, subagentPolicy, startTimeoutMs, sessions, lineageFor, isEnabled, visibility, execution, indicatorEnabled, indicatorExePath, indicatorExeSource, pet, blessings, companionRequested, ensureIndicator, applyCompanionPreferences, refreshIndicator, deliverables, deliveryHealthCache, artifacts, confirmations, actionDecision, hostAuthority, approvals, queryTickets, registryEpochNow, writeLease, writeLog, modes, foregroundDialogs, withdrawForeground, foregroundApprovals, observer, observerReport, registryMode, identityCache, ensureBackend, warmBackend, requireEvidenceTicket, registrationFailures, registeredToolNames, runtimeSummary, call, stopChildren, revokeSession, acceptance, taskbarViews, connectorExe, appStreamHub, idlePilot, browserStreamHub, streamWs, closeManagedHeadless, disposeBrowserSessionsFor, verifyIdentity, statePayload,
7654
7684
  });
@@ -13,6 +13,7 @@
13
13
  */
14
14
 
15
15
  import { APP_OPEN_TIMEOUT_MS } from './child-session-provisioner.mjs';
16
+ import { childSessionError } from './child-session-readiness.mjs';
16
17
 
17
18
  /** 工具名(注册与分类共用一处,避免两处字符串漂移)。 */
18
19
  export const APP_SESSION_TOOL_NAME = 'computer_app_session';
@@ -123,7 +124,7 @@ function closeArgsFor(args) {
123
124
  * @param input.taskIdOf - `(exec) => string`,由宿主侧给出"当前任务"的稳定标识。
124
125
  * @returns 工具描述符 `{ name, description, parameters, output, execute }`。
125
126
  */
126
- export function createAppSessionTool({ appSessions, modes, taskIdOf = () => '', ops = null, stepRunner = null, resolveGuest = null } = {}) {
127
+ export function createAppSessionTool({ appSessions, modes, taskIdOf = () => '', ops = null, stepRunner = null, resolveGuest = null, readiness = null } = {}) {
127
128
  return {
128
129
  name: APP_SESSION_TOOL_NAME,
129
130
  timeoutMs: APP_OPEN_TIMEOUT_MS,
@@ -340,6 +341,10 @@ export function createAppSessionTool({ appSessions, modes, taskIdOf = () => '',
340
341
  ...(outcome?.actionSent === true ? { actionSent: true } : {}),
341
342
  });
342
343
  }
344
+ if (op === 'open' && readiness && openBackend(args) === 'child-session') {
345
+ const report = await readiness.read();
346
+ if (report.status !== 'ready') return { ...base, status: 'unsupported', code: 'ENV_UNSUPPORTED', note: report.message, recoverable: true };
347
+ }
343
348
  const result = await (op === 'open'
344
349
  ? appSessions.open({
345
350
  ownerSession: sessionId,
@@ -375,7 +380,7 @@ export function createAppSessionTool({ appSessions, modes, taskIdOf = () => '',
375
380
  ...(record?.capabilities ? { capabilities: record.capabilities } : (result?.capabilities ? { capabilities: result.capabilities } : {})),
376
381
  recoverable: result?.recoverable === true || mapped === 'kept_open',
377
382
  note: mapped === 'opened' && backend === 'native-sidebar' ? '已打开' + result.result.title + ',在本机 DSH 后台应用侧栏点「接管」即可使用鼠标和键盘。' :
378
- mapped === 'opened' && backend === 'private-desktop' ? '已在独立桌面打开' + result.result.title + (result.result.manualInput === 'chat-draft' ? '。在 DSH 小窗点「接管」即可编辑聊天草稿。' : '。此独立桌面模式支持旁观。') : sentenceFor({ status: mapped, note: result?.chain ? [result.reason, result.chain.code, result.chain.reason].filter(Boolean).join(' · ') : String(result?.reason ?? result?.note ?? ''), environmentId: result?.environmentId ?? args?.environment_id, backend }),
383
+ mapped === 'opened' && backend === 'private-desktop' ? '已在独立桌面打开' + result.result.title + (result.result.manualInput === 'chat-draft' ? '。在 DSH 小窗点「接管」即可编辑聊天草稿。' : '。此独立桌面模式支持旁观。') : sentenceFor({ status: mapped, note: childSessionError(result?.chain ? [result.reason, result.chain.code, result.chain.reason].filter(Boolean).join(' · ') : String(result?.reason ?? result?.note ?? '')), environmentId: result?.environmentId ?? args?.environment_id, backend }),
379
384
  });
380
385
  },
381
386
  };
@@ -83,21 +83,57 @@ export function createAppStreamHub({ resolveSession, streamerExe, startStreamer
83
83
  height: room.quality === 'high' ? 1080 : room.maxH,
84
84
  quality: room.quality,
85
85
  manual: room.manual === true,
86
+ guardPaused: room.guardPaused === true,
86
87
  maxFps: room.manual ? 120 : 60,
87
88
  };
88
89
  }
89
90
 
91
+ function startNative(room, childSessionId) {
92
+ if (!streamerExe || !childSessionId || room.nativeFailed) return null;
93
+ const key = room.key;
94
+ room.nativeRunning = false;
95
+ const same = () => rooms.get(key) === room && room.native === proc;
96
+ const proc = startStreamer(streamerExe, childSessionId, {
97
+ logger,
98
+ onBounds: bounds => {
99
+ if (!same()) return;
100
+ room.bounds = bounds;
101
+ if (room.nativeActive) {
102
+ resolveSession(key)?.onStreamBounds?.(bounds);
103
+ broadcast(room, meta(key));
104
+ }
105
+ },
106
+ onFrame: frame => {
107
+ if (!same() || !room.nativeRunning || !room.bounds) return;
108
+ markNative(room, true);
109
+ pushFrame(key, frame, true);
110
+ },
111
+ onExit: () => {
112
+ if (!same()) return;
113
+ room.native = null;
114
+ room.nativeFailed = true;
115
+ room.nativeRunning = false;
116
+ markNative(room, false);
117
+ schedule(room, 0);
118
+ },
119
+ });
120
+ room.native = proc;
121
+ return proc;
122
+ }
123
+
90
124
  function syncViewer(key) {
91
125
  if (disposed) return;
92
126
  const room = rooms.get(key);
93
127
  if (!room) return;
94
128
  const session = resolveSession(key);
95
129
  const prevManual = room.manual === true;
96
- room.manual = session?.meta.manual === true;
130
+ const prevPaused = room.guardPaused === true;
131
+ room.manual = room.guard ? room.guard.owner === 'manual' : session?.meta.manual === true;
132
+ room.guardPaused = room.guard ? room.guard.owner !== 'agent' : room.manual;
97
133
  if (!session?.meta.active || room.instanceId !== session.meta.instanceId) {
98
- stopNative(room);
134
+ if (!room.guard) stopNative(room);
99
135
  room.instanceId = session?.meta.instanceId;
100
- room.nativeFailed = false;
136
+ if (!room.guard) room.nativeFailed = false;
101
137
  room.sample = null;
102
138
  room.crisp = false;
103
139
  room.lastFrame = null;
@@ -108,44 +144,16 @@ export function createAppStreamHub({ resolveSession, streamerExe, startStreamer
108
144
  room.viewing = viewing;
109
145
  session?.onViewingChange?.(viewing);
110
146
  }
111
- const running = viewing && (session.healthy?.() ?? true);
112
- if (room.native) {
147
+ const running = Boolean(viewing && session.childSessionId && (session.healthy?.() ?? true));
148
+ const native = room.native ?? (running ? startNative(room, session.childSessionId) : null);
149
+ if (native) {
113
150
  if (room.nativeRunning !== running) {
114
151
  room.nativeRunning = running;
115
- room.native.command(running ? 'resume' : 'pause', streamConfig(room));
152
+ native.command(running ? 'resume' : 'pause', streamConfig(room));
116
153
  if (!running) markNative(room, false);
117
- } else if (running && prevManual !== room.manual) {
118
- room.native.command('mode', { manual: room.manual, maxFps: room.manual ? 120 : 60 });
154
+ } else if (prevManual !== room.manual || prevPaused !== room.guardPaused) {
155
+ native.command('mode', streamConfig(room));
119
156
  }
120
- } else if (running && !room.nativeFailed && streamerExe && session.childSessionId) {
121
- room.nativeRunning = true;
122
- const instance = room.instanceId;
123
- const same = () => rooms.get(key) === room && room.instanceId === instance && room.native === proc;
124
- const proc = startStreamer(streamerExe, session.childSessionId, {
125
- logger,
126
- onBounds: bounds => {
127
- if (!same()) return;
128
- room.bounds = bounds;
129
- if (room.nativeActive) {
130
- resolveSession(key)?.onStreamBounds?.(bounds);
131
- broadcast(room, meta(key));
132
- }
133
- },
134
- onFrame: frame => {
135
- if (!same() || !room.nativeRunning || !room.bounds) return;
136
- markNative(room, true);
137
- pushFrame(key, frame, true);
138
- },
139
- onExit: () => {
140
- if (!same()) return;
141
- room.native = null;
142
- room.nativeFailed = true;
143
- markNative(room, false);
144
- schedule(room, 0);
145
- },
146
- });
147
- room.native = proc;
148
- proc.command('resume', streamConfig(room));
149
157
  }
150
158
  if (viewing && !room.nativeActive && !room.timer && !room.capturing) schedule(room, 0);
151
159
  }
@@ -171,6 +179,7 @@ export function createAppStreamHub({ resolveSession, streamerExe, startStreamer
171
179
  const room = rooms.get(key);
172
180
  if (!room) return;
173
181
  cancelSchedule(room);
182
+ room.guard = null;
174
183
  const closing = stopNative(room);
175
184
  if (!room.clients.size) rooms.delete(key);
176
185
  return closing;
@@ -257,7 +266,7 @@ export function createAppStreamHub({ resolveSession, streamerExe, startStreamer
257
266
  };
258
267
  }
259
268
 
260
- function attachClient(key, client, viewport) {
269
+ function ensureRoom(key, viewport = streamViewport()) {
261
270
  let room = rooms.get(key);
262
271
  if (!room) {
263
272
  room = {
@@ -270,9 +279,13 @@ export function createAppStreamHub({ resolveSession, streamerExe, startStreamer
270
279
  ...viewport,
271
280
  };
272
281
  rooms.set(key, room);
273
- } else if (!room.clients.size) {
274
- Object.assign(room, viewport);
275
282
  }
283
+ return room;
284
+ }
285
+
286
+ function attachClient(key, client, viewport) {
287
+ const room = ensureRoom(key, viewport);
288
+ if (!room.clients.size) Object.assign(room, viewport);
276
289
  room.clients.add(client);
277
290
  sendJson(client, meta(key));
278
291
  const initial = room.lastKeyframe ?? room.lastFrame;
@@ -291,7 +304,7 @@ export function createAppStreamHub({ resolveSession, streamerExe, startStreamer
291
304
  if (room.clients.size === 0) {
292
305
  cancelSchedule(room);
293
306
  syncViewer(key);
294
- if (!room.native && rooms.get(key) === room) rooms.delete(key);
307
+ if (!room.guard && !room.native && rooms.get(key) === room) rooms.delete(key);
295
308
  }
296
309
  };
297
310
  syncViewer(key);
@@ -428,6 +441,8 @@ export function createAppStreamHub({ resolveSession, streamerExe, startStreamer
428
441
  const isLayout = message.type === 'layout' && session.meta.nativeHosted === true;
429
442
  if (!isLayout && !['takeover', 'return', 'input'].includes(message.type)) return { ok: false, error: '无效操作' };
430
443
  if (!isLayout && !session.meta.interactive) return { ok: false, error: '此应用仅支持旁观' };
444
+ if (message.type === 'input' && room?.guard && room.guard.owner !== 'manual')
445
+ return { ok: false, error: '请先接管后台应用,等待控制权切换完成。' };
431
446
 
432
447
  // Fast path: when native app-streamer owns DirectInput in manual takeover, dispatch directly
433
448
  // over the 1MB control pipe to SendInput in the child session (bypassing guest-agent queue!).
@@ -440,7 +455,7 @@ export function createAppStreamHub({ resolveSession, streamerExe, startStreamer
440
455
  if (disposed || resolveSession(key)?.meta.instanceId !== session.meta.instanceId) return { ok: false };
441
456
  const result = await session.control(event);
442
457
  if (event.type === 'takeover' || event.type === 'return') {
443
- if (room?.nativeRunning) {
458
+ if (room?.nativeRunning && !room.guard) {
444
459
  const nextManual = result?.manual === true;
445
460
  room.manual = nextManual;
446
461
  room.native?.command('mode', { manual: nextManual, maxFps: nextManual ? 120 : 60 });
@@ -517,13 +532,38 @@ export function createAppStreamHub({ resolveSession, streamerExe, startStreamer
517
532
 
518
533
  function focusTaskWindow(key, target = {}) {
519
534
  const room = rooms.get(key);
520
- if (!room?.nativeActive || !room.native) return false;
535
+ if ((!room?.guard && !room?.nativeActive) || !room.native) return false;
521
536
  return room.native.command('focus', {
522
537
  ...(Number.isInteger(target.pid) && target.pid > 0 ? { pid: target.pid } : {}),
523
538
  ...(typeof target.process === 'string' && target.process ? { process: target.process } : {}),
524
539
  });
525
540
  }
526
541
 
542
+ async function guardCommand(room, cmd, data, timeout) {
543
+ const report = await room.native?.requestGuard?.(cmd, data, timeout);
544
+ if (report?.suppressedPopups > room.guard?.suppressedPopups) {
545
+ room.guard.suppressedPopups = report.suppressedPopups;
546
+ logger?.debug?.(`App child session hidden popups: ${report.suppressedPopups}`);
547
+ }
548
+ return report?.ok === true;
549
+ }
550
+
551
+ function armGuard(key, { childSessionId, pid, process }) {
552
+ if (disposed) return false;
553
+ const room = ensureRoom(key);
554
+ room.guard = { owner: 'agent', suppressedPopups: 0 };
555
+ room.nativeFailed = false;
556
+ room.native ??= startNative(room, childSessionId);
557
+ return guardCommand(room, 'guard', { pid, process, enabled: true }, 7500);
558
+ }
559
+
560
+ function setGuardOwner(key, owner) {
561
+ const room = rooms.get(key);
562
+ if (!room?.guard || room.guard.owner === owner) return;
563
+ room.guard.owner = owner;
564
+ syncViewer(key);
565
+ }
566
+
527
567
  return {
528
568
  handleStream,
529
569
  attachWsClient,
@@ -535,6 +575,16 @@ export function createAppStreamHub({ resolveSession, streamerExe, startStreamer
535
575
  pushCursor,
536
576
  captureSnapshot,
537
577
  focusTaskWindow,
578
+ armGuard,
579
+ setGuardOwner,
580
+ sweepGuard: key => {
581
+ const room = rooms.get(key);
582
+ return room?.guard ? guardCommand(room, 'sweep') : false;
583
+ },
584
+ clearPoint: (key, { x, y }) => {
585
+ const room = rooms.get(key);
586
+ return room?.guard ? guardCommand(room, 'clearPoint', { x, y }) : false;
587
+ },
538
588
  syncViewer,
539
589
  stopViewer,
540
590
  dispose,
@@ -50,11 +50,17 @@ export function startAppStreamer(exe, sessionId, { onFrame, onBounds, onExit, lo
50
50
  const closed = new Promise(resolve => child.once('close', resolve));
51
51
  let timer;
52
52
  const snapshotWaiters = [];
53
+ const guardWaiters = new Map();
54
+ let nextGuardRequest = 0;
53
55
 
54
56
  child.stderr.on('data', bytes => logger?.debug?.('computer-use: app streamer %s', bytes.toString().trim()));
55
57
  const feed = appStreamPackets((type, flags, width, height, bytes) => {
56
58
  if (type === 3) {
57
59
  const bounds = JSON.parse(bytes);
60
+ if (Number.isInteger(bounds.guardRequestId)) {
61
+ guardWaiters.get(bounds.guardRequestId)?.(bounds);
62
+ return;
63
+ }
58
64
  if (![bounds.x, bounds.y, bounds.width, bounds.height].every(Number.isInteger) ||
59
65
  bounds.width <= 0 || bounds.height <= 0 || !['dxgi', 'gdi'].includes(bounds.backend)) {
60
66
  throw new Error('invalid app-streamer desktop bounds');
@@ -95,6 +101,7 @@ export function startAppStreamer(exe, sessionId, { onFrame, onBounds, onExit, lo
95
101
  done = true;
96
102
  clearTimeout(timer);
97
103
  flushSnapshots(null);
104
+ for (const settle of guardWaiters.values()) settle(null);
98
105
  if (!stopping) onExit();
99
106
  }
100
107
  function fault(error) {
@@ -141,6 +148,20 @@ export function startAppStreamer(exe, sessionId, { onFrame, onBounds, onExit, lo
141
148
  }
142
149
  });
143
150
  }
151
+ function requestGuard(cmd, data = {}, timeoutMs = 1000) {
152
+ if (done || stopping) return Promise.resolve(null);
153
+ const requestId = ++nextGuardRequest;
154
+ return new Promise(resolve => {
155
+ const settle = value => {
156
+ clearTimeout(timeout);
157
+ guardWaiters.delete(requestId);
158
+ resolve(value);
159
+ };
160
+ const timeout = setTimeout(() => settle(null), timeoutMs).unref();
161
+ guardWaiters.set(requestId, settle);
162
+ if (!command(cmd, { ...data, requestId })) settle(null);
163
+ });
164
+ }
144
165
  function stop() {
145
166
  if (done || stopping) return closed;
146
167
  command('stop');
@@ -151,5 +172,5 @@ export function startAppStreamer(exe, sessionId, { onFrame, onBounds, onExit, lo
151
172
  timer.unref?.();
152
173
  return closed;
153
174
  }
154
- return { command, sendInput, requestKeyframe, requestSnapshot, stop };
175
+ return { command, sendInput, requestKeyframe, requestSnapshot, requestGuard, stop };
155
176
  }