@tina_summer/codepocket 2.2.7 → 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 +68 -54
  2. package/package.json +1 -1
package/bin/codepocket.js CHANGED
@@ -533,12 +533,13 @@ 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
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}`)
@@ -632,74 +633,83 @@ async function handleSpawnSession(requestId, directory) {
632
633
  async function handleResumeSession(requestId, sessionId) {
633
634
  log(`[DEBUG:resume] === START resume-session ===`)
634
635
  log(`[DEBUG:resume] requestId=${requestId}, sessionId=${sessionId}`)
635
- log(`[DEBUG:resume] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
636
636
 
637
637
  if (!hubBin) {
638
- log(`[DEBUG:resume] FAIL: hubBin is null`)
639
638
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Hub binary not found' })
640
639
  return
641
640
  }
642
641
  if (!sessionId) {
643
- log(`[DEBUG:resume] FAIL: sessionId is empty`)
644
642
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session ID is required' })
645
643
  return
646
644
  }
647
645
 
648
646
  try {
649
- // 1. Fetch session metadata from Hub
650
- log(`[DEBUG:resume] Fetching session metadata...`)
647
+ // 1. Fetch session metadata to get the working directory
651
648
  let res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
652
649
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
653
650
  })
654
- log(`[DEBUG:resume] Metadata fetch status=${res.status}`)
655
651
  if (res.status === 401) {
656
- log(`[DEBUG:resume] Got 401, refreshing JWT...`)
657
652
  const token = await findHubToken()
658
653
  jwt = await authenticateHub(token)
659
654
  res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
660
655
  headers: { Authorization: `Bearer ${jwt}` },
661
656
  })
662
- log(`[DEBUG:resume] Retry status=${res.status}`)
663
657
  }
664
658
  if (!res.ok) {
665
- log(`[DEBUG:resume] FAIL: metadata fetch returned ${res.status}`)
666
659
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: `Session not found (${res.status})` })
667
660
  return
668
661
  }
669
662
  const data = await res.json()
670
663
  const session = data.session || data
671
664
  const directory = (session.metadata?.path || '').replace(/^~/, os.homedir())
672
- let claudeSessionId = session.metadata?.agentSessionId || session.metadata?.claudeSessionId
673
-
674
- log(`[DEBUG:resume] Session metadata: directory=${directory}, claudeSessionId=${claudeSessionId || 'NOT SET'}`)
675
- log(`[DEBUG:resume] Full metadata: ${JSON.stringify(session.metadata || {})}`)
676
-
677
665
  if (!directory) {
678
- log(`[DEBUG:resume] FAIL: no directory in metadata`)
679
666
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session has no working directory' })
680
667
  return
681
668
  }
682
669
 
683
- // 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
684
672
  if (!claudeSessionId) {
685
673
  claudeSessionId = findClaudeSessionFile(directory)
686
- if (claudeSessionId) {
687
- log(`[DEBUG:resume] claudeSessionId resolved from file scan: ${claudeSessionId}`)
688
- } else {
689
- log(`[DEBUG:resume] No session file found, using Hub session ID as fallback`)
690
- claudeSessionId = sessionId
691
- }
674
+ log(`[DEBUG:resume] claudeSessionId from file scan: ${claudeSessionId || 'NOT FOUND'}`)
692
675
  }
676
+ const spawnArgs = ['claude', '--codepocket-starting-mode', 'remote']
677
+ if (claudeSessionId) {
678
+ spawnArgs.push('--resume', claudeSessionId)
679
+ }
680
+ log(`[DEBUG:resume] claudeSessionId: ${claudeSessionId || 'NONE'}`)
693
681
 
694
- // 2. Spawn with --resume
695
- const spawnArgs = ['--path', directory, '--resume', claudeSessionId]
696
- 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}`)
697
695
  const child = spawn(hubBin, spawnArgs, {
698
696
  stdio: ['ignore', 'pipe', 'pipe'],
699
697
  detached: true,
698
+ cwd: directory,
700
699
  env: { ...process.env, ...HOME_ENV },
701
700
  })
702
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
+
703
713
  let resumeStderr = ''
704
714
  child.stderr.on('data', (d) => {
705
715
  const text = d.toString().trim()
@@ -721,49 +731,53 @@ async function handleResumeSession(requestId, sessionId) {
721
731
  if (resumeStderr) log(`[DEBUG:resume] Full stderr:\n${resumeStderr.slice(0, 2000)}`)
722
732
  })
723
733
 
724
- // 3. Poll for session to become active
725
- let resumed = false
726
- 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
727
744
  for (let i = 0; i < 30; i++) {
728
745
  await new Promise(r => setTimeout(r, 1000))
729
746
  try {
730
- const pollRes = await fetch(`${hubUrl}/api/sessions`, {
747
+ let pollRes = await fetch(`${hubUrl}/api/sessions`, {
731
748
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
732
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
+ }
733
757
  const pollData = await pollRes.json()
734
758
  const sessions = pollData.sessions || (Array.isArray(pollData) ? pollData : [])
735
- if (i === 0 || sessions.find(s => s.metadata?.path === directory)) {
736
- 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(', ')}`)
737
- }
759
+ // Find a NEW session (created after spawn) for the same directory
738
760
  const match = sessions.find(s =>
739
- 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
740
764
  )
741
765
  if (match) {
742
- newSession = match
743
- resumed = true
744
- log(`[DEBUG:resume] Poll #${i + 1}: FOUND active session=${match.id}`)
745
- 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
746
769
  }
747
770
  } catch (err) {
748
- log(`[DEBUG:resume] Poll #${i + 1}: fetch error: ${err.message}`)
771
+ log(`[DEBUG:resume] Poll #${i + 1}: error: ${err.message}`)
749
772
  }
750
773
  }
751
774
 
752
- if (resumed) {
753
- // Delete the old inactive session to avoid duplicates
754
- try {
755
- await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
756
- method: 'DELETE',
757
- headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
758
- })
759
- log(`[DEBUG:resume] Deleted old session: ${sessionId}`)
760
- } catch (e) {
761
- log(`[DEBUG:resume] Failed to delete old session: ${e.message}`)
762
- }
763
- log(`[DEBUG:resume] RESULT: resumed=${newSession.id} (replaced ${sessionId})`)
764
- 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 })
765
779
  } else {
766
- log(`[DEBUG:resume] RESULT: no active session found after 30 polls`)
780
+ log(`[DEBUG:resume] RESULT: no new session found after 30 polls`)
767
781
  sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: null, warning: 'Session resuming' })
768
782
  }
769
783
  } catch (err) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tina_summer/codepocket",
3
- "version": "2.2.7",
3
+ "version": "2.2.8",
4
4
  "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",