@binblink/wasmnest-plugin-sdk-mobile 0.0.0-stage → 0.0.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.
Files changed (114) hide show
  1. package/README.md +363 -2
  2. package/README_en.md +353 -0
  3. package/bin/build.js +269 -0
  4. package/bin/cli.js +96 -0
  5. package/bin/lib.js +349 -0
  6. package/bin/manifest-gen.js +324 -0
  7. package/bin/package.js +150 -0
  8. package/bin/scaffold.js +285 -0
  9. package/dev-shell/README.md +151 -0
  10. package/dev-shell/index.html +27 -0
  11. package/dev-shell/package.json +27 -0
  12. package/dev-shell/pnpm-workspace.yaml +9 -0
  13. package/dev-shell/postcss.config.js +6 -0
  14. package/dev-shell/src/App.vue +90 -0
  15. package/dev-shell/src/apps/mock-terminal/MockTerminalSlotCard.vue +51 -0
  16. package/dev-shell/src/apps/mock-terminal/MockTerminalView.vue +168 -0
  17. package/dev-shell/src/apps/mock-terminal/index.ts +50 -0
  18. package/dev-shell/src/components/DevToolbar.vue +100 -0
  19. package/dev-shell/src/components/DialogHost.vue +119 -0
  20. package/dev-shell/src/components/LogPanel.vue +80 -0
  21. package/dev-shell/src/i18n.ts +22 -0
  22. package/dev-shell/src/loader.ts +239 -0
  23. package/dev-shell/src/locale.ts +29 -0
  24. package/dev-shell/src/locales/en-shell.ts +328 -0
  25. package/dev-shell/src/locales/index.ts +70 -0
  26. package/dev-shell/src/locales/shell.ts +328 -0
  27. package/dev-shell/src/main.ts +58 -0
  28. package/dev-shell/src/mock/dialog-service.ts +58 -0
  29. package/dev-shell/src/mock/file-transfer.ts +390 -0
  30. package/dev-shell/src/mock/mobile-api.ts +369 -0
  31. package/dev-shell/src/mock/preset-tasks.ts +186 -0
  32. package/dev-shell/src/mock/session.ts +121 -0
  33. package/dev-shell/src/mock-context.ts +351 -0
  34. package/dev-shell/src/registry.ts +151 -0
  35. package/dev-shell/src/shared-runtime.ts +44 -0
  36. package/dev-shell/src/shell/ShellView.vue +52 -0
  37. package/dev-shell/src/shell/adapters/devAppSource.ts +155 -0
  38. package/dev-shell/src/shell/components/PluginContextHost.vue +40 -0
  39. package/dev-shell/src/shell/components/ShellAppCell.vue +75 -0
  40. package/dev-shell/src/shell/components/ShellAppIcon.vue +111 -0
  41. package/dev-shell/src/shell/components/ShellAppSurface.vue +46 -0
  42. package/dev-shell/src/shell/components/ShellBrandTile.vue +27 -0
  43. package/dev-shell/src/shell/components/ShellCapsuleMenu.vue +123 -0
  44. package/dev-shell/src/shell/components/ShellChip.vue +49 -0
  45. package/dev-shell/src/shell/components/ShellGroupCard.vue +17 -0
  46. package/dev-shell/src/shell/components/ShellHost.vue +75 -0
  47. package/dev-shell/src/shell/components/ShellNotificationShade.vue +496 -0
  48. package/dev-shell/src/shell/components/ShellPermissionPrompt.vue +127 -0
  49. package/dev-shell/src/shell/components/ShellPlaceholderSurface.vue +33 -0
  50. package/dev-shell/src/shell/components/ShellSection.vue +27 -0
  51. package/dev-shell/src/shell/components/ShellSheet.vue +74 -0
  52. package/dev-shell/src/shell/components/ShellStatusbar.vue +84 -0
  53. package/dev-shell/src/shell/components/screens/PluginRoutePage.vue +98 -0
  54. package/dev-shell/src/shell/components/screens/ShellAppDetailScreen.vue +378 -0
  55. package/dev-shell/src/shell/components/screens/ShellAppRunScreen.vue +90 -0
  56. package/dev-shell/src/shell/components/screens/ShellAppsScreen.vue +195 -0
  57. package/dev-shell/src/shell/components/screens/ShellHomeScreen.vue +316 -0
  58. package/dev-shell/src/shell/components/screens/ShellPermissionsScreen.vue +376 -0
  59. package/dev-shell/src/shell/components/screens/ShellSettingsScreen.vue +240 -0
  60. package/dev-shell/src/shell/components/screens/ShellSwitcherScreen.vue +559 -0
  61. package/dev-shell/src/shell/components/ui/ConfirmDialog.vue +137 -0
  62. package/dev-shell/src/shell/components/ui/Toggle.vue +53 -0
  63. package/dev-shell/src/shell/composables/useShellApps.ts +415 -0
  64. package/dev-shell/src/shell/composables/useShellNavigation.ts +197 -0
  65. package/dev-shell/src/shell/composables/useShellNotifications.ts +115 -0
  66. package/dev-shell/src/shell/composables/useShellOpen.ts +35 -0
  67. package/dev-shell/src/shell/composables/useShellOverlays.ts +101 -0
  68. package/dev-shell/src/shell/composables/useShellPreferences.ts +143 -0
  69. package/dev-shell/src/shell/composables/useShellRecent.ts +84 -0
  70. package/dev-shell/src/shell/composables/useToast.ts +33 -0
  71. package/dev-shell/src/shell/index.ts +88 -0
  72. package/dev-shell/src/shell/logger.ts +45 -0
  73. package/dev-shell/src/shell/permissions.ts +145 -0
  74. package/dev-shell/src/shell/registry.ts +220 -0
  75. package/dev-shell/src/shell/styles/shell.css +841 -0
  76. package/dev-shell/src/shell/types.ts +137 -0
  77. package/dev-shell/src/shell/utils.ts +54 -0
  78. package/dev-shell/src/styles/main.css +153 -0
  79. package/dev-shell/src/styles/mobile.css +884 -0
  80. package/dev-shell/src/styles/wallpaper.css +130 -0
  81. package/dev-shell/src/theme.ts +71 -0
  82. package/dev-shell/src/vite-env.d.ts +20 -0
  83. package/dev-shell/tailwind.config.js +101 -0
  84. package/dev-shell/tsconfig.json +16 -0
  85. package/dev-shell/vite.config.ts +130 -0
  86. package/dist/index.d.ts +84 -0
  87. package/dist/index.js +161 -0
  88. package/dist/types.d.ts +637 -0
  89. package/dist/types.js +0 -0
  90. package/dist/vite-plugin.d.ts +16 -0
  91. package/dist/vite-plugin.js +95 -0
  92. package/package.json +80 -3
  93. package/src/constants.ts +6 -0
  94. package/src/global-dialog.ts +168 -0
  95. package/src/index.ts +87 -0
  96. package/src/runtime.ts +44 -0
  97. package/src/types.ts +715 -0
  98. package/src/ui/PluginGlobalDialog.vue +388 -0
  99. package/src/ui/Select.d.ts +37 -0
  100. package/src/ui/Select.vue +307 -0
  101. package/src/ui/plugin-global-dialog.d.ts +11 -0
  102. package/src/ui/useSwipeTabs.d.ts +20 -0
  103. package/src/ui/useSwipeTabs.ts +53 -0
  104. package/src/vite-plugin.ts +132 -0
  105. package/template/.gitignore +4 -0
  106. package/template/README.md +46 -0
  107. package/template/package.json +23 -0
  108. package/template/plugin.json +13 -0
  109. package/template/rust/Cargo.toml +19 -0
  110. package/template/rust/src/lib.rs +33 -0
  111. package/template/src/env.d.ts +24 -0
  112. package/template/src/index.ts +37 -0
  113. package/template/tsconfig.json +17 -0
  114. package/template/vite.config.ts +21 -0
@@ -0,0 +1,369 @@
1
+ /**
2
+ * MobileHostApi mock(SDK getMobileApi() 返回的宿主通用连接/HTTP 能力)
3
+ *
4
+ * 与真实宿主一致:暴露连接态(activeSessionId / activeSessions / sessionConfigs /
5
+ * isConnected)+ 通用 httpRequest 通道。任务队列等业务端点在 dev-shell 内按
6
+ * 路径路由模拟(宿主能力 mock 的一部分,固定在 dev-shell 内实现);演示种子
7
+ * 数据由插件 devMock.queueSeed 提供(领域数据归插件)。
8
+ */
9
+ import { computed, ref } from 'vue'
10
+ import type {
11
+ MobileHostApi,
12
+ MobileHttpRequestOptions,
13
+ MobileHttpResult,
14
+ MobileConnectionStatus,
15
+ MobileDeviceTarget,
16
+ MobileMdnsService,
17
+ } from '../../../src/types'
18
+ import { activeSessionId, connected, onDevEvent, sessions } from './session'
19
+ import { getAllDevMocks } from '../registry'
20
+
21
+ /** 连接历史(dev-shell mock:演示种子为空列表) */
22
+ const connectionHistory = ref<{ address: string; name: string; lastConnected?: string }[]>([])
23
+
24
+ /** 活跃会话列表(响应式,MobileHostApi.activeSessions) */
25
+ const activeSessions = computed(() => sessions.value.map((s) => ({ ...s })))
26
+
27
+ /** 队列任务项(dev-shell mock 内部结构,演示数据来自插件 devMock.queueSeed) */
28
+ interface QueueTaskItem {
29
+ id: string
30
+ prompt: string
31
+ position: number
32
+ status: string
33
+ created_at: string
34
+ }
35
+
36
+ const STORAGE_KEY = 'wasmnest-dev-shell:queue-tasks'
37
+
38
+ function seedQueue(): QueueTaskItem[] {
39
+ // 首个注册了队列种子的插件的领域数据(localStorage 无缓存时使用)
40
+ for (const mock of getAllDevMocks()) {
41
+ const seed = mock.queueSeed as QueueTaskItem[] | undefined
42
+ if (seed?.length) return seed
43
+ }
44
+ return []
45
+ }
46
+
47
+ function loadQueue(): QueueTaskItem[] {
48
+ try {
49
+ const raw = localStorage.getItem(STORAGE_KEY)
50
+ if (raw) return JSON.parse(raw)
51
+ } catch {
52
+ // localStorage 不可用则使用内存种子数据
53
+ }
54
+ return seedQueue()
55
+ }
56
+
57
+ const queueTasks = ref<QueueTaskItem[]>(loadQueue())
58
+ let queueSeeded = queueTasks.value.length > 0
59
+
60
+ /** 插件 devMock 注册完成后调用:无持久化缓存时注入队列种子(惰性,避免模块加载时序问题) */
61
+ export function syncQueueSeed(): void {
62
+ if (queueSeeded) return
63
+ queueSeeded = true
64
+ const seed = seedQueue()
65
+ if (seed.length) {
66
+ queueTasks.value = seed
67
+ saveQueue()
68
+ }
69
+ }
70
+
71
+ /** 任务队列接口访问前确保种子已注入 */
72
+ function ensureQueueSeed(): void {
73
+ if (!queueSeeded) syncQueueSeed()
74
+ }
75
+
76
+ const sessionMode = ref({ autoExecute: false, autoAnswer: false })
77
+
78
+ function saveQueue(): void {
79
+ try {
80
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(queueTasks.value))
81
+ } catch {
82
+ // 隐私模式等场景静默降级
83
+ }
84
+ }
85
+
86
+ function ok<T>(data?: T): MobileHttpResult<T> {
87
+ return { code: 0, message: 'ok', data }
88
+ }
89
+
90
+ function fail(message: string): MobileHttpResult {
91
+ return { code: 1, message }
92
+ }
93
+
94
+ // ==================== 请求体解析(避免 any 字典,字段按需窄化) ====================
95
+
96
+ type JsonBody = Record<string, unknown>
97
+
98
+ function parseBody(body: unknown): JsonBody {
99
+ if (!body) return {}
100
+ if (typeof body === 'string') {
101
+ try {
102
+ return JSON.parse(body) as JsonBody
103
+ } catch {
104
+ return {}
105
+ }
106
+ }
107
+ return body as JsonBody
108
+ }
109
+
110
+ function strField(body: JsonBody, key: string): string {
111
+ const v = body[key]
112
+ return typeof v === 'string' ? v : ''
113
+ }
114
+
115
+ function strArrayField(body: JsonBody, key: string): string[] {
116
+ const v = body[key]
117
+ return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : []
118
+ }
119
+
120
+ function boolField(body: JsonBody, key: string): boolean | undefined {
121
+ const v = body[key]
122
+ return typeof v === 'boolean' ? v : undefined
123
+ }
124
+
125
+ /** 通用 HTTP 请求路由:按对端任务域(bedcode app)端点路径模拟(dev-shell 宿主能力 mock) */
126
+ async function routeHttpRequest(
127
+ path: string,
128
+ method: string,
129
+ body: JsonBody,
130
+ ): Promise<MobileHttpResult> {
131
+ const [pathname, queryString] = path.split('?')
132
+ const query = new URLSearchParams(queryString || '')
133
+ const sessionId = query.get('session_id') || strField(body, 'session_id') || ''
134
+
135
+ const BASE = '/api/plugin/com.wasmnest.bedcode'
136
+
137
+ if (pathname === `${BASE}/task-queue/list`) {
138
+ if (!sessionId) return fail('missing sessionId')
139
+ ensureQueueSeed()
140
+ return ok({
141
+ session_id: sessionId,
142
+ tasks: queueTasks.value.map((t, i) => ({ ...t, position: i + 1 })),
143
+ queue_count: queueTasks.value.length,
144
+ active_task: null,
145
+ })
146
+ }
147
+
148
+ if (pathname === `${BASE}/task-queue/add`) {
149
+ const prompt = strField(body, 'prompt')
150
+ if (!sessionId || !prompt) return fail('missing sessionId or prompt')
151
+ const id = `dev-queue-${Date.now()}`
152
+ queueTasks.value.push({
153
+ id,
154
+ prompt,
155
+ position: queueTasks.value.length + 1,
156
+ status: 'pending',
157
+ created_at: new Date().toISOString(),
158
+ })
159
+ saveQueue()
160
+ return ok({ task_id: id, position: queueTasks.value.length })
161
+ }
162
+
163
+ if (pathname === `${BASE}/task-queue/remove`) {
164
+ const taskId = strField(body, 'task_id')
165
+ if (!sessionId || !taskId) return fail('missing params')
166
+ queueTasks.value = queueTasks.value.filter((t) => t.id !== taskId)
167
+ saveQueue()
168
+ return ok()
169
+ }
170
+
171
+ if (pathname === `${BASE}/task-queue/cancel`) {
172
+ const taskId = strField(body, 'task_id')
173
+ if (!sessionId || !taskId) return fail('missing params')
174
+ queueTasks.value = queueTasks.value.filter((t) => t.id !== taskId)
175
+ saveQueue()
176
+ return ok()
177
+ }
178
+
179
+ if (pathname === `${BASE}/task-queue/clear`) {
180
+ if (!sessionId) return fail('missing sessionId')
181
+ queueTasks.value = []
182
+ saveQueue()
183
+ return ok()
184
+ }
185
+
186
+ if (pathname === `${BASE}/task-queue/update`) {
187
+ const taskId = strField(body, 'task_id')
188
+ if (!sessionId || !taskId) return fail('missing params')
189
+ const task = queueTasks.value.find((t) => t.id === taskId)
190
+ if (!task) return fail('task not found')
191
+ task.prompt = strField(body, 'prompt')
192
+ saveQueue()
193
+ return ok()
194
+ }
195
+
196
+ if (pathname === `${BASE}/task-queue/reorder`) {
197
+ if (!sessionId) return fail('missing sessionId')
198
+ const byId = new Map(queueTasks.value.map((t) => [t.id, t]))
199
+ const ids = strArrayField(body, 'task_ids')
200
+ queueTasks.value = ids.map((id) => byId.get(id)).filter(Boolean) as QueueTaskItem[]
201
+ saveQueue()
202
+ return ok()
203
+ }
204
+
205
+ if (pathname === `${BASE}/session-settings`) {
206
+ if (!sessionId) return fail('missing sessionId')
207
+ return ok({
208
+ session_id: sessionId,
209
+ auto_execute: sessionMode.value.autoExecute,
210
+ auto_answer: sessionMode.value.autoAnswer,
211
+ })
212
+ }
213
+
214
+ if (pathname === `${BASE}/session-mode`) {
215
+ if (!sessionId) return fail('missing sessionId')
216
+ const autoExecute = boolField(body, 'auto_execute')
217
+ const autoAnswer = boolField(body, 'auto_answer')
218
+ if (autoExecute !== undefined) sessionMode.value.autoExecute = autoExecute
219
+ if (autoAnswer !== undefined) sessionMode.value.autoAnswer = autoAnswer
220
+ return ok()
221
+ }
222
+
223
+ if (pathname === `${BASE}/task-history/current`) {
224
+ if (!sessionId) return fail('missing sessionId')
225
+ const first = queueTasks.value.find((t) => t.status !== 'done')
226
+ return ok({
227
+ session_id: sessionId,
228
+ task: first
229
+ ? {
230
+ id: first.id,
231
+ description: first.prompt,
232
+ status: first.status,
233
+ auto_approve: sessionMode.value.autoExecute ? 1 : 0,
234
+ created_at: first.created_at,
235
+ }
236
+ : null,
237
+ })
238
+ }
239
+
240
+ if (pathname === `${BASE}/task-history/list`) {
241
+ return ok({
242
+ tasks: [],
243
+ total: 0,
244
+ limit: Number(query.get('limit') || 20),
245
+ offset: Number(query.get('offset') || 0),
246
+ })
247
+ }
248
+
249
+ if (pathname === `${BASE}/supported-agents`) {
250
+ return ok({ agents: ['wasmnest', 'claude-code', 'deepseek'] })
251
+ }
252
+
253
+ if (pathname === `${BASE}/scheduled-jobs/list`) {
254
+ return ok({ jobs: [] })
255
+ }
256
+
257
+ if (pathname === `${BASE}/scheduled-jobs/create`) {
258
+ return ok({ job_id: `dev-job-${Date.now()}` })
259
+ }
260
+
261
+ return fail(`dev-shell mock: unhandled endpoint ${method} ${path}`)
262
+ }
263
+
264
+ /** dev-shell 主题(无真机主题系统;如需验证深色路径可手动置 true) */
265
+ const isDark = ref(false)
266
+
267
+ /** dev-shell 本地设置投影(vibrate 无意义置 false;档位与宿主 MobileSettings 同形) */
268
+ const mobileSettings = ref({ vibrate: false, maxOpenTerminals: 5 })
269
+
270
+ /** 暴露到 window.__WASMNEST_SHARED__.mobileApi */
271
+ export const mobileApi: MobileHostApi = {
272
+ activeSessionId,
273
+ activeSessions,
274
+ sessionConfigs: computed(() =>
275
+ sessions.value.map((s) => ({ session_id: s.id, agent: s.agent, status: s.status })),
276
+ ),
277
+ isConnected: connected,
278
+ // dev-shell 无真实认证阶段:演示环境视为已认证(会话/任务端点可直接响应)
279
+ isPaired: connected,
280
+
281
+ httpRequest<T = any>(path: string, options: MobileHttpRequestOptions = {}) {
282
+ return routeHttpRequest(path, options.method || 'GET', parseBody(options.body)) as Promise<
283
+ MobileHttpResult<T>
284
+ >
285
+ },
286
+
287
+ // dev-shell:列表已是内存真源(mock 会话),拉取即 no-op
288
+ async loadActiveSessions(): Promise<void> {},
289
+ async loadSessionConfigs(): Promise<void> {},
290
+ hasLoadedConfigs: ref(true),
291
+ isLoadingConfigs: ref(false),
292
+
293
+ // 票 15:终端 UI 域下沉所需机制面 —— dev-shell 接 mock 会话输出(字符串 → UTF-8 字节),
294
+ // 真机为宿主页面 Channel 裸字节投递
295
+ async openTerminalStream(sessionId: string, onBytes: (bytes: Uint8Array) => void) {
296
+ const encoder = new TextEncoder()
297
+ const un = onDevEvent('terminal:output', (payload: { sessionId: string; data: string }) => {
298
+ if (payload.sessionId === sessionId) onBytes(encoder.encode(payload.data))
299
+ })
300
+ return {
301
+ dispose() {
302
+ un.dispose()
303
+ },
304
+ }
305
+ },
306
+ isDark,
307
+ mobileSettings,
308
+ onSessionEvent(handler) {
309
+ // dev-shell:桥接 mock 会话生命周期(断线 / 会话停止);像素级状态流不在浏览器模拟
310
+ const d1 = onDevEvent('plugin:lifecycle:disconnect', () => handler({ type: 'disconnected' }))
311
+ const d2 = onDevEvent('plugin:lifecycle:sessionStopped', (p: any) =>
312
+ handler({ type: 'session_stopped', sessionId: p?.sessionId }),
313
+ )
314
+ return {
315
+ dispose() {
316
+ d1.dispose()
317
+ d2.dispose()
318
+ },
319
+ }
320
+ },
321
+ // ── 连接引擎面(票 2026-10-09:宿主页下沉;dev-shell 提供静默 no-op 替身)──
322
+ // 演示环境已是可用的「已认证」连接(与上方 isConnected / isPaired 同口径,
323
+ // 否则宿主页头部显示「未连接」而认证卡片已渲染,前后矛盾)
324
+ connectionStatus: ref<MobileConnectionStatus>('paired'),
325
+ isConnecting: ref(false),
326
+ currentDevice: ref<MobileDeviceTarget | null>(null),
327
+ connectionHistory,
328
+ async connectDevice() {},
329
+ async cancelConnection() {},
330
+ async authenticateWithStoredToken() {
331
+ return true
332
+ },
333
+ async disconnect() {},
334
+ async loadConnectionHistory() {},
335
+ async clearConnectionHistory() {
336
+ connectionHistory.value = []
337
+ },
338
+ async removeFromConnectionHistory() {},
339
+ async addToConnectionHistory(address: string, name?: string) {
340
+ // dev-shell:内存历史去重置顶(与宿主域上限 10 条同口径)
341
+ const list = connectionHistory.value.filter((item) => item.address !== address)
342
+ list.unshift({ address, name: name || address.split(':')[0] })
343
+ connectionHistory.value = list.slice(0, 10)
344
+ },
345
+ onConnectionEvent() {
346
+ return { dispose() {} }
347
+ },
348
+ // ── mDNS 引擎事实(dev-shell 无 mDNS,静默空列表)──
349
+ mdnsServices: ref<MobileMdnsService[]>([]),
350
+ mdnsScanning: ref(false),
351
+ async mdnsStart() {},
352
+ async mdnsStop() {},
353
+ async mdnsRefresh() {},
354
+ // ── 生物凭证引擎面(dev-shell 视为不支持)──
355
+ async getBiometricKeyStatus() {
356
+ return { deviceSupported: false, deviceReason: 12, hasKey: false }
357
+ },
358
+ async bindBiometricCredential() {
359
+ return false
360
+ },
361
+ async unbindBiometricCredential() {
362
+ return false
363
+ },
364
+ // dev-shell 的会话流走真实渲染路径(非宿主 DEV mock 会话),故无 mockSessionId
365
+ mockSessionId: null,
366
+ }
367
+
368
+ /** 供 MockTerminalView 展示队列 */
369
+ export { queueTasks, sessionMode }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * 预设任务 mock(宿主 usePresetTasks 的浏览器实现)
3
+ *
4
+ * tasks 持久化到 localStorage;sendTask/executeTask 需要与对端桌面端通信,
5
+ * 浏览器中不可用,调用时记日志提示。API 形状与宿主 composable 保持一致(含执行状态字段)。
6
+ */
7
+ import { ref } from 'vue'
8
+ import { pushLog } from '../registry'
9
+
10
+ const STORAGE_KEY = 'wasmnest-dev-shell:preset-tasks'
11
+
12
+ export type PresetTaskStatus = 'unused' | 'executing' | 'completed' | 'interrupted'
13
+
14
+ export interface PresetTaskItem {
15
+ id: string
16
+ prompt: string
17
+ status: PresetTaskStatus
18
+ createdAt: string
19
+ repeatable: boolean
20
+ pendingTaskId: string | null
21
+ pendingSessionId: string | null
22
+ }
23
+
24
+ const tasks = ref<PresetTaskItem[]>(load())
25
+
26
+ function load(): PresetTaskItem[] {
27
+ try {
28
+ const raw = localStorage.getItem(STORAGE_KEY)
29
+ const parsed = raw ? JSON.parse(raw) : []
30
+ return (parsed as Partial<PresetTaskItem>[]).map(t => ({
31
+ id: t.id ?? '',
32
+ prompt: t.prompt ?? '',
33
+ status: t.status ?? 'unused',
34
+ createdAt: t.createdAt ?? '',
35
+ repeatable: t.repeatable ?? true,
36
+ pendingTaskId: t.pendingTaskId ?? null,
37
+ pendingSessionId: t.pendingSessionId ?? null,
38
+ }))
39
+ } catch {
40
+ return []
41
+ }
42
+ }
43
+
44
+ function saveToStorage(): void {
45
+ try {
46
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(tasks.value))
47
+ } catch {
48
+ // localStorage 不可用(隐私模式)时静默降级
49
+ }
50
+ }
51
+
52
+ async function loadRemote(): Promise<void> {
53
+ // 宿主实现从桌面端拉取;浏览器 mock 直接读本地
54
+ tasks.value = load()
55
+ }
56
+
57
+ async function addTask(input: { content: string; repeatable?: boolean }): Promise<void> {
58
+ tasks.value.unshift({
59
+ id: `dev-task-${Date.now()}`,
60
+ prompt: input.content,
61
+ status: 'unused',
62
+ createdAt: new Date().toISOString(),
63
+ repeatable: input.repeatable ?? true,
64
+ pendingTaskId: null,
65
+ pendingSessionId: null,
66
+ })
67
+ saveToStorage()
68
+ }
69
+
70
+ async function updateTask(id: string, prompt: string): Promise<void> {
71
+ const task = tasks.value.find((t) => t.id === id)
72
+ if (task) {
73
+ const contentChanged = task.prompt !== prompt
74
+ task.prompt = prompt
75
+ // 内容变化视为重新定义任务,执行状态重置
76
+ if (contentChanged) {
77
+ task.status = 'unused'
78
+ task.pendingTaskId = null
79
+ }
80
+ saveToStorage()
81
+ }
82
+ }
83
+
84
+ async function deleteTask(id: string): Promise<void> {
85
+ tasks.value = tasks.value.filter((t) => t.id !== id)
86
+ saveToStorage()
87
+ }
88
+
89
+ async function sendTask(id: string): Promise<void> {
90
+ pushLog('warn', 'preset-tasks', `sendTask(${id}) 需要连接对端桌面端,浏览器 dev-shell 不可用`)
91
+ }
92
+
93
+ async function executeTask(id: string): Promise<void> {
94
+ pushLog('warn', 'preset-tasks', `executeTask(${id}) 需要连接对端桌面端,浏览器 dev-shell 不可用`)
95
+ const task = tasks.value.find((t) => t.id === id)
96
+ if (task) {
97
+ task.status = 'completed'
98
+ task.pendingTaskId = null
99
+ task.pendingSessionId = null
100
+ saveToStorage()
101
+ }
102
+ }
103
+
104
+ /** 入队成功:记录队列项 id 与会话,状态 → executing */
105
+ async function markEnqueued(id: string, taskId: string, sessionId: string): Promise<void> {
106
+ const task = tasks.value.find((t) => t.id === id)
107
+ if (!task) return
108
+ task.status = 'executing'
109
+ task.pendingTaskId = taskId
110
+ task.pendingSessionId = sessionId
111
+ saveToStorage()
112
+ }
113
+
114
+ /** 完成广播:按队列项 id 匹配预设,状态 → completed(不匹配忽略) */
115
+ async function markCompletedByTaskId(taskId: string): Promise<void> {
116
+ const task = tasks.value.find((t) => t.pendingTaskId === taskId)
117
+ if (!task) return
118
+ task.status = 'completed'
119
+ task.pendingTaskId = null
120
+ task.pendingSessionId = null
121
+ saveToStorage()
122
+ }
123
+
124
+ /** 对账:单个预设落中断 */
125
+ async function markInterrupted(id: string): Promise<void> {
126
+ const task = tasks.value.find((t) => t.id === id)
127
+ if (!task || task.status !== 'executing') return
128
+ task.status = 'interrupted'
129
+ saveToStorage()
130
+ }
131
+
132
+ /** 按队列项 id 落中断(取消/会话终止广播,与宿主 usePresetTasks 对齐) */
133
+ async function markInterruptedByTaskId(taskId: string): Promise<void> {
134
+ const task = tasks.value.find((t) => t.pendingTaskId === taskId)
135
+ if (!task || task.status !== 'executing') return
136
+ task.status = 'interrupted'
137
+ task.pendingTaskId = null
138
+ task.pendingSessionId = null
139
+ saveToStorage()
140
+ }
141
+
142
+ /** 队列项移除:按队列项 id 回退未使用(不匹配忽略) */
143
+ async function revertToUnusedByTaskId(taskId: string): Promise<void> {
144
+ const task = tasks.value.find((t) => t.pendingTaskId === taskId)
145
+ if (!task) return
146
+ task.status = 'unused'
147
+ task.pendingTaskId = null
148
+ task.pendingSessionId = null
149
+ saveToStorage()
150
+ }
151
+
152
+ function clearAllTasks(): void {
153
+ tasks.value = []
154
+ saveToStorage()
155
+ }
156
+
157
+ /** 锁定判定:不可重复 + 已执行 → 锁定;可重复 + 执行中 → 防重复。
158
+ * 必须同步返回(模板禁用直接依赖布尔值,async 会恒为真导致禁用失效) */
159
+ function canEnqueueTask(task: PresetTaskItem): boolean {
160
+ if (task.status === 'executing') return false
161
+ if (!task.repeatable && task.status !== 'unused') return false
162
+ return true
163
+ }
164
+
165
+ export function usePresetTasks() {
166
+ return {
167
+ tasks,
168
+ load: loadRemote,
169
+ addTask,
170
+ updateTask,
171
+ deleteTask,
172
+ sendTask,
173
+ executeTask,
174
+ clearAllTasks,
175
+ saveToStorage,
176
+ markEnqueued,
177
+ markCompletedByTaskId,
178
+ markInterrupted,
179
+ markInterruptedByTaskId,
180
+ revertToUnusedByTaskId,
181
+ canEnqueue: canEnqueueTask,
182
+ }
183
+ }
184
+
185
+ /** 暴露到 window.__WASMNEST_SHARED__.presetTasks(SDK getPresetTasks() 约定) */
186
+ export const presetTasksApi = { usePresetTasks }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * 模拟会话/终端环境
3
+ *
4
+ * 浏览器中不存在真实 WS 连接,这里提供可交互的假会话:
5
+ * - MockTerminalView 的输入/输出、会话生命周期按钮都驱动本模块
6
+ * - context.session / context.lifecycle / mobileApi 全部接本模块
7
+ * (context.terminal 已随票 15 阶段 B 退役——TerminalAPI 整面删除)
8
+ * 事件经全局 emitter 分发(key 与宿主 plugin/events.ts 一致,插件无感知)。
9
+ */
10
+ import { reactive, ref } from 'vue'
11
+ import type { Disposable } from '../../../src/types'
12
+
13
+ export interface MockSession {
14
+ id: string
15
+ name: string
16
+ agent: string
17
+ status: 'running' | 'stopped'
18
+ }
19
+
20
+ const sessions = ref<MockSession[]>([
21
+ { id: 'mock-session-1', name: 'mock-session-1', agent: 'wasmnest', status: 'running' },
22
+ { id: 'mock-session-2', name: 'mock-session-2', agent: 'claude-code', status: 'running' },
23
+ ])
24
+ const activeSessionId = ref<string>(sessions.value[0].id)
25
+ const connected = ref(true)
26
+ const outputs = reactive<Record<string, string[]>>({
27
+ [sessions.value[0].id]: ['$ 欢迎使用 WasmNest Dev Shell(模拟会话)', '$ 在右侧输入命令,或点击「模拟输出」触发插件输出解析'],
28
+ [sessions.value[1].id]: ['$ mock session 2 ready'],
29
+ })
30
+ const inputs = reactive<Record<string, string[]>>({})
31
+
32
+ // ==================== 全局事件 emitter ====================
33
+
34
+ const listeners = new Map<string, Set<(...args: any[]) => void>>()
35
+
36
+ /** 订阅 dev-shell 事件(返回 disposable) */
37
+ export function onDevEvent(event: string, handler: (...args: any[]) => void): Disposable {
38
+ let set = listeners.get(event)
39
+ if (!set) {
40
+ set = new Set()
41
+ listeners.set(event, set)
42
+ }
43
+ set.add(handler)
44
+ return {
45
+ dispose() {
46
+ set!.delete(handler)
47
+ if (set!.size === 0) listeners.delete(event)
48
+ },
49
+ }
50
+ }
51
+
52
+ /** 发射 dev-shell 事件 */
53
+ export function emitDevEvent(event: string, ...args: any[]): void {
54
+ const set = listeners.get(event)
55
+ if (!set) return
56
+ for (const handler of [...set]) {
57
+ try {
58
+ handler(...args)
59
+ } catch (e) {
60
+ console.error(`[dev-shell] event handler "${event}" failed:`, e)
61
+ }
62
+ }
63
+ }
64
+
65
+ // ==================== 会话模拟操作 ====================
66
+
67
+ /** 发送终端输入(记录到会话输入行;terminalInput lifecycle 事件已随票 15 阶段 B 退役) */
68
+ export function sendInputToSession(sessionId: string, text: string): void {
69
+ if (!text.trim()) return
70
+ ;(inputs[sessionId] ||= []).push(text)
71
+ }
72
+
73
+ /** 模拟终端输出(terminal:output 事件供 TerminalAPI 消费者/openTerminalStream mock 使用) */
74
+ export function sendOutput(sessionId: string, data: string): void {
75
+ ;(outputs[sessionId] ||= []).push(data)
76
+ emitDevEvent('terminal:output', { sessionId, data })
77
+ }
78
+
79
+ /** 新建会话(触发 session:statusChange + lifecycle onSessionCreated) */
80
+ export function createSession(): void {
81
+ const id = `mock-session-${sessions.value.length + 1}`
82
+ sessions.value.unshift({ id, name: id, agent: 'wasmnest', status: 'running' })
83
+ outputs[id] = [`$ session ${id} created`]
84
+ activeSessionId.value = id
85
+ emitStatusChange(id, 'created')
86
+ emitDevEvent('plugin:lifecycle:sessionCreated', { sessionId: id })
87
+ }
88
+
89
+ /** 停止会话(触发 session:statusChange + lifecycle onSessionStopped) */
90
+ export function stopSession(sessionId: string): void {
91
+ const s = sessions.value.find((x) => x.id === sessionId)
92
+ if (!s) return
93
+ s.status = 'stopped'
94
+ emitStatusChange(sessionId, 'stopped')
95
+ emitDevEvent('plugin:lifecycle:sessionStopped', { sessionId })
96
+ }
97
+
98
+ /** 切换连接状态(触发 lifecycle onDisconnect / onAuthSuccess) */
99
+ export function setConnected(next: boolean): void {
100
+ if (connected.value === next) return
101
+ connected.value = next
102
+ if (!next) {
103
+ emitDevEvent('plugin:lifecycle:disconnect', { reason: 'dev-shell 手动断开' })
104
+ }
105
+ }
106
+
107
+ /** 模拟认证成功(触发 lifecycle onAuthSuccess) */
108
+ export function authSuccess(): void {
109
+ connected.value = true
110
+ emitDevEvent('plugin:lifecycle:authSuccess', {})
111
+ }
112
+
113
+ function emitStatusChange(sessionId: string, status: string): void {
114
+ emitDevEvent('session:statusChange', {
115
+ sessionId,
116
+ status,
117
+ sessions: sessions.value.map((s) => ({ ...s })),
118
+ })
119
+ }
120
+
121
+ export { sessions, activeSessionId, connected, outputs, inputs }