@ai-workbench/connect 0.7.34 → 0.7.36
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 +23 -9
- package/client/index.cjs +33 -23
- package/helper/host-directories.cjs +43 -1
- package/lib/api.d.ts +1 -0
- package/lib/directory-session.d.ts +7 -0
- package/lib/directory-session.js +153 -0
- package/lib/enrollment.d.ts +1 -0
- package/lib/enrollment.js +4 -1
- package/lib/host-directories.d.ts +5 -1
- package/lib/host-directories.js +11 -5
- package/lib/index.js +1 -1
- package/lib/integration.d.ts +1 -1
- package/lib/integration.js +2 -2
- package/lib/needs.js +1 -1
- package/lib/ports.d.ts +1 -0
- package/lib/profile-activation.js +1 -3
- package/lib/profile-enrollment.js +11 -10
- package/lib/profile-runtime.js +6 -0
- package/lib/startup.js +4 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,17 +1,20 @@
|
|
|
1
|
-
|
|
1
|
+
员工一次安装:在官方 DSH「插件 → 添加插件」输入 `@ai-workbench/workbench`。已分装 network、connect、remote-agent 的,先移除三者,再装总包。
|
|
2
|
+
|
|
3
|
+
本轮总包0.1.1精确锁定 network 0.4.9 / connect 0.7.36 / remote-agent 0.8.27;管理员按[总包发版说明](packages/workbench/README.md)重新生成并核验固定 tgz 与 SHA。工人不 publish。
|
|
4
|
+
|
|
5
|
+
单独安装 connect:在官方 DSH「插件 → 添加插件」中选择编排已核验的 tgz 绝对路径,或输入编排已发布的精确包版本。发布由编排执行。
|
|
2
6
|
|
|
3
7
|
# 远程主机连接插件(L)
|
|
4
8
|
|
|
5
|
-
|
|
9
|
+
员工按插件名安装/更新,沿官方pnpm的24小时成熟期;未满24小时选已成熟旧版。不预置 `@ai-workbench/*` 发布时间例外,不改员工profile。验收或紧急修复由编排提供精确版本,兼容子包同批发布。历史D17诊断仍留在docs/evidence,旧scope例外不再是当前安装前置。
|
|
6
10
|
|
|
7
|
-
|
|
8
|
-
minimumReleaseAgeExclude:
|
|
9
|
-
- '@ai-workbench/*'
|
|
10
|
-
```
|
|
11
|
+
## 0.7.36 · 设置、身份复用和工作位置
|
|
11
12
|
|
|
12
|
-
|
|
13
|
+
重装后重新导入同一资料,源authkey已被N按合同清理时,L仍把不含authKeyFile的配置交N.activate,由N先验证已保存身份。L不读身份/journal或密钥字节;只有N明确NEED_ENROLLMENT才显示缺凭据,密钥明确拒绝才要求领取新凭据,空/权限/链接异常仍拒绝。N的配置路径/摘要、nodeName和默认值变更可能ENROLLMENT_MISMATCH,本单不迁移或绕过它;真实重装由编排leo复验。
|
|
13
14
|
|
|
14
|
-
|
|
15
|
+
设置页沿原生通用设置的标题/灰字说明/右侧官方按钮和细分隔线,摘要为一行说明;登录内容与一次粘贴协议保留,高级使用官方DisclosureRow默认折叠。
|
|
16
|
+
|
|
17
|
+
S0.4.25资料可含workspaceSources=["host","local"]、["host"]或["local"]。L只保存/呈现该非秘密字段,缺字段按两者显示,不补写旧源包/旧登记。添加工作区只显示允许来源,单来源直接进入并灰字说明。**这是员工界面限制,不是安全边界**;不改变既有工作区、后端选择/主机/session/bridge/policy或执行能力,不改X/N/S。
|
|
15
18
|
|
|
16
19
|
## TLS证书错误导致安装或组件下载失败(D25)
|
|
17
20
|
|
|
@@ -41,7 +44,7 @@ openssl s_client -connect registry.npmjs.org:443 -servername registry.npmjs.org
|
|
|
41
44
|
|
|
42
45
|
N消费端保持公开activate/getActivationState/onActivationState握手;L登记非秘密引用,N唯一消费/清理开通材料。本轮不改N开通语义。
|
|
43
46
|
|
|
44
|
-
D13已通过[PR15](https://github.com/yzsnstotz/ai-workbench-connect/pull/15)合推main7915df5,移除前为909eabb
|
|
47
|
+
D13已通过[PR15](https://github.com/yzsnstotz/ai-workbench-connect/pull/15)合推main7915df5,移除前为909eabb;五项被拒产物及清单引用已撤除。当时撤除的旧聚合整包和验收ZIP不再生成;10-26 owner另授权的新workbench包仅复用官方bundle机制合并已发布子包patch,见本文开头,不复活旧整包装配器。
|
|
45
48
|
|
|
46
49
|
**插件版本0.7.32,API版本保持0.7.0,旧native-local-v1能力标识已删除。** 本轮沿用现有N/X公开API,真实组合由编排验证。L导入动作固定使用官方系统目录窗口:自动能力为native时直接消费其pick;SSH等启动上下文提供browse时,明确调用同一官方原生包的公开pickNativeDirectory,不修改全局选择器。失败原因在本节技术详情准确投影。js-yaml及其传递运行依赖随tgz打包,官方宿主peer由已安装官方程序提供,员工不另装npm依赖。真实中文GUI/授权及leo E门分别留证。旧140测试/46图只属于前任draft.3;本轮证据独立记录于[第2轮证据](docs/evidence/2026-10-21-L-round2-draft4/)。不得拿旧0.6.3 tgz当native-local-v1的输入。
|
|
47
50
|
|
|
@@ -59,6 +62,17 @@ D13已通过[PR15](https://github.com/yzsnstotz/ai-workbench-connect/pull/15)合
|
|
|
59
62
|
|
|
60
63
|
仅后续新建且使用本版公开sshArgs的SSH生效,升级不会主动结束旧进程;目录查询取消和刷新由X的既有消费路径处理。
|
|
61
64
|
|
|
65
|
+
### 远程目录浏览(0.7.35)
|
|
66
|
+
|
|
67
|
+
官方 profile 中的远程目录浏览使用一个 SSH 通道和一个远程 Node 进程,按行请求多次目录列表,不再每次点击启动登录 shell、命令包装进程和目录 helper。无 profile 的内部 Runner 注入保留原单次请求供独立消费者/诊断;官方插件总是传入自己的 profile。执行前 inspect 和显式新建目录仍走原来的鲜查/创建路径,不把预取当作执行授权;新建前关闭浏览连接,下一次浏览取得新页面。
|
|
68
|
+
|
|
69
|
+
浏览 SSH 采用 OpenSSH 原生 `ControlMaster=auto`、`ControlPersist=60` 秒,并沿用现有 `ServerAliveInterval=15` / `ServerAliveCountMax=3`、严格主机信任及 N 原样 `ProxyCommand`。`DIRECTORY_CONTROL_PERSIST_SECONDS=60` 是本轮 B 类固定技术参数,给意外结束的空闲 master 保留短期回收窗口,**不是目录/登录/生成总时限**;本轮按派单不加设置,可调策略另提 C 类。正常关闭主动 `ssh -O exit`,不等这 60 秒;N 不需要新增接口。[OpenSSH 官方说明](https://man.openbsd.org/ssh_config#ControlMaster)明确复用同一已认证网络连接,连接建立时仍使用原代理。
|
|
70
|
+
|
|
71
|
+
控制 socket 位于 `<profile>/ai-workbench-connect/ssh/m-<本次随机目录>/c`;L 根、ssh 父目录及随机目录均为当前用户独占 0700,拒绝符号链接或宽权限。SSH 以当前 profile 为 cwd,ControlPath 使用该 profile 内的相对路径,避免长路径超过 macOS Unix socket 路径长度;不借用其他插件、profile 或员工的 master。当前目标完整参数变化、连接 instance/epoch/phase 变化、取消当次请求、profile 卸载会使旧浏览流失效;关闭只操作本实例的精确目录/master,不扫描或删除其他 socket。浏览进程随当前 profile 浏览连接存活,无后台轮询、总时限或自动重放;关闭目录弹窗本身不结束 profile 连接。
|
|
72
|
+
|
|
73
|
+
每页返回后在主机内预取本页可读且可进入的直接子目录首屏,只一层,不递归、不读取文件内容。单页仍按 `workspaceLocations.pageSize` 分页;预取缓存合计沿用 `commandOutputMaxBytes` 字节预算,放不下的不缓存,不截断页面。缓存仅存当前浏览进程内,下一页/目录切换会替换,创建、连接失效或卸载会清除。下一次实际点击先重验缓存目标的规范路径、身份、权限与目录时间戳,并刷新本页子条目的身份/权限;变化时重新列当前路径,预取失败也在实际点击时鲜查,不拿旧错误/旧规范路径替代。传输或协议错误明确失败,不换路径、不降级代理、不重试。
|
|
74
|
+
|
|
75
|
+
|
|
62
76
|
## 0.7.30 · 默认浏览器登录
|
|
63
77
|
|
|
64
78
|
在设置 → 远程主机连接点「登录 Claude」,插件用系统默认浏览器打开主机官方CLI生成的授权页。完成网页登录后,在Claude页面复制授权码,回到「Claude(远程主机)」行粘贴并点「完成登录」。码仅在本次内存与受保护POST正文、SSH stdin中交接,不写进命令参数、日志或状态。码不属于本次登录则明确失败;主机未确认成功时说明失败,可立即重发。登录失败后重新查官方状态,未登录重新显示按钮;无法核实保留入口并先检查再授权。
|
package/client/index.cjs
CHANGED
|
@@ -6,7 +6,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
6
6
|
"title": "Remote host connection",
|
|
7
7
|
"import": "Import connection files",
|
|
8
8
|
"importing": "Selecting and checking connection files…",
|
|
9
|
-
"enrollmentKeyMissing": "These connection files are missing setup credentials.
|
|
9
|
+
"enrollmentKeyMissing": "These connection files are missing setup credentials. Import connection files that include valid setup credentials.",
|
|
10
10
|
"imported": "Imported{employee}",
|
|
11
11
|
"importHelp": "Choose the connection files folder provided by your administrator.",
|
|
12
12
|
"enrollmentRejected": "The device setup is no longer valid. Contact your administrator; submission has stopped.",
|
|
@@ -23,7 +23,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
23
23
|
"statusSignIn": "Sign in required",
|
|
24
24
|
"loginRequired": "Sign in required",
|
|
25
25
|
"notReady": "The remote host connection is not ready. Contact your administrator.",
|
|
26
|
-
"enrollment": "
|
|
26
|
+
"enrollment": "Import connection files to connect to the company host.",
|
|
27
27
|
"settings": "The remote host connection has not been configured. Contact your administrator.",
|
|
28
28
|
"loginFailed": "This sign-in was not completed. You can start again now.",
|
|
29
29
|
"denied": "This account is currently unavailable. Contact your company account administrator.",
|
|
@@ -142,8 +142,11 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
142
142
|
"claudeLoginFailed": "Claude sign-in was not completed. You can sign in again now.",
|
|
143
143
|
"claudeLoginReportedFailure": "The host confirms Claude is signed in, but this attempt reported a failure. Check again.",
|
|
144
144
|
"enrollmentKeyRejected": "The setup link is no longer valid. Ask your administrator for a new one.",
|
|
145
|
-
"ready": "
|
|
146
|
-
"
|
|
145
|
+
"ready": "All ready",
|
|
146
|
+
"remainingTasks": "Remaining: {steps}",
|
|
147
|
+
"stepSeparator": ", ",
|
|
148
|
+
"sourceHostOnly": "Your administrator has set workspaces to use remote host folders only.",
|
|
149
|
+
"sourceLocalOnly": "Your administrator has set workspaces to use local folders only.",
|
|
147
150
|
"connectionFiles": "Connection files",
|
|
148
151
|
"networkLabel": "Network",
|
|
149
152
|
"networkConnected": "Connected to the company host",
|
|
@@ -205,7 +208,6 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
205
208
|
"need.PROJECT_BINDING_REQUIRED": "Choose a linked remote workspace in this session.",
|
|
206
209
|
"need.DISPOSED": "The connection plugin is disabled. Enable it again.",
|
|
207
210
|
"need.AUTH_STATUS_INVALID": "Unable to confirm sign-in status. Check your network, then check again.",
|
|
208
|
-
"remainingOne": "1 step remaining",
|
|
209
211
|
"statusAuthorizing": "Signing in…",
|
|
210
212
|
"parenthetical": " ({value})"
|
|
211
213
|
},
|
|
@@ -213,7 +215,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
213
215
|
"title": "远程主机连接",
|
|
214
216
|
"import": "导入连接资料",
|
|
215
217
|
"importing": "正在选择并检查连接资料…",
|
|
216
|
-
"enrollmentKeyMissing": "
|
|
218
|
+
"enrollmentKeyMissing": "这份连接资料缺少开通凭据,请导入含有效开通凭据的连接资料。",
|
|
217
219
|
"imported": "已导入{employee}",
|
|
218
220
|
"importHelp": "请选择管理员给你的连接资料文件夹",
|
|
219
221
|
"enrollmentKeyRejected": "开通链接已失效,请向管理员领取新的。",
|
|
@@ -231,7 +233,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
231
233
|
"statusSignIn": "需要登录",
|
|
232
234
|
"loginRequired": "需要登录",
|
|
233
235
|
"notReady": "远程主机连接尚未准备好,请查看技术详情。",
|
|
234
|
-
"enrollment": "
|
|
236
|
+
"enrollment": "请先导入连接资料。",
|
|
235
237
|
"settings": "远程主机连接还没有设置好,请查看技术详情。",
|
|
236
238
|
"loginFailed": "本次登录未完成,可立即重新发起。",
|
|
237
239
|
"claudeLoginFailed": "本次 Claude 登录未完成。可再次点“登录 Claude”,或稍后再试。",
|
|
@@ -349,8 +351,11 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
349
351
|
"interruptionPrefix": "与主机的连接已中断(已持续 ",
|
|
350
352
|
"interruptionSuffix": " 分钟),网络恢复后会自动重连;你可以先检查本机网络",
|
|
351
353
|
"reconfirming": "正在重新确认",
|
|
352
|
-
"ready": "
|
|
353
|
-
"
|
|
354
|
+
"ready": "全部就绪",
|
|
355
|
+
"remainingTasks": "还需:{steps}",
|
|
356
|
+
"stepSeparator": "、",
|
|
357
|
+
"sourceHostOnly": "管理员已设置为只使用远程主机目录",
|
|
358
|
+
"sourceLocalOnly": "管理员已设置为只使用本机目录",
|
|
354
359
|
"connectionFiles": "连接资料",
|
|
355
360
|
"networkLabel": "网络",
|
|
356
361
|
"networkConnected": "已连接公司主机",
|
|
@@ -412,7 +417,6 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
412
417
|
"need.PROJECT_BINDING_REQUIRED": "请在会话中选择已关联的远程工作区。",
|
|
413
418
|
"need.DISPOSED": "连接插件已卸载,需要重新启用插件。",
|
|
414
419
|
"need.AUTH_STATUS_INVALID": "暂时无法确认登录状态,可检查本机网络后重新检查。",
|
|
415
|
-
"remainingOne": "还差 1 步",
|
|
416
420
|
"statusAuthorizing": "正在登录…",
|
|
417
421
|
"parenthetical": "({value})"
|
|
418
422
|
}
|
|
@@ -439,7 +443,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
439
443
|
const UI=require('@deepseek-ai/dsh-client-ui-primitives'),Button=UI.Button,Input=UI.Input;
|
|
440
444
|
const Translation=React.createContext(null);
|
|
441
445
|
function LocaleText({id,params}){const {t}=React.useContext(Translation);return t(id,params);}
|
|
442
|
-
function NeedMessage({need,fallback='actionFailed'}){const {t}=React.useContext(Translation);return h(React.Fragment,null,t(need?.code?needKey(need.code):fallback),need?.message?h('details',null,h('summary',null,t('details')),h('pre',null,JSON.stringify({message:need.message,action:need.action},null,2))):null);}
|
|
446
|
+
function NeedMessage({need,fallback='actionFailed'}){const {t}=React.useContext(Translation);return h(React.Fragment,null,t(need?.code==='ENROLLMENT_REQUIRED'&&need.officialReason==='NEED_ENROLLMENT'?'enrollmentKeyMissing':need?.code?needKey(need.code):fallback),need?.message?h('details',null,h('summary',null,t('details')),h('pre',null,JSON.stringify({message:need.message,action:need.action},null,2))):null);}
|
|
443
447
|
function DirectoryPermissions({permissions}){const {t}=React.useContext(Translation);return h('p',null,...['read','write','execute'].map((key,index)=>(index?' · ':'')+({read:t('permissionRead'),write:t('permissionWrite'),execute:t('permissionEnter')}[key])+': '+(permissions?.[key]===true?t('allowed'):permissions?.[key]===false?t('deniedPermission'):t('unknownPermission'))),permissions?.reason?t('parenthetical',{value:permissions.reason}):'');}
|
|
444
448
|
const sameLocationContext=(state,context)=>state?.instanceId===context.instanceId&&state?.epoch===context.epoch&&state.items?.some(item=>item.workspaceId===context.workspaceId&&item.bindingId===context.expectedBindingId);
|
|
445
449
|
function WorkspaceLocationRow({item,locations,workbench}){const {t}=React.useContext(Translation);
|
|
@@ -469,8 +473,11 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
469
473
|
h('div',{style:{...actionStyle,paddingTop:16}},h(Button,{type:'button',disabled:busy||!page,onClick:()=>setFolder('')},t('newFolder')),h(Button,{type:'button',disabled:busy,'aria-pressed':showHidden,onClick:()=>setShowHidden(v=>!v)},t('showHidden')),h('span',{style:{flex:1}}),h(Button,{type:'button',disabled:saving||busy&&folder!==null,onClick:cancel},t('cancel')),h(Button,{type:'button',disabled:busy||!page,onClick:select},t('open')))),
|
|
470
474
|
folder!==null?h('section',{role:'dialog','aria-label':t('newFolder'),'aria-modal':true,style:{padding:16,border:'1px solid var(--border, #ddd)',borderRadius:8,marginTop:16}},h('h3',null,t('newFolder')),h('p',null,t('newFolderPrefix')+(page?.path??'')+t('newFolderSuffix')),h(Input,{'aria-label':t('folderName'),value:folder,autoFocus:true,disabled:busy,onChange:event=>setFolder(event.target.value)}),error?h('div',{role:'alert'},error):null,h('div',{style:{...actionStyle,justifyContent:'flex-end',paddingTop:12}},h(Button,{type:'button',disabled:busy,onClick:()=>setFolder(null)},t('cancel')),h(Button,{type:'button',disabled:busy||!folder||['.','..'].includes(folder)||/[\\/]/.test(folder),onClick:async()=>{if(await createFolder(folder))setFolder(null);}},t('create')))):null);
|
|
471
475
|
}
|
|
476
|
+
const emptyPickerSnapshot={};const emptyPickerSubscribe=()=>()=>{};const getEmptyPickerSnapshot=()=>emptyPickerSnapshot;
|
|
472
477
|
function WorkspaceDirectoryFlow(props){return h(Translation.Provider,{value:{t:props.t}},h(WorkspaceDirectoryFlowBody,props));}
|
|
473
478
|
function WorkspaceDirectoryFlowBody(props){const {t}=React.useContext(Translation);
|
|
479
|
+
const sourceSnapshot=React.useSyncExternalStore(props.workbench.subscribe??emptyPickerSubscribe,props.workbench.getSnapshot??getEmptyPickerSnapshot);
|
|
480
|
+
const sources=sourceSnapshot.value?.enrollment?.workspaceSources??['local','host'],sourceKey=sources.join(','),onlySource=sources.length===1?sources[0]:undefined;
|
|
474
481
|
const {open,workbench}=props,[page,setPage]=React.useState(null),[busy,setBusy]=React.useState(false),[error,setError]=React.useState(''),[target,setTarget]=React.useState(null),[saving,setSaving]=React.useState(false),[creating,setCreating]=React.useState(false);
|
|
475
482
|
const live=React.useRef(true),active=React.useRef(false),generation=React.useRef(0),locked=React.useRef(false),savingRef=React.useRef(false),lastOpen=React.useRef(false),outcome=React.useRef(props);outcome.current=props;
|
|
476
483
|
if(lastOpen.current!==open){lastOpen.current=open;generation.current++;active.current=!!open;locked.current=false;savingRef.current=false;}
|
|
@@ -494,12 +501,12 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
494
501
|
if(value.target==='local'){setPage(null);await pickLocal(at);}else setPage(append&&previous?.target==='host'&&previous.path===value.path?{...value,entries:[...previous.entries,...value.entries.filter(entry=>!previous.entries.some(old=>old.path===entry.path))]}:value);
|
|
495
502
|
}catch{if(current(at))setError(h(LocaleText,{id:savingRef.current?'workspaceAddUnknown':'directoryReadFailed'}));}finally{if(current(at)){locked.current=false;savingRef.current=false;setSaving(false);setBusy(false);}}
|
|
496
503
|
};
|
|
497
|
-
React.useEffect(()=>{savingRef.current=false;setSaving(false);if(open){active.current=true;generation.current++;locked.current=false;setTarget(null);setPage(null);setError('');setBusy(false);}else{setPage(null);setError('');setBusy(false);}},[open]);
|
|
504
|
+
React.useEffect(()=>{savingRef.current=false;setSaving(false);if(open){active.current=true;generation.current++;locked.current=false;setTarget(null);setPage(null);setError('');setBusy(false);if(onlySource)void browse({target:onlySource});}else{setPage(null);setError('');setBusy(false);}},[open,sourceKey]);
|
|
498
505
|
const cancel=()=>{if(!active.current||savingRef.current)return;active.current=false;generation.current++;locked.current=false;setPage(null);setBusy(false);outcome.current.onCancel();};
|
|
499
506
|
const select=async()=>{if(!active.current||locked.current||!page)return;locked.current=true;setBusy(true);setError('');const at=generation.current;try{await commit(page,at);}catch{if(current(at))setError(h(LocaleText,{id:'workspaceAddUnknown'}));}finally{if(current(at)){locked.current=false;savingRef.current=false;setSaving(false);setBusy(false);}}};
|
|
500
507
|
const createFolder=async(name)=>{if(!active.current||locked.current||!page)return false;locked.current=true;savingRef.current=true;setBusy(true);setError('');const at=generation.current;try{const result=await workbench.createWorkspaceDirectory({selectionToken:page.selectionToken,name});if(!current(at))return false;if(!result?.ok){setError(pickerNeedText(result?.error,'folderCreateFailed'));return false;}setPage(result.value);return true;}catch{if(current(at))setError(h(LocaleText,{id:'folderCreateUnknown'}));return false;}finally{if(current(at)){locked.current=false;savingRef.current=false;setBusy(false);}}};
|
|
501
508
|
if(!open)return null;
|
|
502
|
-
return h('section',{role:'dialog','aria-modal':true,'aria-label':t('chooseWorkspace'),style:{position:'fixed',inset:0,zIndex:100,background:'rgba(0,0,0,.25)',display:'flex',alignItems:'center',justifyContent:'center'}},h('div',{style:{background:'var(--
|
|
509
|
+
return h('section',{role:'dialog','aria-modal':true,'aria-label':t('chooseWorkspace'),style:{position:'fixed',inset:0,zIndex:100,background:'rgba(0,0,0,.25)',display:'flex',alignItems:'center',justifyContent:'center'}},h('div',{style:{background:'var(--dsw-alias-bg-layer-2)',color:'var(--dsw-alias-label-primary)',border:'1px solid var(--dsw-alias-border-l2)',borderRadius:12,padding:24,width:'min(720px,90vw)',maxHeight:'85vh',overflow:'auto',boxShadow:'0 12px 40px rgba(0,0,0,.2)'}},h('h2',null,t('chooseWorkspace')),onlySource?h('p',{style:descriptionStyle},t(onlySource==='host'?'sourceHostOnly':'sourceLocalOnly')):h('div',{'aria-label':t('deviceLocation'),style:{display:'flex',gap:8}},...sources.map(value=>h(Button,{key:value,type:'button',disabled:busy||creating,'aria-pressed':target===value,onClick:()=>browse({target:value})},value==='local'?t('local'):t('remoteHost')))),
|
|
503
510
|
target===null?h(React.Fragment,null,h('p',null,t('chooseDevice')),h(Button,{type:'button',onClick:cancel},t('cancel'))):target==='host'?h(RemoteWorkspaceBrowser,{page,busy,error,browse,select,cancel,createFolder,saving,onCreateOpenChange:setCreating}):h(React.Fragment,null,h('p',{role:'status'},busy?saving?t('addingWorkspace'):t('systemChooseFolder'):t('systemFolderHelp')),error?h('div',{role:'alert'},error):null,h(Button,{type:'button',disabled:busy,onClick:()=>browse({target:'local'})},t('chooseFolder')),h(Button,{type:'button',disabled:saving,onClick:cancel},t('cancel')))));
|
|
504
511
|
}
|
|
505
512
|
function createWorkspaceDirectoryPickerRegistration(ctx,workbench){
|
|
@@ -528,7 +535,7 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
528
535
|
function BrowserLogin({value,action}){
|
|
529
536
|
const {t}=React.useContext(Translation),[code,setCode]=React.useState('');
|
|
530
537
|
const submit=event=>{event.preventDefault();const trimmed=code.trim();if(!trimmed||value.phase!=='waiting')return;setCode('');return action('/login-code/'+value.id,{code:trimmed});};
|
|
531
|
-
return h('div',{'aria-label':t('provider',{brand:value.provider==='claude'?'Claude':'Codex'}),style:{paddingTop:12,paddingBottom:16,paddingLeft:
|
|
538
|
+
return h('div',{'aria-label':t('provider',{brand:value.provider==='claude'?'Claude':'Codex'}),style:{paddingTop:12,paddingBottom:16,paddingLeft:0,display:'grid',gap:16,minWidth:0}},
|
|
532
539
|
value.provider==='codex'?h('div',{style:{display:'grid',gap:8}},h('p',{style:{margin:0}},t('deviceHelp')),h('div',{style:{display:'flex',alignItems:'center',gap:8,minWidth:0}},h('code',{style:{fontSize:24,fontFamily:'var(--dsh-font-family-code-default, monospace)',letterSpacing:'.12em',userSelect:'text',overflowWrap:'anywhere',minWidth:0}},value.deviceCode),h(Copy,{text:value.deviceCode,label:t('copy')+' '+value.deviceCode}))):null,
|
|
533
540
|
h('div',null,h(Button,{type:'button',variant:'primary',onClick:()=>void action('/open-login/'+value.id)},t(value.provider==='claude'?'openAuthorization':'openPage'))),
|
|
534
541
|
h('div',{style:{display:'grid',gap:8,minWidth:0}},h('span',null,t('loginLink')),h('div',{style:{display:'flex',alignItems:'flex-start',gap:8,minWidth:0}},h('code',{style:{overflowWrap:'anywhere',userSelect:'text',fontFamily:'var(--dsh-font-family-code-default, monospace)',fontSize:12,minWidth:0}},value.url),h(Copy,{text:value.url,label:t('copy')+' '+t('loginLink')}))),
|
|
@@ -548,7 +555,10 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
548
555
|
const [,update]=React.useState(0);React.useEffect(()=>{if(recovery?.phase!=='reconnecting'||!Number.isFinite(recovery.startedAt))return;const timer=setInterval(()=>update(n=>n+1),60000);return()=>clearInterval(timer);},[recovery?.phase,recovery?.startedAt]);
|
|
549
556
|
if(recovery?.phase!=='reconnecting'||!Number.isFinite(recovery.startedAt))return null;return h('p',{role:'status'},t('interruptionPrefix')+Math.max(0,Math.floor((Date.now()-recovery.startedAt)/60000))+t('interruptionSuffix'));
|
|
550
557
|
}
|
|
551
|
-
|
|
558
|
+
const descriptionStyle={fontSize:12,lineHeight:'18px',color:'var(--dsw-alias-label-secondary)'};
|
|
559
|
+
function SettingsRow({title,status,action,children,error}){return h('div',{style:{borderBottom:'.5px solid var(--dsw-alias-border-l2)',padding:'16px 0'}},h('div',{style:{display:'flex',alignItems:'center',justifyContent:'space-between',gap:24}},h('div',{style:{flex:1,minWidth:0}},h('div',{style:{fontSize:14,lineHeight:'20px',fontWeight:400}},title),h('div',{style:{...descriptionStyle,marginTop:4,...error?{color:'var(--dsw-alias-state-error-primary)'}:{}}},status)),action?h('div',{style:{flexShrink:0}},action):null),children);}
|
|
560
|
+
function Advanced({t,children}){const [open,setOpen]=React.useState(false);return h('div',{style:{marginTop:24}},h(UI.DisclosureRow,{title:t('advanced'),icon:h(UI.IconChevronRightOutlineRegular,{'aria-hidden':true}),open,expandable:true,expandOnRowClick:true,onToggle:()=>setOpen(value=>!value)},children));}
|
|
561
|
+
|
|
552
562
|
function providerStatus(s,provider){const checking=!s||s.phase==='checking'||s.checkingProviders?.includes(provider),unknown=!!s?.providerNeeds?.[provider]||s?.logins?.[provider]===undefined;return {checking,unknown,ready:!checking&&!unknown&&s?.logins?.[provider]===true,needsLogin:!checking&&!unknown&&s?.logins?.[provider]===false};}
|
|
553
563
|
function Panel(props){return h(Translation.Provider,{value:{t:props.t}},h(PanelBody,props));}
|
|
554
564
|
function PanelBody({workbench,t}){
|
|
@@ -559,22 +569,22 @@ window.__ModuleLoader__.load({id:'@ai-workbench/connect',factory:(require)=>{
|
|
|
559
569
|
const loginFailure=s?.technicalDetails?.code==='LOGIN_FAILED',failure=s?.technicalDetails?.loginFailureMessage;
|
|
560
570
|
const handledFailure=loginFailure||['codex','claude'].some(provider=>s?.providerNeeds?.[provider]?.code==='LOGIN_FAILED');
|
|
561
571
|
const generalError=error&&!(error==='LOGIN_FAILED'&&handledFailure)&&![enrollmentError,networkError].includes(error)&&!reconfirming?error:undefined;
|
|
562
|
-
return h('section',{'aria-label':t('title')},h('
|
|
572
|
+
return h('section',{'aria-label':t('title')},h('p',{role:'status','data-connect-summary':true,style:{...descriptionStyle,margin:'16px 0 0'}},steps.length?t('remainingTasks',{steps:steps.join(t('stepSeparator'))}):t('ready')),
|
|
563
573
|
reconfirming?h('p',{role:'status'},t('reconfirming')):null,
|
|
564
574
|
h('fieldset',{disabled:!!reconfirming,style:{border:0,padding:0,margin:0,minWidth:0}},
|
|
565
|
-
h(
|
|
566
|
-
h(
|
|
575
|
+
h(SettingsRow,{title:t('connectionFiles'),error:!!enrollmentError,status:imported?t('imported',{employee:enrollment.username?t('parenthetical',{value:enrollment.username}):''}):enrollmentError?t(enrollmentError==='ENROLLMENT_REQUIRED'?'enrollmentKeyMissing':needKey(enrollmentError)):t(enrollment?.phase==='importing'?'importing':'importHelp'),action:imported?null:h(Button,{type:'button',variant:'outline',disabled:enrollment?.phase==='importing'||['ENROLLMENT_KEY_REJECTED','ENROLLMENT_REJECTED'].includes(enrollmentError),onClick:()=>void action('/enrollment/import')},t('import'))}),
|
|
576
|
+
h(SettingsRow,{title:t('networkLabel'),error:!!networkError,status:connected?t('networkConnected'):state?.connection?.recovery?.phase==='reconnecting'?h(ConnectionInterruption,{recovery:state.connection.recovery}):networkError?h(NeedMessage,{need:state.connection.need}):t(!imported?'networkWaiting':state?.connection?.phase==='connecting'?'networkChecking':'unknown'),action:h(Button,{type:'button',variant:'outline',onClick:()=>void action()},t('recheck'))}),
|
|
567
577
|
...['codex','claude'].map(provider=>{
|
|
568
578
|
const brand=provider==='claude'?'Claude':'Codex',{checking,unknown,ready}=providerStatus(s,provider),active=state?.browserLogin?.provider===provider&&s?.phase==='authorizing',question=isLoginQuestion(state)&&s.provider===provider;
|
|
569
579
|
const allowed=!checking&&(s?.logins?.[provider]===false&&!unknown||provider==='claude'&&unknown&&!['checking','disposed'].includes(s?.phase));
|
|
570
|
-
return h(
|
|
580
|
+
return h(SettingsRow,{key:provider,title:t('provider',{brand}),status:t(active?'statusAuthorizing':checking?'statusChecking':unknown?'statusUnknown':ready?'statusSignedIn':'statusSignIn'),action:!active&&allowed?h(Button,{type:'button',variant:'outline',disabled:s?.phase==='authorizing',onClick:()=>void action(question?'/respond/'+s.requestId+'/authorize':'/start-login/'+provider+'/'+s.instanceId+'/'+s.revision)},t('signIn',{brand})):!active&&!checking&&unknown?h(Button,{type:'button',variant:'outline',disabled:s?.phase==='authorizing',onClick:()=>void action()},t('recheck')):null},
|
|
571
581
|
active?h(BrowserLogin,{key:state.browserLogin.id,value:state.browserLogin,action}):null,
|
|
572
|
-
s?.providerNeeds?.[provider]&&!(provider==='claude'&&loginFailure)?h('div',{role:'alert',style:{
|
|
573
|
-
provider==='claude'&&loginFailure?h('p',{role:'alert',style:{
|
|
582
|
+
s?.providerNeeds?.[provider]&&!(provider==='claude'&&loginFailure)?h('div',{role:'alert',style:{...descriptionStyle,color:'var(--dsw-alias-state-error-primary)',marginTop:4}},h(NeedMessage,{need:s.providerNeeds[provider]})):null,
|
|
583
|
+
provider==='claude'&&loginFailure?h('p',{role:'alert',style:{...descriptionStyle,color:'var(--dsw-alias-state-error-primary)',marginTop:4}},t(ready?'claudeLoginReportedFailure':failure?.includes('不属于本次登录')?'invalidCode':failure?.includes('主机未确认成功')?'hostLoginFailed':'claudeLoginFailed')):null);
|
|
574
584
|
}),
|
|
575
|
-
generalError?h('p',{role:'alert'},t(needKey(generalError))):null),
|
|
585
|
+
generalError?h('p',{role:'alert',style:{...descriptionStyle,color:'var(--dsw-alias-state-error-primary)'}},t(needKey(generalError))):null),
|
|
576
586
|
reconfirming?h(Button,{type:'button',variant:'outline',onClick:()=>void action()},t('recheck')):null,
|
|
577
|
-
h(
|
|
587
|
+
h(Advanced,{t},!state?.workspaceLocations?h('p',null,t('workspaceLimit')):null,workbench.directoryPickerRegistration?h(WorkspacePickerSettings,{registration:workbench.directoryPickerRegistration}):null,h(WorkspaceLocations,{state,workbench}),h(Details,{state,error,t}),h(ConversationLog,{workbench})));
|
|
578
588
|
}
|
|
579
589
|
return {name:'ai-workbench-connect-client',inject:['slots','locale','uiWorkspace'],createWorkbenchController,WorkspaceDirectoryFlow,RemoteWorkspaceBrowser,createWorkspaceDirectoryPickerRegistration,Panel,dictionaries,apply(ctx){
|
|
580
590
|
ctx.effect(()=>ctx.locale.register(NS,dictionaries));const t=ctx.locale.bind(NS);
|
|
@@ -70,5 +70,47 @@ async function main(){
|
|
|
70
70
|
let result;try{result=await execute(JSON.parse(input));}catch{result=error('PROJECT_PROTOCOL_INVALID');}
|
|
71
71
|
process.stdout.write(JSON.stringify(result)+'\n');
|
|
72
72
|
}
|
|
73
|
-
|
|
73
|
+
// One remote Node process per browsing connection. Speculation is one level only,
|
|
74
|
+
// shares the existing output budget, and never authorizes execution or selection.
|
|
75
|
+
async function serve(maxBytes){
|
|
76
|
+
const {StringDecoder}=require('node:string_decoder');const decoder=new StringDecoder('utf8');
|
|
77
|
+
let buffer='',cache=new Map(),prefetchGeneration=0;
|
|
78
|
+
const cacheKey=r=>JSON.stringify([r?.operation,r?.path??null,r?.after??null,r?.pageSize,r?.maxOutputBytes]);
|
|
79
|
+
async function respond(frame){
|
|
80
|
+
if(!frame||Object.keys(frame).sort().join(',')!=='id,request'||typeof frame.id!=='string')throw new Error('PROJECT_PROTOCOL_INVALID');
|
|
81
|
+
const request=frame.request,key=cacheKey(request),saved=cache.get(key);
|
|
82
|
+
let result=saved?await saved:await execute(request);
|
|
83
|
+
// Re-observe a prefetched directory at click time: changed links, permissions,
|
|
84
|
+
// or entries must not return an old canonical path or a stale listing.
|
|
85
|
+
if(saved&&!result.ok)result=await execute(request);
|
|
86
|
+
else if(saved&&result.ok){
|
|
87
|
+
let current;try{current=await observe(request.path);}catch(exception){result=error(classify(exception),exception);}
|
|
88
|
+
if(current){
|
|
89
|
+
let changed=JSON.stringify(current)!==JSON.stringify((({entries,nextAfter,...info})=>info)(result.value));
|
|
90
|
+
if(!changed)try{for(const entry of result.value.entries){if(JSON.stringify(await directoryEntry(entry.requestedPath,entry.name))!==JSON.stringify(entry)){changed=true;break;}}}catch{changed=true;}
|
|
91
|
+
if(changed)result=await execute(request);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const mine=++prefetchGeneration;cache=new Map();
|
|
95
|
+
const line=JSON.stringify({id:frame.id,result})+'\n';
|
|
96
|
+
process.stdout.write(Buffer.byteLength(line)>maxBytes?JSON.stringify({id:frame.id,result:error('HOST_DIRECTORY_PAGE_TOO_LARGE')})+'\n':line);
|
|
97
|
+
if(request?.operation!=='browse'||!result.ok)return;
|
|
98
|
+
const nextCache=cache;let bytes=0;
|
|
99
|
+
// No recursion: execute() never calls serve() or starts another prefetch.
|
|
100
|
+
void (async()=>{for(const entry of result.value.entries){
|
|
101
|
+
if(mine!==prefetchGeneration)break;
|
|
102
|
+
if(entry.errorCode||entry.permissions.read!==true||entry.permissions.execute!==true)continue;
|
|
103
|
+
const child={...request,path:entry.requestedPath};delete child.after;
|
|
104
|
+
const key=cacheKey(child),pending=execute(child);nextCache.set(key,pending);
|
|
105
|
+
const value=await pending;bytes+=Buffer.byteLength(JSON.stringify(value));
|
|
106
|
+
if(bytes>maxBytes){nextCache.delete(key);break;}
|
|
107
|
+
}})().catch(()=>{prefetchGeneration++;cache.clear();process.exitCode=1;process.stdin.destroy();});
|
|
108
|
+
}
|
|
109
|
+
for await(const chunk of process.stdin){
|
|
110
|
+
buffer+=decoder.write(chunk);if(Buffer.byteLength(buffer)>maxBytes)throw new Error('HOST_DIRECTORY_PAGE_TOO_LARGE');
|
|
111
|
+
let end;while((end=buffer.indexOf('\n'))!==-1){const line=buffer.slice(0,end);buffer=buffer.slice(end+1);await respond(JSON.parse(line));}
|
|
112
|
+
}
|
|
113
|
+
prefetchGeneration++;cache.clear();if(buffer||decoder.end())throw new Error('PROJECT_PROTOCOL_INVALID');
|
|
114
|
+
}
|
|
115
|
+
module.exports={execute,serve};
|
|
74
116
|
if(require.main===module)void main();
|
package/lib/api.d.ts
CHANGED
|
@@ -120,6 +120,7 @@ export interface HostSessionProjectTarget {
|
|
|
120
120
|
target: SshTarget;
|
|
121
121
|
}
|
|
122
122
|
export interface EnrollmentState {
|
|
123
|
+
workspaceSources?: ('host' | 'local')[];
|
|
123
124
|
instanceId: string;
|
|
124
125
|
revision: number;
|
|
125
126
|
phase: 'empty' | 'importing' | 'imported' | 'blocked';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { SshTarget } from './api.ts';
|
|
2
|
+
export declare const DIRECTORY_CONTROL_PERSIST_SECONDS = 60;
|
|
3
|
+
export declare function createDirectorySession(profileDir: string, maxBytes: number): {
|
|
4
|
+
request(target: SshTarget, request: unknown, signal: AbortSignal): Promise<string>;
|
|
5
|
+
reset(): Promise<void>;
|
|
6
|
+
dispose(): Promise<void>;
|
|
7
|
+
};
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { readFile, mkdtemp, realpath, rm, lstat } from 'node:fs/promises';
|
|
3
|
+
import { join, relative } from 'node:path';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
6
|
+
import { sshArgs } from "./ssh.js";
|
|
7
|
+
import { privateDirectory } from "./private-files.js";
|
|
8
|
+
import { AuthDiagnosticError } from "./auth-diagnostics.js";
|
|
9
|
+
// B-class fixed transport policy, documented in README; not a business deadline.
|
|
10
|
+
export const DIRECTORY_CONTROL_PERSIST_SECONDS = 60;
|
|
11
|
+
export function createDirectorySession(profileDir, maxBytes) {
|
|
12
|
+
let current;
|
|
13
|
+
let tail = Promise.resolve(), generation = 0, disposed = false;
|
|
14
|
+
const failure = (reason) => new AuthDiagnosticError({ stage: 'directory-stream', reason });
|
|
15
|
+
async function close() {
|
|
16
|
+
const old = current;
|
|
17
|
+
if (!old)
|
|
18
|
+
return;
|
|
19
|
+
old.failure ??= failure('CONNECTION_LOST');
|
|
20
|
+
old.pending?.reject(old.failure);
|
|
21
|
+
old.pending = undefined;
|
|
22
|
+
if (old.child.exitCode === null && old.child.signalCode === null)
|
|
23
|
+
old.child.kill('SIGTERM');
|
|
24
|
+
// Only this instance's private master, never another profile's connection.
|
|
25
|
+
const exitCode = await new Promise((resolve, reject) => { const child = spawn('ssh', ['-O', 'exit', ...old.args], { cwd: profileDir, stdio: 'ignore', shell: false, env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined } }); child.once('error', () => reject(failure('MASTER_CLEANUP_FAILED'))); child.once('close', code => resolve(code)); });
|
|
26
|
+
if (exitCode !== 0)
|
|
27
|
+
try {
|
|
28
|
+
await lstat(join(old.directory, 'c'));
|
|
29
|
+
throw failure('MASTER_CLEANUP_FAILED');
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
if (error.code !== 'ENOENT')
|
|
33
|
+
throw error;
|
|
34
|
+
}
|
|
35
|
+
await old.closed;
|
|
36
|
+
try {
|
|
37
|
+
await lstat(join(old.directory, 'c'));
|
|
38
|
+
throw failure('MASTER_CLEANUP_FAILED');
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
if (error.code !== 'ENOENT')
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
await rm(old.directory, { recursive: true, force: true });
|
|
45
|
+
if (current === old)
|
|
46
|
+
current = undefined;
|
|
47
|
+
}
|
|
48
|
+
async function open(target) {
|
|
49
|
+
const key = JSON.stringify(target);
|
|
50
|
+
if (current?.target === key && !current.failure)
|
|
51
|
+
return current;
|
|
52
|
+
await close();
|
|
53
|
+
if (await realpath(profileDir) !== profileDir)
|
|
54
|
+
throw failure('PRIVATE_DIRECTORY_REQUIRED');
|
|
55
|
+
const root = join(profileDir, 'ai-workbench-connect');
|
|
56
|
+
await privateDirectory(root);
|
|
57
|
+
if (await realpath(root) !== root)
|
|
58
|
+
throw failure('PRIVATE_DIRECTORY_REQUIRED');
|
|
59
|
+
const sockets = join(root, 'ssh');
|
|
60
|
+
await privateDirectory(sockets);
|
|
61
|
+
const directory = await mkdtemp(join(sockets, 'm-'));
|
|
62
|
+
// A relative Unix socket path avoids macOS sun_path limits for long profile paths.
|
|
63
|
+
const control = './' + relative(profileDir, join(directory, 'c'));
|
|
64
|
+
const args = ['-o', 'ControlMaster=auto', '-o', 'ControlPath=' + JSON.stringify(control.replaceAll('%', '%%')), '-o', 'ControlPersist=' + DIRECTORY_CONTROL_PERSIST_SECONDS, ...sshArgs(target)];
|
|
65
|
+
try {
|
|
66
|
+
const source = await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
|
|
67
|
+
const command = 'node -e ' + "'" + (source + '\nserve(' + maxBytes + ');').replaceAll("'", "'\\''") + "'";
|
|
68
|
+
const child = spawn('ssh', [...args, command], { cwd: profileDir, shell: false, stdio: ['pipe', 'pipe', 'pipe'], env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined } });
|
|
69
|
+
let done = () => { };
|
|
70
|
+
const closed = new Promise(resolve => done = resolve);
|
|
71
|
+
const session = { target: key, child, closed, directory, args };
|
|
72
|
+
current = session;
|
|
73
|
+
const stop = (reason) => { session.failure ??= failure(reason); session.pending?.reject(session.failure); session.pending = undefined; if (child.exitCode === null && child.signalCode === null)
|
|
74
|
+
child.kill('SIGTERM'); };
|
|
75
|
+
const decoder = new StringDecoder('utf8');
|
|
76
|
+
let buffer = '';
|
|
77
|
+
child.stdout.on('data', (chunk) => {
|
|
78
|
+
buffer += decoder.write(chunk);
|
|
79
|
+
if (Buffer.byteLength(buffer) > maxBytes) {
|
|
80
|
+
stop('OUTPUT_LIMIT_EXCEEDED');
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
let end;
|
|
84
|
+
while ((end = buffer.indexOf('\n')) !== -1) {
|
|
85
|
+
const line = buffer.slice(0, end);
|
|
86
|
+
buffer = buffer.slice(end + 1);
|
|
87
|
+
try {
|
|
88
|
+
const frame = JSON.parse(line);
|
|
89
|
+
if (!session.pending || !frame || Object.keys(frame).sort().join(',') !== 'id,result' || frame.id !== session.pending.id)
|
|
90
|
+
throw Error();
|
|
91
|
+
const pending = session.pending;
|
|
92
|
+
session.pending = undefined;
|
|
93
|
+
pending.resolve(JSON.stringify(frame.result));
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
stop('PROJECT_PROTOCOL_INVALID');
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
child.stderr.on('data', () => stop('SSH_STDERR_NONEMPTY'));
|
|
102
|
+
child.stdin.on('error', () => stop('STDIN_FAILED'));
|
|
103
|
+
child.once('error', () => stop('SPAWN_FAILED'));
|
|
104
|
+
child.once('close', () => { stop('CONNECTION_LOST'); done(); });
|
|
105
|
+
return session;
|
|
106
|
+
}
|
|
107
|
+
catch (error) {
|
|
108
|
+
await rm(directory, { recursive: true, force: true });
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
request(target, request, signal) {
|
|
114
|
+
const mine = generation;
|
|
115
|
+
const task = tail.then(async () => {
|
|
116
|
+
if (disposed || signal.aborted || mine !== generation)
|
|
117
|
+
throw failure('CANCELLED');
|
|
118
|
+
const session = await open(target);
|
|
119
|
+
if (disposed || signal.aborted || mine !== generation) {
|
|
120
|
+
await close();
|
|
121
|
+
throw failure('CANCELLED');
|
|
122
|
+
}
|
|
123
|
+
if (session.failure)
|
|
124
|
+
throw session.failure;
|
|
125
|
+
const id = randomUUID(), line = JSON.stringify({ id, request }) + '\n';
|
|
126
|
+
if (Buffer.byteLength(line) > maxBytes)
|
|
127
|
+
throw failure('OUTPUT_LIMIT_EXCEEDED');
|
|
128
|
+
const abort = () => { session.failure ??= failure('CANCELLED'); session.pending?.reject(session.failure); session.pending = undefined; session.child.kill('SIGTERM'); };
|
|
129
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
130
|
+
try {
|
|
131
|
+
return await new Promise((resolve, reject) => { session.pending = { id, resolve, reject }; if (signal.aborted)
|
|
132
|
+
abort();
|
|
133
|
+
else
|
|
134
|
+
session.child.stdin.write(line); });
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
signal.removeEventListener('abort', abort);
|
|
138
|
+
if (session.failure)
|
|
139
|
+
await close();
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
tail = task.catch(() => { });
|
|
143
|
+
return task;
|
|
144
|
+
},
|
|
145
|
+
reset() { generation++; const task = tail.then(close); tail = task.catch(() => { }); if (current) {
|
|
146
|
+
current.failure ??= failure('CONNECTION_LOST');
|
|
147
|
+
current.pending?.reject(current.failure);
|
|
148
|
+
current.pending = undefined;
|
|
149
|
+
current.child.kill('SIGTERM');
|
|
150
|
+
} return task; },
|
|
151
|
+
dispose() { disposed = true; return this.reset(); },
|
|
152
|
+
};
|
|
153
|
+
}
|
package/lib/enrollment.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
1
|
import type { Result } from './api.ts';
|
|
2
2
|
import type { Enrollment } from './ports.ts';
|
|
3
|
+
export declare function validWorkspaceSources(value: unknown): value is ('host' | 'local')[];
|
|
3
4
|
export declare function readEnrollment(packageDir: string, trustDir: string, maxMetadataBytes?: number): Promise<Result<Enrollment>>;
|
package/lib/enrollment.js
CHANGED
|
@@ -3,6 +3,7 @@ import { join, isAbsolute } from 'node:path';
|
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { fail, ok } from "./needs.js";
|
|
5
5
|
import { privateDirectory, privateFile, readPrivate } from "./private-files.js";
|
|
6
|
+
export function validWorkspaceSources(value) { return Array.isArray(value) && value.length > 0 && value.length <= 2 && value.every(source => source === 'host' || source === 'local') && new Set(value).size === value.length; }
|
|
6
7
|
export async function readEnrollment(packageDir, trustDir, maxMetadataBytes) {
|
|
7
8
|
try {
|
|
8
9
|
if (!isAbsolute(packageDir) || !isAbsolute(trustDir))
|
|
@@ -11,6 +12,8 @@ export async function readEnrollment(packageDir, trustDir, maxMetadataBytes) {
|
|
|
11
12
|
if (!dir.isDirectory() || dir.isSymbolicLink() || dir.uid !== process.getuid() || (dir.mode & 0o077) !== 0)
|
|
12
13
|
return fail('ENROLLMENT_INVALID');
|
|
13
14
|
const wire = JSON.parse(await readPrivate(join(packageDir, 'enroll.json'), maxMetadataBytes));
|
|
15
|
+
if (wire.workspaceSources !== undefined && !validWorkspaceSources(wire.workspaceSources))
|
|
16
|
+
return fail('ENROLLMENT_INVALID');
|
|
14
17
|
if (wire.schemaVersion !== 1 || !/^emp-[a-z0-9][a-z0-9-]*$/.test(wire.employee?.username) || wire.employee.username.length > 32)
|
|
15
18
|
return fail('ENROLLMENT_INVALID');
|
|
16
19
|
const user = wire.employee.username, home = '/Users/' + user;
|
|
@@ -63,7 +66,7 @@ export async function readEnrollment(packageDir, trustDir, maxMetadataBytes) {
|
|
|
63
66
|
await rm(temp, { force: true });
|
|
64
67
|
}
|
|
65
68
|
}
|
|
66
|
-
return ok({ authKeyFile, host: wire.host.name, username: user, port: wire.host.sshPort, projectRoot: wire.employee.projectsRoot, knownHostsFile: destination, session: { command: wire.session.command, root: wire.session.root, settingsPath: wire.session.settingsPath, protocolVersion: 1 } });
|
|
69
|
+
return ok({ ...wire.workspaceSources === undefined ? {} : { workspaceSources: [...wire.workspaceSources] }, authKeyFile, host: wire.host.name, username: user, port: wire.host.sshPort, projectRoot: wire.employee.projectsRoot, knownHostsFile: destination, session: { command: wire.session.command, root: wire.session.root, settingsPath: wire.session.settingsPath, protocolVersion: 1 } });
|
|
67
70
|
}
|
|
68
71
|
catch {
|
|
69
72
|
return fail('ENROLLMENT_INVALID');
|
|
@@ -47,8 +47,12 @@ export interface HostDirectoryRequest {
|
|
|
47
47
|
pageSize: number;
|
|
48
48
|
}
|
|
49
49
|
export interface HostDirectories {
|
|
50
|
+
reset?(): Promise<void>;
|
|
51
|
+
dispose?(): Promise<void>;
|
|
50
52
|
browse(target: SshTarget, data: HostDirectoryRequest, signal: AbortSignal): Promise<Result<HostDirectoryData>>;
|
|
51
53
|
inspect(target: SshTarget, path: string, signal: AbortSignal): Promise<Result<Pick<HostDirectoryInfo, 'path'>>>;
|
|
52
54
|
create?(target: SshTarget, path: string, name: string, signal: AbortSignal): Promise<Result<HostDirectoryInfo>>;
|
|
53
55
|
}
|
|
54
|
-
export declare function createHostDirectories(runner: Runner, maxOutputBytes: number
|
|
56
|
+
export declare function createHostDirectories(runner: Runner, maxOutputBytes: number, options?: {
|
|
57
|
+
profileDir: string;
|
|
58
|
+
}): HostDirectories;
|
package/lib/host-directories.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createDirectorySession } from "./directory-session.js";
|
|
1
2
|
import { readFile } from 'node:fs/promises';
|
|
2
3
|
import { runRemote } from "./ssh.js";
|
|
3
4
|
import { fail, ok } from "./needs.js";
|
|
@@ -21,16 +22,21 @@ function validEntry(value, parent) {
|
|
|
21
22
|
return validPath(value.path) && validIdentity(value.identity);
|
|
22
23
|
}
|
|
23
24
|
const binaryCompare = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
|
|
24
|
-
export function createHostDirectories(runner, maxOutputBytes) {
|
|
25
|
+
export function createHostDirectories(runner, maxOutputBytes, options) {
|
|
26
|
+
const session = options ? createDirectorySession(options.profileDir, maxOutputBytes) : undefined;
|
|
25
27
|
async function request(target, operation, data, signal) {
|
|
26
28
|
if (signal.aborted)
|
|
27
29
|
return fail('CONNECTION_LOST');
|
|
28
30
|
if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1 || data.path !== undefined && !validPath(data.path) || operation === 'create' && (!validPath(data.path) || !validName(data.name)) || operation === 'inspect' && data.path === undefined || operation === 'browse' && (!Number.isSafeInteger(data.pageSize) || data.pageSize < 1 || data.after !== undefined && (!validName(data.after))))
|
|
29
31
|
return fail('HOST_DIRECTORY_INVALID');
|
|
30
32
|
try {
|
|
31
|
-
const
|
|
33
|
+
const payload = { protocolVersion: 1, operation, ...data, maxOutputBytes };
|
|
34
|
+
// Inspect/create always perform a fresh check/mutation through the original path.
|
|
35
|
+
if (operation === 'create')
|
|
36
|
+
await session?.reset();
|
|
37
|
+
const source = operation === 'browse' && session ? '' : await readFile(new URL('../helper/host-directories.cjs', import.meta.url), 'utf8');
|
|
32
38
|
const command = 'node -e ' + "'" + (source + '\nmain();').replaceAll("'", "'\\''") + "'";
|
|
33
|
-
const raw = await runRemote(runner, target, command, signal, JSON.stringify(
|
|
39
|
+
const raw = operation === 'browse' && session ? { exitCode: 0, stderr: '', stdout: await session.request(target, payload, signal) } : await runRemote(runner, target, command, signal, JSON.stringify(payload));
|
|
34
40
|
if (signal.aborted)
|
|
35
41
|
return fail('CONNECTION_LOST');
|
|
36
42
|
if (raw.exitCode !== 0 || raw.stderr !== '')
|
|
@@ -68,11 +74,11 @@ export function createHostDirectories(runner, maxOutputBytes) {
|
|
|
68
74
|
if (error instanceof AuthDiagnosticError) {
|
|
69
75
|
if (error.diagnostic.reason === 'OUTPUT_LIMIT_EXCEEDED')
|
|
70
76
|
return fail('HOST_DIRECTORY_PAGE_TOO_LARGE');
|
|
71
|
-
if (error.diagnostic.stage === 'remote-frame')
|
|
77
|
+
if (error.diagnostic.stage === 'remote-frame' || error.diagnostic.reason === 'PROJECT_PROTOCOL_INVALID')
|
|
72
78
|
return fail('PROJECT_PROTOCOL_INVALID');
|
|
73
79
|
}
|
|
74
80
|
return authFailure('host-directory', 'DIRECTORY_CHECK_EXCEPTION', {}, error, 'CONNECTION_LOST');
|
|
75
81
|
}
|
|
76
82
|
}
|
|
77
|
-
return { create: (target, path, name, signal) => request(target, 'create', { path, name }, signal), browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
|
|
83
|
+
return { ...(session ? { reset: () => session.reset(), dispose: () => session.dispose() } : {}), create: (target, path, name, signal) => request(target, 'create', { path, name }, signal), browse: (target, data, signal) => request(target, 'browse', data, signal), inspect: (target, path, signal) => request(target, 'inspect', { path }, signal) };
|
|
78
84
|
}
|
package/lib/index.js
CHANGED
|
@@ -41,7 +41,7 @@ export function register(ctx, ports, _inventory, extend, autoStart = true) {
|
|
|
41
41
|
export function apply(ctx, config = {}) {
|
|
42
42
|
config = profileSettings(config, ctx.get('profileContext')?.dir);
|
|
43
43
|
const network = ctx.get('aiWorkbenchNetwork');
|
|
44
|
-
const ports = configuredPorts(config, network);
|
|
44
|
+
const ports = configuredPorts(config, network, ctx.get('profileContext')?.dir);
|
|
45
45
|
register(ctx, ports, config.inventory, api => attachProfileRuntime(ctx, api, ports, config, network, true), false);
|
|
46
46
|
registerComponents(ctx, config.inventory, config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes);
|
|
47
47
|
}
|
package/lib/integration.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import type { RuntimeConfig } from './profile-settings.ts';
|
|
2
2
|
import type { Ports } from './ports.ts';
|
|
3
3
|
import { type NetworkProvider } from './provider.ts';
|
|
4
|
-
export declare function configuredPorts(config: RuntimeConfig, provider?: NetworkProvider): Ports;
|
|
4
|
+
export declare function configuredPorts(config: RuntimeConfig, provider?: NetworkProvider, profileDir?: string): Ports;
|
package/lib/integration.js
CHANGED
|
@@ -9,7 +9,7 @@ import { runLogin } from "./login.js";
|
|
|
9
9
|
import { parseLoginStatus } from "./auth-status.js";
|
|
10
10
|
import { authFailure } from "./auth-diagnostics.js";
|
|
11
11
|
import { fail, ok } from "./needs.js";
|
|
12
|
-
export function configuredPorts(config, provider) {
|
|
12
|
+
export function configuredPorts(config, provider, profileDir) {
|
|
13
13
|
const ports = {};
|
|
14
14
|
const network = provider ? adaptNetwork(provider) : undefined;
|
|
15
15
|
if (config.enrollmentPackageDir && config.trustDir)
|
|
@@ -19,7 +19,7 @@ export function configuredPorts(config, provider) {
|
|
|
19
19
|
if (config.commandOutputMaxBytes !== undefined) {
|
|
20
20
|
const runner = createRunner(config.commandOutputMaxBytes);
|
|
21
21
|
ports.ssh = createSsh(runner, config.commandOutputMaxBytes);
|
|
22
|
-
ports.hostDirectories = createHostDirectories(runner, config.commandOutputMaxBytes);
|
|
22
|
+
ports.hostDirectories = createHostDirectories(runner, config.commandOutputMaxBytes, profileDir ? { profileDir } : undefined);
|
|
23
23
|
}
|
|
24
24
|
else if (provider)
|
|
25
25
|
ports.ssh = { verify: async () => fail('SETTINGS_REQUIRED'), status: async () => fail('SETTINGS_REQUIRED') };
|
package/lib/needs.js
CHANGED
|
@@ -30,7 +30,7 @@ const entries = {
|
|
|
30
30
|
HELPER_SHUTDOWN_FORCED: { layer: 'network', message: '网络组件未能正常退出,请联系管理员核实状态。', requires: '核实网络组件退出状态', actor: 'administrator', action: { id: 'inspect-network-enrollment', label: '联系管理员', available: false } },
|
|
31
31
|
ENROLLMENT_KEY_REJECTED: { layer: 'enrollment', message: '开通链接已失效,请向管理员领取新的。', requires: '新的开通链接', actor: 'administrator', action: { id: 'renew-enrollment', label: '联系管理员', available: false } },
|
|
32
32
|
ENROLLMENT_REJECTED: { layer: 'enrollment', message: '已存设备身份已失效,请联系管理员处理。', requires: '管理员处理已失效的设备身份', actor: 'administrator', action: { id: 'check-enrollment-result', label: '联系管理员', available: false } },
|
|
33
|
-
ENROLLMENT_REQUIRED: { layer: 'enrollment', message: '
|
|
33
|
+
ENROLLMENT_REQUIRED: { layer: 'enrollment', message: '这份连接资料缺少开通凭据,请导入含有效开通凭据的连接资料。', requires: '含有效开通凭据的连接资料', actor: 'employee', action: { id: 'import-enrollment', label: '导入连接资料', available: true } },
|
|
34
34
|
ENROLLMENT_INVALID: { layer: 'enrollment', message: '开通文件无效,我需要管理员重新发放。', requires: '有效开通文件', actor: 'administrator', action: { id: 'request-enrollment', label: '重新开通', available: false } },
|
|
35
35
|
NETWORK_KEY_INVALID: { layer: 'network', message: '员工开通已失效,请联系管理员重新发放开通链接。', requires: '新的开通链接', actor: 'administrator', action: { id: 'request-enrollment', label: '联系管理员', available: false } },
|
|
36
36
|
HOST_OFFLINE: { layer: 'network', message: '暂时无法连接主机,最后在线时间未提供时为未知;可先检查本机网络。', requires: '在线的公司主机', actor: 'administrator', action: { id: 'contact-administrator', label: '联系管理员', available: false } },
|
package/lib/ports.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import type { Provider, Result, SshTarget, SessionTarget } from './api.ts';
|
|
2
2
|
import type { createHostDirectories } from './host-directories.ts';
|
|
3
3
|
export interface Enrollment {
|
|
4
|
+
workspaceSources?: ('host' | 'local')[];
|
|
4
5
|
authKeyFile?: string;
|
|
5
6
|
host: string;
|
|
6
7
|
username: string;
|
|
@@ -86,9 +86,7 @@ export function createProfileActivation(options) {
|
|
|
86
86
|
throw error;
|
|
87
87
|
if (stored)
|
|
88
88
|
return fail('LOCAL_STATE_INVALID');
|
|
89
|
-
|
|
90
|
-
return fail('ENROLLMENT_REQUIRED');
|
|
91
|
-
await save(settings.configFile, { ...expected, authKeyFile: e.authKeyFile });
|
|
89
|
+
await save(settings.configFile, { ...expected, ...e.authKeyFile === undefined ? {} : { authKeyFile: e.authKeyFile } });
|
|
92
90
|
}
|
|
93
91
|
if (!stored)
|
|
94
92
|
await save(recordFile, registration);
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { lstat, realpath, open, rename, rm } from 'node:fs/promises';
|
|
2
2
|
import { join, isAbsolute, resolve } from 'node:path';
|
|
3
3
|
import { randomUUID, createHash } from 'node:crypto';
|
|
4
|
-
import { readEnrollment } from "./enrollment.js";
|
|
4
|
+
import { readEnrollment, validWorkspaceSources } from "./enrollment.js";
|
|
5
5
|
import { privateDirectory, privateFile, readPrivate } from "./private-files.js";
|
|
6
6
|
import { ok, fail, need, NeedError } from "./needs.js";
|
|
7
7
|
// Only metadata about authkey is examined here. Its contents belong exclusively to N.
|
|
@@ -14,7 +14,7 @@ export function createProfileEnrollment(options) {
|
|
|
14
14
|
const dataDir = join(options.profileDir, 'ai-workbench-connect'), file = join(dataDir, 'enrollment.json'), trustDir = join(dataDir, 'trust');
|
|
15
15
|
const snapshot = () => structuredClone(state);
|
|
16
16
|
const publish = (phase, reason) => { if (disposed)
|
|
17
|
-
return; state = { instanceId, revision: state.revision + 1, phase, ...(phase === 'imported' && record ? { username: record.username } : {}), ...(reason ? { need: typeof reason === 'string' ? need(reason) : structuredClone(reason) } : {}) }; options.onState?.(snapshot()); for (const fn of listeners)
|
|
17
|
+
return; state = { instanceId, revision: state.revision + 1, phase, ...(phase === 'imported' && record ? { username: record.username } : {}), ...(record?.workspaceSources ? { workspaceSources: [...record.workspaceSources] } : {}), ...(reason ? { need: typeof reason === 'string' ? need(reason) : structuredClone(reason) } : {}) }; options.onState?.(snapshot()); for (const fn of listeners)
|
|
18
18
|
fn(snapshot()); };
|
|
19
19
|
const validOptions = () => isAbsolute(options.profileDir) && Number.isSafeInteger(options.metadataMaxBytes) && options.metadataMaxBytes > 0 && options.metadataMaxBytes <= 2147483647;
|
|
20
20
|
const canonical = async (path) => { if (!isAbsolute(path) || await realpath(path) !== resolve(path))
|
|
@@ -49,7 +49,7 @@ export function createProfileEnrollment(options) {
|
|
|
49
49
|
await canonical(dataDir);
|
|
50
50
|
try {
|
|
51
51
|
const value = JSON.parse(await readPrivate(file, options.metadataMaxBytes));
|
|
52
|
-
if (value.schemaVersion !== 1 || typeof value.requestId !== 'string' || !value.requestId || typeof value.source !== 'string' || !/^[a-f0-9]{64}$/.test(value.digest) || !['host', 'username', 'projectRoot'].every(k => typeof value[k] === 'string') || !Number.isInteger(value.port))
|
|
52
|
+
if (value.workspaceSources !== undefined && !validWorkspaceSources(value.workspaceSources) || value.schemaVersion !== 1 || typeof value.requestId !== 'string' || !value.requestId || typeof value.source !== 'string' || !/^[a-f0-9]{64}$/.test(value.digest) || !['host', 'username', 'projectRoot'].every(k => typeof value[k] === 'string') || !Number.isInteger(value.port))
|
|
53
53
|
throw Error('REGISTRATION_INVALID');
|
|
54
54
|
record = value;
|
|
55
55
|
}
|
|
@@ -91,11 +91,11 @@ export function createProfileEnrollment(options) {
|
|
|
91
91
|
const key = join(source, keyName);
|
|
92
92
|
try {
|
|
93
93
|
if ((await sourceFile(key)).size === 0)
|
|
94
|
-
return fail('
|
|
94
|
+
return fail('ENROLLMENT_INVALID');
|
|
95
95
|
}
|
|
96
96
|
catch (error) {
|
|
97
|
-
if (error.code !== 'ENOENT'
|
|
98
|
-
return fail(
|
|
97
|
+
if (error.code !== 'ENOENT')
|
|
98
|
+
return fail('ENROLLMENT_INVALID');
|
|
99
99
|
}
|
|
100
100
|
// Validate the source digest before replacing our trust cache on an existing registration.
|
|
101
101
|
const digest = createHash('sha256').update(metadata).digest('hex');
|
|
@@ -114,7 +114,7 @@ export function createProfileEnrollment(options) {
|
|
|
114
114
|
return fail('ENROLLMENT_INVALID');
|
|
115
115
|
await canonical(source);
|
|
116
116
|
const { host, username, port, projectRoot } = normalized.value;
|
|
117
|
-
return ok({ enrollment: normalized.value, registration: { schemaVersion: 1, requestId: record?.requestId ?? randomUUID(), source, digest, host, username, port, projectRoot } });
|
|
117
|
+
return ok({ enrollment: normalized.value, registration: { schemaVersion: 1, ...normalized.value.workspaceSources === undefined ? {} : { workspaceSources: [...normalized.value.workspaceSources] }, requestId: record?.requestId ?? randomUUID(), source, digest, host, username, port, projectRoot } });
|
|
118
118
|
}
|
|
119
119
|
catch {
|
|
120
120
|
return fail('ENROLLMENT_INVALID');
|
|
@@ -143,16 +143,17 @@ export function createProfileEnrollment(options) {
|
|
|
143
143
|
publish('blocked', result.error.code);
|
|
144
144
|
return result;
|
|
145
145
|
}
|
|
146
|
+
record = result.value.registration;
|
|
146
147
|
if (!options.activate)
|
|
147
148
|
return fail('DEPENDENCY_REQUIRED');
|
|
148
149
|
const activated = await options.activate(result.value.enrollment, abort.signal);
|
|
149
150
|
if (disposed)
|
|
150
151
|
return fail('DISPOSED');
|
|
151
152
|
if (!activated.ok) {
|
|
152
|
-
publish('blocked', activated.error
|
|
153
|
+
publish('blocked', activated.error);
|
|
153
154
|
return activated;
|
|
154
155
|
}
|
|
155
|
-
if (state.phase !== 'imported' || state.need)
|
|
156
|
+
if (state.phase !== 'imported' || state.need || JSON.stringify(state.workspaceSources) !== JSON.stringify(record.workspaceSources))
|
|
156
157
|
publish('imported');
|
|
157
158
|
return ok(result.value.enrollment);
|
|
158
159
|
})();
|
|
@@ -245,7 +246,7 @@ export function createProfileEnrollment(options) {
|
|
|
245
246
|
if (disposed)
|
|
246
247
|
return fail('DISPOSED');
|
|
247
248
|
if (!activated.ok) {
|
|
248
|
-
publish('blocked', activated.error
|
|
249
|
+
publish('blocked', activated.error);
|
|
249
250
|
return activated;
|
|
250
251
|
}
|
|
251
252
|
publish('imported');
|
package/lib/profile-runtime.js
CHANGED
|
@@ -15,6 +15,12 @@ function attachScopedProfileRuntime(ctx, api, ports, config, network, autoStart
|
|
|
15
15
|
const profile = ctx.get('profileContext');
|
|
16
16
|
if (!profile || typeof profile.dir !== 'string')
|
|
17
17
|
return;
|
|
18
|
+
let directoryConnection = '';
|
|
19
|
+
const releaseDirectories = api.onConnectionState(state => { const key = JSON.stringify([state.instanceId, state.epoch, state.phase]); if (key !== directoryConnection) {
|
|
20
|
+
directoryConnection = key;
|
|
21
|
+
void ports.hostDirectories?.reset?.().catch(() => console.warn('目录浏览连接未能完整关闭,请查看技术详情。'));
|
|
22
|
+
} });
|
|
23
|
+
ctx.effect(() => () => { releaseDirectories(); return ports.hostDirectories?.dispose?.(); });
|
|
18
24
|
const activation = createProfileActivation({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes, network, settings: config.network });
|
|
19
25
|
const manager = createProfileEnrollment({ profileDir: profile.dir, metadataMaxBytes: config.enrollmentMetadataMaxBytes ?? L_DEFAULTS.enrollmentMetadataMaxBytes,
|
|
20
26
|
pick: createNativeImportPicker(() => ctx.get('directoryPicker')),
|
package/lib/startup.js
CHANGED
|
@@ -10,8 +10,10 @@ export function employeeMessage(code, connection) {
|
|
|
10
10
|
return need(code).message;
|
|
11
11
|
if (code === 'DEPENDENCY_REQUIRED')
|
|
12
12
|
return '远程主机连接尚未准备好,请联系管理员。';
|
|
13
|
-
if (code === 'ENROLLMENT_REQUIRED'
|
|
14
|
-
return '
|
|
13
|
+
if (code === 'ENROLLMENT_REQUIRED')
|
|
14
|
+
return '请先导入连接资料。';
|
|
15
|
+
if (code === 'ENROLLMENT_INVALID' || code === 'NETWORK_KEY_INVALID')
|
|
16
|
+
return need(code).message;
|
|
15
17
|
if (code === 'SETTINGS_REQUIRED')
|
|
16
18
|
return need(code).message;
|
|
17
19
|
if (code === 'LOGIN_FAILED')
|