@tina_summer/codepocket 2.2.6 → 2.2.8

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 (2) hide show
  1. package/bin/codepocket.js +115 -75
  2. package/package.json +1 -1
package/bin/codepocket.js CHANGED
@@ -98,11 +98,13 @@ function findHubBin() {
98
98
  return null
99
99
  }
100
100
 
101
- function isHubRunning(hubUrl) {
101
+ async function isHubRunning(hubUrl) {
102
102
  try {
103
- const code = execSync(`curl -s -o /dev/null -w "%{http_code}" --max-time 2 ${hubUrl}/api/sessions 2>/dev/null`).toString().trim()
104
- // Any HTTP response (including 401) means the hub server is up
105
- return /^\d{3}$/.test(code) && code !== '000'
103
+ const controller = new AbortController()
104
+ const timer = setTimeout(() => controller.abort(), 2000)
105
+ const res = await fetch(`${hubUrl}/api/sessions`, { signal: controller.signal })
106
+ clearTimeout(timer)
107
+ return res.status > 0 // Any HTTP response means hub is up
106
108
  } catch { return false }
107
109
  }
108
110
 
@@ -266,27 +268,25 @@ function log(msg) {
266
268
 
267
269
  function waitForHub() {
268
270
  return new Promise((resolve) => {
269
- if (noHub || isHubRunning(hubUrl)) { resolve(); return }
271
+ if (noHub) { resolve(); return }
272
+ isHubRunning(hubUrl).then(up => { if (up) { resolve(); return } })
270
273
  let attempts = 0
271
274
  const check = setInterval(() => {
272
275
  attempts++
273
- if (isHubRunning(hubUrl)) {
274
- clearInterval(check)
275
- resolve()
276
- } else if (attempts > 30) {
277
- clearInterval(check)
278
- resolve()
279
- }
276
+ isHubRunning(hubUrl).then(up => {
277
+ if (up) { clearInterval(check); resolve() }
278
+ else if (attempts > 30) { clearInterval(check); resolve() }
279
+ })
280
280
  }, 1000)
281
281
  })
282
282
  }
283
283
 
284
- function startHub(hubBin) {
285
- return new Promise((resolve) => {
286
- if (noHub) { resolve(); return }
287
- if (isHubRunning(hubUrl)) { resolve(); return }
288
- if (!hubBin) { resolve(); return }
284
+ async function startHub(hubBin) {
285
+ if (noHub) return
286
+ if (await isHubRunning(hubUrl)) return
287
+ if (!hubBin) return
289
288
 
289
+ return new Promise((resolve) => {
290
290
  const hub = spawn(hubBin, ['hub', 'start'], {
291
291
  stdio: ['ignore', 'pipe', 'pipe'],
292
292
  detached: false,
@@ -303,8 +303,8 @@ function startHub(hubBin) {
303
303
  }
304
304
  })
305
305
 
306
- setTimeout(() => {
307
- if (!started && isHubRunning(hubUrl)) { started = true }
306
+ setTimeout(async () => {
307
+ if (!started && await isHubRunning(hubUrl)) { started = true }
308
308
  resolve()
309
309
  }, 8000)
310
310
 
@@ -533,21 +533,35 @@ async function handleSpawnSession(requestId, directory) {
533
533
  log(`[DEBUG:spawn] Expanded directory: ${directory}`)
534
534
 
535
535
  try {
536
- const spawnArgs = ['--path', directory]
537
- log(`[DEBUG:spawn] Spawning: ${hubBin} ${spawnArgs.join(' ')}`)
536
+ const spawnArgs = ['claude', '--codepocket-starting-mode', 'remote']
537
+ log(`[DEBUG:spawn] Spawning: ${hubBin} ${spawnArgs.join(' ')} in ${directory}`)
538
538
 
539
539
  const child = spawn(hubBin, spawnArgs, {
540
- stdio: 'ignore',
540
+ stdio: ['ignore', 'pipe', 'pipe'],
541
541
  detached: true,
542
+ cwd: directory,
542
543
  env: { ...process.env, ...HOME_ENV },
543
544
  })
544
545
  log(`[DEBUG:spawn] Process spawned, PID=${child.pid}`)
546
+ let spawnStderr = ''
547
+ child.stderr.on('data', (d) => {
548
+ const text = d.toString().trim()
549
+ if (text) {
550
+ spawnStderr += text + '\n'
551
+ log(`[DEBUG:spawn] stderr: ${text.slice(0, 500)}`)
552
+ }
553
+ })
554
+ child.stdout.on('data', (d) => {
555
+ const text = d.toString().trim()
556
+ if (text) log(`[DEBUG:spawn] stdout: ${text.slice(0, 500)}`)
557
+ })
545
558
  child.unref()
546
559
  child.on('error', (err) => {
547
560
  log(`[DEBUG:spawn] Process error: ${err.message}`)
548
561
  })
549
562
  child.on('exit', (code, signal) => {
550
563
  log(`[DEBUG:spawn] Process exited: code=${code}, signal=${signal}, PID=${child.pid}`)
564
+ if (spawnStderr) log(`[DEBUG:spawn] Full stderr:\n${spawnStderr.slice(0, 2000)}`)
551
565
  })
552
566
 
553
567
  // Refresh JWT before polling
@@ -619,125 +633,151 @@ async function handleSpawnSession(requestId, directory) {
619
633
  async function handleResumeSession(requestId, sessionId) {
620
634
  log(`[DEBUG:resume] === START resume-session ===`)
621
635
  log(`[DEBUG:resume] requestId=${requestId}, sessionId=${sessionId}`)
622
- log(`[DEBUG:resume] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
623
636
 
624
637
  if (!hubBin) {
625
- log(`[DEBUG:resume] FAIL: hubBin is null`)
626
638
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Hub binary not found' })
627
639
  return
628
640
  }
629
641
  if (!sessionId) {
630
- log(`[DEBUG:resume] FAIL: sessionId is empty`)
631
642
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session ID is required' })
632
643
  return
633
644
  }
634
645
 
635
646
  try {
636
- // 1. Fetch session metadata from Hub
637
- log(`[DEBUG:resume] Fetching session metadata...`)
647
+ // 1. Fetch session metadata to get the working directory
638
648
  let res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
639
649
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
640
650
  })
641
- log(`[DEBUG:resume] Metadata fetch status=${res.status}`)
642
651
  if (res.status === 401) {
643
- log(`[DEBUG:resume] Got 401, refreshing JWT...`)
644
652
  const token = await findHubToken()
645
653
  jwt = await authenticateHub(token)
646
654
  res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
647
655
  headers: { Authorization: `Bearer ${jwt}` },
648
656
  })
649
- log(`[DEBUG:resume] Retry status=${res.status}`)
650
657
  }
651
658
  if (!res.ok) {
652
- log(`[DEBUG:resume] FAIL: metadata fetch returned ${res.status}`)
653
659
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: `Session not found (${res.status})` })
654
660
  return
655
661
  }
656
662
  const data = await res.json()
657
663
  const session = data.session || data
658
664
  const directory = (session.metadata?.path || '').replace(/^~/, os.homedir())
659
- let claudeSessionId = session.metadata?.agentSessionId || session.metadata?.claudeSessionId
660
-
661
- log(`[DEBUG:resume] Session metadata: directory=${directory}, claudeSessionId=${claudeSessionId || 'NOT SET'}`)
662
- log(`[DEBUG:resume] Full metadata: ${JSON.stringify(session.metadata || {})}`)
663
-
664
665
  if (!directory) {
665
- log(`[DEBUG:resume] FAIL: no directory in metadata`)
666
666
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session has no working directory' })
667
667
  return
668
668
  }
669
669
 
670
- // Fallback: if claudeSessionId not in metadata, scan for the session file directly
670
+ // 2. Spawn in remote mode with --resume to load old conversation context
671
+ let claudeSessionId = session.metadata?.agentSessionId || session.metadata?.claudeSessionId
671
672
  if (!claudeSessionId) {
672
673
  claudeSessionId = findClaudeSessionFile(directory)
673
- if (claudeSessionId) {
674
- log(`[DEBUG:resume] claudeSessionId resolved from file scan: ${claudeSessionId}`)
675
- } else {
676
- log(`[DEBUG:resume] No session file found, using Hub session ID as fallback`)
677
- claudeSessionId = sessionId
678
- }
674
+ log(`[DEBUG:resume] claudeSessionId from file scan: ${claudeSessionId || 'NOT FOUND'}`)
675
+ }
676
+ const spawnArgs = ['claude', '--codepocket-starting-mode', 'remote']
677
+ if (claudeSessionId) {
678
+ spawnArgs.push('--resume', claudeSessionId)
679
679
  }
680
+ log(`[DEBUG:resume] claudeSessionId: ${claudeSessionId || 'NONE'}`)
680
681
 
681
- // 2. Spawn with --resume
682
- const spawnArgs = ['--path', directory, '--resume', claudeSessionId]
683
- log(`[DEBUG:resume] Spawning: ${hubBin} ${spawnArgs.join(' ')}`)
682
+ // Log sessions BEFORE spawn
683
+ try {
684
+ const beforeRes = await fetch(`${hubUrl}/api/sessions`, {
685
+ headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
686
+ })
687
+ const beforeData = await beforeRes.json()
688
+ const beforeSessions = beforeData.sessions || []
689
+ const dirSessions = beforeSessions.filter(s => s.metadata?.path === directory)
690
+ log(`[DEBUG:resume] BEFORE spawn: ${dirSessions.length} sessions for ${directory}: ${dirSessions.map(s => `${s.id}(active=${s.active})`).join(', ')}`)
691
+ } catch {}
692
+
693
+ log(`[DEBUG:resume] Spawning: ${hubBin} ${spawnArgs.join(' ')} (cwd=${directory})`)
694
+ log(`[DEBUG:resume] ENV CODEPOCKET_HOME=${process.env.CODEPOCKET_HOME || HOME_ENV.CODEPOCKET_HOME}`)
684
695
  const child = spawn(hubBin, spawnArgs, {
685
- stdio: 'ignore',
696
+ stdio: ['ignore', 'pipe', 'pipe'],
686
697
  detached: true,
698
+ cwd: directory,
687
699
  env: { ...process.env, ...HOME_ENV },
688
700
  })
689
701
  log(`[DEBUG:resume] Process spawned, PID=${child.pid}`)
702
+
703
+ // Check if process is still alive after 500ms
704
+ setTimeout(() => {
705
+ try {
706
+ process.kill(child.pid, 0)
707
+ log(`[DEBUG:resume] Health check: PID=${child.pid} is alive`)
708
+ } catch (e) {
709
+ log(`[DEBUG:resume] Health check: PID=${child.pid} is DEAD already: ${e.message}`)
710
+ }
711
+ }, 500)
712
+
713
+ let resumeStderr = ''
714
+ child.stderr.on('data', (d) => {
715
+ const text = d.toString().trim()
716
+ if (text) {
717
+ resumeStderr += text + '\n'
718
+ log(`[DEBUG:resume] stderr: ${text.slice(0, 500)}`)
719
+ }
720
+ })
721
+ child.stdout.on('data', (d) => {
722
+ const text = d.toString().trim()
723
+ if (text) log(`[DEBUG:resume] stdout: ${text.slice(0, 500)}`)
724
+ })
690
725
  child.unref()
691
726
  child.on('error', (err) => {
692
727
  log(`[DEBUG:resume] Process error: ${err.message}`)
693
728
  })
694
729
  child.on('exit', (code, signal) => {
695
730
  log(`[DEBUG:resume] Process exited: code=${code}, signal=${signal}, PID=${child.pid}`)
731
+ if (resumeStderr) log(`[DEBUG:resume] Full stderr:\n${resumeStderr.slice(0, 2000)}`)
696
732
  })
697
733
 
698
- // 3. Poll for session to become active
699
- let resumed = false
700
- let newSession = null
734
+ // 3. Refresh JWT and poll for new session
735
+ try {
736
+ const token = await findHubToken()
737
+ jwt = await authenticateHub(token)
738
+ } catch (err) {
739
+ log(`[DEBUG:resume] JWT refresh failed: ${err.message}`)
740
+ }
741
+
742
+ const spawnTime = Date.now()
743
+ let newSessionId = null
701
744
  for (let i = 0; i < 30; i++) {
702
745
  await new Promise(r => setTimeout(r, 1000))
703
746
  try {
704
- const pollRes = await fetch(`${hubUrl}/api/sessions`, {
747
+ let pollRes = await fetch(`${hubUrl}/api/sessions`, {
705
748
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
706
749
  })
750
+ if (pollRes.status === 401) {
751
+ const token = await findHubToken()
752
+ jwt = await authenticateHub(token)
753
+ pollRes = await fetch(`${hubUrl}/api/sessions`, {
754
+ headers: { Authorization: `Bearer ${jwt}` },
755
+ })
756
+ }
707
757
  const pollData = await pollRes.json()
708
758
  const sessions = pollData.sessions || (Array.isArray(pollData) ? pollData : [])
709
- if (i === 0 || sessions.find(s => s.metadata?.path === directory)) {
710
- log(`[DEBUG:resume] Poll #${i + 1}: ${sessions.length} sessions, matching path sessions: ${sessions.filter(s => s.metadata?.path === directory).map(s => `${s.id}(active=${s.active})`).join(', ')}`)
711
- }
759
+ // Find a NEW session (created after spawn) for the same directory
712
760
  const match = sessions.find(s =>
713
- s.metadata?.path === directory && s.active && s.id !== sessionId
761
+ s.metadata?.path === directory && s.id
762
+ && (!s.updatedAt || s.updatedAt * 1000 >= spawnTime - 5000)
763
+ && s.id !== sessionId
714
764
  )
715
765
  if (match) {
716
- newSession = match
717
- resumed = true
718
- log(`[DEBUG:resume] Poll #${i + 1}: FOUND active session=${match.id}`)
719
- break
766
+ newSessionId = match.id
767
+ log(`[DEBUG:resume] Poll #${i + 1}: FOUND new session=${match.id}, active=${!!match.active}`)
768
+ if (match.active) break
720
769
  }
721
770
  } catch (err) {
722
- log(`[DEBUG:resume] Poll #${i + 1}: fetch error: ${err.message}`)
771
+ log(`[DEBUG:resume] Poll #${i + 1}: error: ${err.message}`)
723
772
  }
724
773
  }
725
774
 
726
- if (resumed) {
727
- // Delete the old inactive session to avoid duplicates
728
- try {
729
- await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
730
- method: 'DELETE',
731
- headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
732
- })
733
- log(`[DEBUG:resume] Deleted old session: ${sessionId}`)
734
- } catch (e) {
735
- log(`[DEBUG:resume] Failed to delete old session: ${e.message}`)
736
- }
737
- log(`[DEBUG:resume] RESULT: resumed=${newSession.id} (replaced ${sessionId})`)
738
- sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: newSession.id })
775
+ if (newSessionId) {
776
+ // Don't delete old session — mini-program needs it for message history
777
+ log(`[DEBUG:resume] RESULT: new session=${newSessionId}, old session=${sessionId} preserved for history`)
778
+ sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: newSessionId, oldSessionId: sessionId })
739
779
  } else {
740
- log(`[DEBUG:resume] RESULT: no active session found after 30 polls`)
780
+ log(`[DEBUG:resume] RESULT: no new session found after 30 polls`)
741
781
  sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: null, warning: 'Session resuming' })
742
782
  }
743
783
  } catch (err) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tina_summer/codepocket",
3
- "version": "2.2.6",
3
+ "version": "2.2.8",
4
4
  "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",