@tina_summer/codepocket 2.7.0 → 2.7.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/bin/codepocket.js CHANGED
@@ -22,7 +22,13 @@ const agents = require('../src/agents')
22
22
 
23
23
  // Agent (codex/zcode) state changes surface as SSE events so the phone
24
24
  // refreshes — sendToRelay fans out one encrypted copy per paired device.
25
+ // Throttled: bursts (poll loops, reconnect churn) must not flood the phone
26
+ // with reload-triggering events (observed WeChat service-thread timeouts).
27
+ let _lastAgentBroadcast = 0
25
28
  agents.onSessionEvent(() => {
29
+ const now = Date.now()
30
+ if (now - _lastAgentBroadcast < 3000) return
31
+ _lastAgentBroadcast = now
26
32
  sendToRelay({ type: 'sse-event', event: { type: 'session-updated' } })
27
33
  })
28
34
 
@@ -939,7 +945,7 @@ async function handleSpawnSession(requestId, directory, provider) {
939
945
  // Agent selection: 'claude' (default, omit-safe for older miniprogram
940
946
  // versions) or a connector-side agent backend.
941
947
  const agentKey = (typeof provider === 'string' && provider) ? provider : 'claude'
942
- if (!['claude', 'codex'].includes(agentKey)) {
948
+ if (!['claude', 'codex', 'zcode'].includes(agentKey)) {
943
949
  sendSpawnResult(requestId, null, `${agentKey} 会话不能从手机创建(在对应客户端内新建)`)
944
950
  return
945
951
  }
@@ -976,6 +982,18 @@ async function handleSpawnSession(requestId, directory, provider) {
976
982
  return
977
983
  }
978
984
 
985
+ // ZCode/GLM: created on the desktop via the ws2 relay (createSession command).
986
+ // The desktop's active workspace is used — dir selection is advisory only.
987
+ if (agentKey === 'zcode') {
988
+ try {
989
+ const sessionId = await agents.spawn('zcode', absDir)
990
+ sendSpawnResult(requestId, sessionId)
991
+ } catch (e) {
992
+ sendSpawnResult(requestId, null, e.message || 'GLM 会话创建失败(需 ZCode 桌面端在线并开启远控)')
993
+ }
994
+ return
995
+ }
996
+
979
997
  if (!hubBin) {
980
998
  log(`[DEBUG:spawn] FAIL: hubBin is null`)
981
999
  sendSpawnResult(requestId, null, 'Hub binary not found')
@@ -1087,6 +1105,13 @@ async function handleResumeSession(requestId, sessionId) {
1087
1105
  log(`[DEBUG:resume] requestId=${requestId}, sessionId=${sessionId}`)
1088
1106
  const peer = takePeer(requestId)
1089
1107
 
1108
+ // Agent-namespaced sessions are persistent (codex rollout / zcode desktop) —
1109
+ // "resume" is a no-op that returns the same id; the chat page opens directly.
1110
+ if (typeof sessionId === 'string' && (sessionId.startsWith('codex:') || sessionId.startsWith('zcode:'))) {
1111
+ sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId }, peer)
1112
+ return
1113
+ }
1114
+
1090
1115
  if (!hubBin) {
1091
1116
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Hub binary not found' }, peer)
1092
1117
  return
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tina_summer/codepocket",
3
- "version": "2.7.0",
3
+ "version": "2.7.1",
4
4
  "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",
@@ -20,10 +20,10 @@
20
20
  "ws": "^8.18.0"
21
21
  },
22
22
  "optionalDependencies": {
23
- "@tina_summer/codepocket-darwin-arm64": "2.7.0",
24
- "@tina_summer/codepocket-darwin-x64": "2.7.0",
25
- "@tina_summer/codepocket-linux-x64": "2.7.0",
26
- "@tina_summer/codepocket-win32-x64": "2.7.0"
23
+ "@tina_summer/codepocket-darwin-arm64": "2.7.1",
24
+ "@tina_summer/codepocket-darwin-x64": "2.7.1",
25
+ "@tina_summer/codepocket-linux-x64": "2.7.1",
26
+ "@tina_summer/codepocket-win32-x64": "2.7.1"
27
27
  },
28
28
  "engines": {
29
29
  "node": ">=18"
@@ -106,7 +106,10 @@ function startServer(st) {
106
106
  proc.on('error', (err) => reject(new Error(`无法启动 codex app-server: ${err.message}`)))
107
107
 
108
108
  rpc(st, 'initialize', {
109
- clientInfo: { name: 'codepocket', version: '1' },
109
+ // clientInfo.name becomes the session originator — matching the TUI's
110
+ // own value ("codex_cli_rs") makes phone-created sessions appear in the
111
+ // terminal's /resume picker. Override-able via env for debugging.
112
+ clientInfo: { name: process.env.CODEPOCKET_CODEX_ORIGINATOR || 'codex_cli_rs', version: '1' },
110
113
  capabilities: { experimentalApi: true },
111
114
  }, INIT_TIMEOUT)
112
115
  .then((info) => {
@@ -203,11 +206,14 @@ async function refresh(st) {
203
206
  st.updatedAt = Date.now()
204
207
  const type = result && result.thread && result.thread.status && result.thread.status.type
205
208
  const isActive = type === 'active'
209
+ // Notify ONLY on actual state transitions — the poller runs every 1.5s and
210
+ // unconditional notify() floods the phone with session-updated SSE events
211
+ // (observed: WeChat service-thread timeout under the reload storm).
206
212
  if (isActive !== st.active) {
207
213
  st.active = isActive
208
214
  if (!isActive && st.poller) { clearInterval(st.poller); st.poller = null }
215
+ notify()
209
216
  }
210
- notify()
211
217
  } catch { /* transient read failure — keep last known state */ }
212
218
  }
213
219
 
@@ -27,8 +27,8 @@ function agentSessions() {
27
27
  const rows = rollout.sessionRows(_liveMapWithDiscovered(discovered))
28
28
  const zRows = zcode.listSessions().map(r => ({
29
29
  ...r,
30
- // 发送能力取决于 ws2 中继是否已连接(连接会占用官方手机端位)
31
- capabilities: zcodeLive.isReady() ? zcodeLive.LIVE_CAPS : { ...zcode.READONLY_CAPS, resume: true, share: true },
30
+ // 发送/新建能力取决于 ws2 中继是否已连接(连接会占用官方手机端位)
31
+ capabilities: zcodeLive.isReady() ? zcodeLive.LIVE_CAPS : { ...zcode.READONLY_CAPS, resume: true, share: true, spawn: true },
32
32
  }))
33
33
  return rows.concat(zRows)
34
34
  }
@@ -151,8 +151,9 @@ function handleRest(method, p, body) {
151
151
  }
152
152
 
153
153
  /** spawn-session routing; returns a promise of {sessionId} or throws. */
154
- function spawn(provider, dir) {
154
+ async function spawn(provider, dir) {
155
155
  if (provider === 'codex') return live.spawnSession(dir)
156
+ if (provider === 'zcode') return zcodeLive.createSession()
156
157
  throw new Error(`agent ${provider} 暂不支持从手机创建会话`)
157
158
  }
158
159
 
@@ -89,9 +89,9 @@ function listProviders() {
89
89
  })
90
90
 
91
91
  providers.push({
92
- key: 'zcode', label: 'GLM', spawn: false, cwdRequired: false, available: zcodeData,
92
+ key: 'zcode', label: 'GLM', spawn: zcodeData, cwdRequired: false, available: zcodeData,
93
93
  reason: zcodeData
94
- ? 'ZCode 会话:可查看历史并发送消息(需要 ZCode 桌面端在线并开启手机远控)'
94
+ ? 'ZCode 会话:可查看历史、发送消息、从手机新建(需 ZCode 桌面端在线并开启手机远控)'
95
95
  : '未检测到 ZCode 桌面端',
96
96
  })
97
97
 
@@ -317,8 +317,9 @@ class ZcodeRelayClient {
317
317
  return true
318
318
  }
319
319
 
320
- sendMessage(sessionId, text) {
320
+ sendMessage(sessionIdRaw, text) {
321
321
  if (!this.bridge) throw new Error('ZCode 中继未连接')
322
+ const sessionId = String(sessionIdRaw).replace(/^zcode:/, '')
322
323
  const envelope = {
323
324
  commandId: crypto.randomUUID(),
324
325
  clientId: this.clientId,
@@ -338,12 +339,40 @@ class ZcodeRelayClient {
338
339
  })
339
340
  }
340
341
 
342
+ /**
343
+ * Create a NEW conversation on the desktop via the verified createSession
344
+ * command (web-client shape: sessionId null + payload.workspaceId; the
345
+ * accepted result carries the new sess_ id). First message is NOT sent —
346
+ * the phone's composer sends it after landing on the session.
347
+ */
348
+ async createSession() {
349
+ if (!this.bridge) throw new Error('ZCode 中继未连接')
350
+ const r = await this.call('zcode-agent', 'sendConversationCommandV4', {
351
+ workspacePath: this.bridge.workspaceKey,
352
+ envelope: {
353
+ commandId: crypto.randomUUID(),
354
+ clientId: this.clientId,
355
+ sessionId: null,
356
+ type: 'createSession',
357
+ payload: {
358
+ workspaceId: this.bridge.workspaceKey,
359
+ },
360
+ issuedAt: Date.now(),
361
+ },
362
+ }, 30000)
363
+ if (!r || r.status !== 'accepted' || !(r.result && r.result.sessionId)) {
364
+ throw new Error('ZCode 新建会话被拒: ' + JSON.stringify(r).slice(0, 160))
365
+ }
366
+ return 'zcode:' + r.result.sessionId
367
+ }
368
+
341
369
  /** Open (or re-open) the workspace bridge bound to a specific task so the
342
370
  * agent channel can resolve its sessionId (verified: without setting the
343
371
  * task view + taskId-bound bridge the send is rejected with
344
372
  * proto.sessionNotFound). */
345
- async bindTask(sessionId) {
373
+ async bindTask(sessionIdRaw) {
346
374
  if (!this.bridge) throw new Error('ZCode 中继未连接')
375
+ const sessionId = String(sessionIdRaw).replace(/^zcode:/, '') // strip namespace prefix
347
376
  if (this.bridge.taskId === sessionId) return
348
377
  // 1. set the desktop's active task view + view state to the target session
349
378
  // (verified from the captured web flow: both updates precede a successful send)
@@ -452,10 +481,31 @@ function resetClient() {
452
481
  }
453
482
 
454
483
  function sendMessage(sessionId, text) {
455
- const attempt = () => getClient().then(async c => {
484
+ // Try the CURRENT bridge first — fresh sessions and already-bound sessions
485
+ // send directly (verified). Only sessionNotFound triggers a task re-bind;
486
+ // unconditional bindTask destabilizes freshly-created runtimes.
487
+ const direct = () => getClient().then(c => c.sendMessage(String(sessionId).replace(/^zcode:/, ''), text))
488
+ const withBind = () => getClient().then(async c => {
456
489
  await c.bindTask(sessionId)
457
- return c.sendMessage(sessionId, text)
490
+ return c.sendMessage(String(sessionId).replace(/^zcode:/, ''), text)
458
491
  })
492
+ return direct().then(r => {
493
+ if (r && r.status === 'rejected' && /sessionNotFound/i.test(String(r.reasonCode || ''))) {
494
+ return withBind()
495
+ }
496
+ return r
497
+ }).catch(e => {
498
+ const msg = String(e && e.message || e)
499
+ if (/超时|timeout|not ready|未连接|closed|degraded/i.test(msg)) {
500
+ resetClient()
501
+ return withBind()
502
+ }
503
+ throw e
504
+ })
505
+ }
506
+
507
+ function createSession() {
508
+ const attempt = () => getClient().then(c => c.createSession())
459
509
  return attempt().catch(e => {
460
510
  const msg = String(e && e.message || e)
461
511
  if (/超时|timeout|not ready|未连接|closed|degraded/i.test(msg)) {
@@ -472,5 +522,5 @@ function liveInfo() {
472
522
 
473
523
  module.exports = {
474
524
  LIVE_CAPS, readDeviceConfig, readJwt,
475
- getClient, sendMessage, isReady, liveInfo, onSessionEvent,
525
+ getClient, sendMessage, createSession, isReady, liveInfo, onSessionEvent,
476
526
  }