@tina_summer/codepocket 2.2.7 → 2.2.9

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 +72 -56
  2. package/package.json +1 -1
package/bin/codepocket.js CHANGED
@@ -382,8 +382,10 @@ function connectRelay() {
382
382
  sessionToken: savedSession?.sessionToken || undefined,
383
383
  }))
384
384
  relayPingInterval = setInterval(() => {
385
- if (relayWs?.readyState === WebSocket.OPEN) relayWs.ping()
386
- }, 30000)
385
+ if (relayWs?.readyState === WebSocket.OPEN) {
386
+ relayWs.send(JSON.stringify({ type: 'ping' }))
387
+ }
388
+ }, 25000)
387
389
  })
388
390
 
389
391
  relayWs.on('message', (raw) => {
@@ -533,12 +535,13 @@ async function handleSpawnSession(requestId, directory) {
533
535
  log(`[DEBUG:spawn] Expanded directory: ${directory}`)
534
536
 
535
537
  try {
536
- const spawnArgs = ['--path', directory]
537
- log(`[DEBUG:spawn] Spawning: ${hubBin} ${spawnArgs.join(' ')}`)
538
+ const spawnArgs = ['claude', '--codepocket-starting-mode', 'remote']
539
+ log(`[DEBUG:spawn] Spawning: ${hubBin} ${spawnArgs.join(' ')} in ${directory}`)
538
540
 
539
541
  const child = spawn(hubBin, spawnArgs, {
540
542
  stdio: ['ignore', 'pipe', 'pipe'],
541
543
  detached: true,
544
+ cwd: directory,
542
545
  env: { ...process.env, ...HOME_ENV },
543
546
  })
544
547
  log(`[DEBUG:spawn] Process spawned, PID=${child.pid}`)
@@ -632,74 +635,83 @@ async function handleSpawnSession(requestId, directory) {
632
635
  async function handleResumeSession(requestId, sessionId) {
633
636
  log(`[DEBUG:resume] === START resume-session ===`)
634
637
  log(`[DEBUG:resume] requestId=${requestId}, sessionId=${sessionId}`)
635
- log(`[DEBUG:resume] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
636
638
 
637
639
  if (!hubBin) {
638
- log(`[DEBUG:resume] FAIL: hubBin is null`)
639
640
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Hub binary not found' })
640
641
  return
641
642
  }
642
643
  if (!sessionId) {
643
- log(`[DEBUG:resume] FAIL: sessionId is empty`)
644
644
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session ID is required' })
645
645
  return
646
646
  }
647
647
 
648
648
  try {
649
- // 1. Fetch session metadata from Hub
650
- log(`[DEBUG:resume] Fetching session metadata...`)
649
+ // 1. Fetch session metadata to get the working directory
651
650
  let res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
652
651
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
653
652
  })
654
- log(`[DEBUG:resume] Metadata fetch status=${res.status}`)
655
653
  if (res.status === 401) {
656
- log(`[DEBUG:resume] Got 401, refreshing JWT...`)
657
654
  const token = await findHubToken()
658
655
  jwt = await authenticateHub(token)
659
656
  res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
660
657
  headers: { Authorization: `Bearer ${jwt}` },
661
658
  })
662
- log(`[DEBUG:resume] Retry status=${res.status}`)
663
659
  }
664
660
  if (!res.ok) {
665
- log(`[DEBUG:resume] FAIL: metadata fetch returned ${res.status}`)
666
661
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: `Session not found (${res.status})` })
667
662
  return
668
663
  }
669
664
  const data = await res.json()
670
665
  const session = data.session || data
671
666
  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
667
  if (!directory) {
678
- log(`[DEBUG:resume] FAIL: no directory in metadata`)
679
668
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session has no working directory' })
680
669
  return
681
670
  }
682
671
 
683
- // Fallback: if claudeSessionId not in metadata, scan for the session file directly
672
+ // 2. Spawn in remote mode with --resume to load old conversation context
673
+ let claudeSessionId = session.metadata?.agentSessionId || session.metadata?.claudeSessionId
684
674
  if (!claudeSessionId) {
685
675
  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
- }
676
+ log(`[DEBUG:resume] claudeSessionId from file scan: ${claudeSessionId || 'NOT FOUND'}`)
677
+ }
678
+ const spawnArgs = ['claude', '--codepocket-starting-mode', 'remote']
679
+ if (claudeSessionId) {
680
+ spawnArgs.push('--resume', claudeSessionId)
692
681
  }
682
+ log(`[DEBUG:resume] claudeSessionId: ${claudeSessionId || 'NONE'}`)
693
683
 
694
- // 2. Spawn with --resume
695
- const spawnArgs = ['--path', directory, '--resume', claudeSessionId]
696
- log(`[DEBUG:resume] Spawning: ${hubBin} ${spawnArgs.join(' ')}`)
684
+ // Log sessions BEFORE spawn
685
+ try {
686
+ const beforeRes = await fetch(`${hubUrl}/api/sessions`, {
687
+ headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
688
+ })
689
+ const beforeData = await beforeRes.json()
690
+ const beforeSessions = beforeData.sessions || []
691
+ const dirSessions = beforeSessions.filter(s => s.metadata?.path === directory)
692
+ log(`[DEBUG:resume] BEFORE spawn: ${dirSessions.length} sessions for ${directory}: ${dirSessions.map(s => `${s.id}(active=${s.active})`).join(', ')}`)
693
+ } catch {}
694
+
695
+ log(`[DEBUG:resume] Spawning: ${hubBin} ${spawnArgs.join(' ')} (cwd=${directory})`)
696
+ log(`[DEBUG:resume] ENV CODEPOCKET_HOME=${process.env.CODEPOCKET_HOME || HOME_ENV.CODEPOCKET_HOME}`)
697
697
  const child = spawn(hubBin, spawnArgs, {
698
698
  stdio: ['ignore', 'pipe', 'pipe'],
699
699
  detached: true,
700
+ cwd: directory,
700
701
  env: { ...process.env, ...HOME_ENV },
701
702
  })
702
703
  log(`[DEBUG:resume] Process spawned, PID=${child.pid}`)
704
+
705
+ // Check if process is still alive after 500ms
706
+ setTimeout(() => {
707
+ try {
708
+ process.kill(child.pid, 0)
709
+ log(`[DEBUG:resume] Health check: PID=${child.pid} is alive`)
710
+ } catch (e) {
711
+ log(`[DEBUG:resume] Health check: PID=${child.pid} is DEAD already: ${e.message}`)
712
+ }
713
+ }, 500)
714
+
703
715
  let resumeStderr = ''
704
716
  child.stderr.on('data', (d) => {
705
717
  const text = d.toString().trim()
@@ -721,49 +733,53 @@ async function handleResumeSession(requestId, sessionId) {
721
733
  if (resumeStderr) log(`[DEBUG:resume] Full stderr:\n${resumeStderr.slice(0, 2000)}`)
722
734
  })
723
735
 
724
- // 3. Poll for session to become active
725
- let resumed = false
726
- let newSession = null
736
+ // 3. Refresh JWT and poll for new session
737
+ try {
738
+ const token = await findHubToken()
739
+ jwt = await authenticateHub(token)
740
+ } catch (err) {
741
+ log(`[DEBUG:resume] JWT refresh failed: ${err.message}`)
742
+ }
743
+
744
+ const spawnTime = Date.now()
745
+ let newSessionId = null
727
746
  for (let i = 0; i < 30; i++) {
728
747
  await new Promise(r => setTimeout(r, 1000))
729
748
  try {
730
- const pollRes = await fetch(`${hubUrl}/api/sessions`, {
749
+ let pollRes = await fetch(`${hubUrl}/api/sessions`, {
731
750
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
732
751
  })
752
+ if (pollRes.status === 401) {
753
+ const token = await findHubToken()
754
+ jwt = await authenticateHub(token)
755
+ pollRes = await fetch(`${hubUrl}/api/sessions`, {
756
+ headers: { Authorization: `Bearer ${jwt}` },
757
+ })
758
+ }
733
759
  const pollData = await pollRes.json()
734
760
  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
- }
761
+ // Find a NEW session (created after spawn) for the same directory
738
762
  const match = sessions.find(s =>
739
- s.metadata?.path === directory && s.active && s.id !== sessionId
763
+ s.metadata?.path === directory && s.id
764
+ && (!s.updatedAt || s.updatedAt * 1000 >= spawnTime - 5000)
765
+ && s.id !== sessionId
740
766
  )
741
767
  if (match) {
742
- newSession = match
743
- resumed = true
744
- log(`[DEBUG:resume] Poll #${i + 1}: FOUND active session=${match.id}`)
745
- break
768
+ newSessionId = match.id
769
+ log(`[DEBUG:resume] Poll #${i + 1}: FOUND new session=${match.id}, active=${!!match.active}`)
770
+ if (match.active) break
746
771
  }
747
772
  } catch (err) {
748
- log(`[DEBUG:resume] Poll #${i + 1}: fetch error: ${err.message}`)
773
+ log(`[DEBUG:resume] Poll #${i + 1}: error: ${err.message}`)
749
774
  }
750
775
  }
751
776
 
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 })
777
+ if (newSessionId) {
778
+ // Don't delete old session — mini-program needs it for message history
779
+ log(`[DEBUG:resume] RESULT: new session=${newSessionId}, old session=${sessionId} preserved for history`)
780
+ sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: newSessionId, oldSessionId: sessionId })
765
781
  } else {
766
- log(`[DEBUG:resume] RESULT: no active session found after 30 polls`)
782
+ log(`[DEBUG:resume] RESULT: no new session found after 30 polls`)
767
783
  sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: null, warning: 'Session resuming' })
768
784
  }
769
785
  } 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.9",
4
4
  "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",