@tina_summer/codepocket 2.2.4 → 2.2.6

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 +111 -24
  2. package/package.json +1 -1
package/bin/codepocket.js CHANGED
@@ -100,7 +100,9 @@ function findHubBin() {
100
100
 
101
101
  function isHubRunning(hubUrl) {
102
102
  try {
103
- return execSync(`curl -s -o /dev/null -w "%{http_code}" ${hubUrl}/ 2>/dev/null`).toString().trim() === '200'
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'
104
106
  } catch { return false }
105
107
  }
106
108
 
@@ -405,10 +407,12 @@ function connectRelay() {
405
407
  break
406
408
  }
407
409
  case 'rest-request': {
410
+ log(`[DEBUG:relay] rest-request: ${msg.method} ${msg.path}`)
408
411
  forwardToHub(msg.requestId, msg.method, msg.path, msg.body)
409
412
  break
410
413
  }
411
414
  case 'auth-request': {
415
+ log(`[DEBUG:relay] auth-request`)
412
416
  handleAuthRequest(msg.requestId, msg.accessToken)
413
417
  break
414
418
  }
@@ -421,10 +425,12 @@ function connectRelay() {
421
425
  break
422
426
  }
423
427
  case 'spawn-session': {
428
+ log(`[DEBUG:relay] >>> spawn-session received, directory=${msg.directory}`)
424
429
  handleSpawnSession(msg.requestId, msg.directory)
425
430
  break
426
431
  }
427
432
  case 'resume-session': {
433
+ log(`[DEBUG:relay] >>> resume-session received, sessionId=${msg.sessionId}`)
428
434
  handleResumeSession(msg.requestId, msg.sessionId)
429
435
  break
430
436
  }
@@ -506,11 +512,17 @@ async function handleAuthRequest(requestId, accessToken) {
506
512
  }
507
513
 
508
514
  async function handleSpawnSession(requestId, directory) {
515
+ log(`[DEBUG:spawn] === START spawn-session ===`)
516
+ log(`[DEBUG:spawn] requestId=${requestId}, raw directory=${directory}`)
517
+ log(`[DEBUG:spawn] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
518
+
509
519
  if (!hubBin) {
520
+ log(`[DEBUG:spawn] FAIL: hubBin is null`)
510
521
  sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Hub binary not found' })
511
522
  return
512
523
  }
513
524
  if (!directory || typeof directory !== 'string') {
525
+ log(`[DEBUG:spawn] FAIL: directory invalid`)
514
526
  sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Directory is required' })
515
527
  return
516
528
  }
@@ -518,76 +530,126 @@ async function handleSpawnSession(requestId, directory) {
518
530
  // Expand ~ to home directory
519
531
  directory = directory.replace(/^~/, os.homedir())
520
532
 
521
- log(`[codepocket] Spawning session in: ${directory}`)
533
+ log(`[DEBUG:spawn] Expanded directory: ${directory}`)
522
534
 
523
535
  try {
524
- const child = spawn(hubBin, ['--path', directory], {
536
+ const spawnArgs = ['--path', directory]
537
+ log(`[DEBUG:spawn] Spawning: ${hubBin} ${spawnArgs.join(' ')}`)
538
+
539
+ const child = spawn(hubBin, spawnArgs, {
525
540
  stdio: 'ignore',
526
541
  detached: true,
527
542
  env: { ...process.env, ...HOME_ENV },
528
543
  })
544
+ log(`[DEBUG:spawn] Process spawned, PID=${child.pid}`)
529
545
  child.unref()
530
546
  child.on('error', (err) => {
531
- log(`[codepocket] Spawn process error: ${err.message}`)
547
+ log(`[DEBUG:spawn] Process error: ${err.message}`)
532
548
  })
549
+ child.on('exit', (code, signal) => {
550
+ log(`[DEBUG:spawn] Process exited: code=${code}, signal=${signal}, PID=${child.pid}`)
551
+ })
552
+
553
+ // Refresh JWT before polling
554
+ log(`[DEBUG:spawn] Refreshing JWT...`)
555
+ try {
556
+ const token = await findHubToken()
557
+ jwt = await authenticateHub(token)
558
+ log(`[DEBUG:spawn] JWT refreshed OK`)
559
+ } catch (err) {
560
+ log(`[DEBUG:spawn] JWT refresh failed: ${err.message}`)
561
+ }
533
562
 
534
563
  // Wait for session to be created by polling /sessions
564
+ const spawnTime = Date.now()
535
565
  let sessionId = null
566
+ let sessionActive = false
536
567
  for (let i = 0; i < 30; i++) {
537
568
  await new Promise(r => setTimeout(r, 1000))
538
569
  try {
539
- const res = await fetch(`${hubUrl}/api/sessions`, {
570
+ let res = await fetch(`${hubUrl}/api/sessions`, {
540
571
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
541
572
  })
573
+ // Refresh JWT on 401
574
+ if (res.status === 401) {
575
+ log(`[DEBUG:spawn] Poll #${i + 1}: got 401, refreshing JWT...`)
576
+ try {
577
+ const token = await findHubToken()
578
+ jwt = await authenticateHub(token)
579
+ res = await fetch(`${hubUrl}/api/sessions`, {
580
+ headers: { Authorization: `Bearer ${jwt}` },
581
+ })
582
+ } catch (err) {
583
+ log(`[DEBUG:spawn] JWT refresh on 401 failed: ${err.message}`)
584
+ }
585
+ }
542
586
  const data = await res.json()
543
587
  const sessions = data.sessions || (Array.isArray(data) ? data : [])
588
+ log(`[DEBUG:spawn] Poll #${i + 1}: ${sessions.length} sessions, status=${res.status}`)
589
+
590
+ // Match by path AND updated after spawn (avoid stale sessions)
544
591
  const match = sessions.find(s =>
545
592
  s.metadata?.path === directory && s.id
593
+ && (!s.updatedAt || s.updatedAt * 1000 >= spawnTime - 5000)
546
594
  )
547
595
  if (match) {
548
596
  sessionId = match.id
549
- break
597
+ sessionActive = !!match.active
598
+ log(`[DEBUG:spawn] Poll #${i + 1}: FOUND session=${sessionId}, active=${sessionActive}`)
599
+ if (sessionActive) break // found and active, done
600
+ // Session exists but not yet active — keep polling
550
601
  }
551
- } catch {}
602
+ } catch (err) {
603
+ log(`[DEBUG:spawn] Poll #${i + 1}: fetch error: ${err.message}`)
604
+ }
552
605
  }
553
606
 
554
607
  if (sessionId) {
555
- log(`[codepocket] Session created: ${sessionId}`)
608
+ log(`[DEBUG:spawn] RESULT: sessionId=${sessionId}, active=${sessionActive}`)
556
609
  } else {
557
- log(`[codepocket] Session not found after polling, directory=${directory}`)
610
+ log(`[DEBUG:spawn] RESULT: session NOT FOUND after 30 polls, directory=${directory}`)
558
611
  }
559
612
  sendSpawnResult(requestId, sessionId)
560
613
  } catch (err) {
561
- console.error(`[codepocket] Spawn failed: ${err.message}`)
614
+ log(`[DEBUG:spawn] EXCEPTION: ${err.message}`)
562
615
  sendSpawnResult(requestId, null, err.message)
563
616
  }
564
617
  }
565
618
 
566
619
  async function handleResumeSession(requestId, sessionId) {
620
+ log(`[DEBUG:resume] === START resume-session ===`)
621
+ log(`[DEBUG:resume] requestId=${requestId}, sessionId=${sessionId}`)
622
+ log(`[DEBUG:resume] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
623
+
567
624
  if (!hubBin) {
625
+ log(`[DEBUG:resume] FAIL: hubBin is null`)
568
626
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Hub binary not found' })
569
627
  return
570
628
  }
571
629
  if (!sessionId) {
630
+ log(`[DEBUG:resume] FAIL: sessionId is empty`)
572
631
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session ID is required' })
573
632
  return
574
633
  }
575
634
 
576
- log(`[codepocket] Resuming session: ${sessionId}`)
577
-
578
635
  try {
579
636
  // 1. Fetch session metadata from Hub
637
+ log(`[DEBUG:resume] Fetching session metadata...`)
580
638
  let res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
581
639
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
582
640
  })
641
+ log(`[DEBUG:resume] Metadata fetch status=${res.status}`)
583
642
  if (res.status === 401) {
643
+ log(`[DEBUG:resume] Got 401, refreshing JWT...`)
584
644
  const token = await findHubToken()
585
645
  jwt = await authenticateHub(token)
586
646
  res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
587
647
  headers: { Authorization: `Bearer ${jwt}` },
588
648
  })
649
+ log(`[DEBUG:resume] Retry status=${res.status}`)
589
650
  }
590
651
  if (!res.ok) {
652
+ log(`[DEBUG:resume] FAIL: metadata fetch returned ${res.status}`)
591
653
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: `Session not found (${res.status})` })
592
654
  return
593
655
  }
@@ -596,7 +658,11 @@ async function handleResumeSession(requestId, sessionId) {
596
658
  const directory = (session.metadata?.path || '').replace(/^~/, os.homedir())
597
659
  let claudeSessionId = session.metadata?.agentSessionId || session.metadata?.claudeSessionId
598
660
 
661
+ log(`[DEBUG:resume] Session metadata: directory=${directory}, claudeSessionId=${claudeSessionId || 'NOT SET'}`)
662
+ log(`[DEBUG:resume] Full metadata: ${JSON.stringify(session.metadata || {})}`)
663
+
599
664
  if (!directory) {
665
+ log(`[DEBUG:resume] FAIL: no directory in metadata`)
600
666
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session has no working directory' })
601
667
  return
602
668
  }
@@ -605,23 +671,28 @@ async function handleResumeSession(requestId, sessionId) {
605
671
  if (!claudeSessionId) {
606
672
  claudeSessionId = findClaudeSessionFile(directory)
607
673
  if (claudeSessionId) {
608
- log(`[codepocket] claudeSessionId not in metadata, found session file: ${claudeSessionId}`)
674
+ log(`[DEBUG:resume] claudeSessionId resolved from file scan: ${claudeSessionId}`)
609
675
  } else {
610
- log(`[codepocket] claudeSessionId not in metadata and no session file found, using Hub session ID as fallback`)
676
+ log(`[DEBUG:resume] No session file found, using Hub session ID as fallback`)
611
677
  claudeSessionId = sessionId
612
678
  }
613
679
  }
614
680
 
615
681
  // 2. Spawn with --resume
616
- log(`[codepocket] Spawning resume: --path ${directory} --resume ${claudeSessionId}`)
617
- const child = spawn(hubBin, ['--path', directory, '--resume', claudeSessionId], {
682
+ const spawnArgs = ['--path', directory, '--resume', claudeSessionId]
683
+ log(`[DEBUG:resume] Spawning: ${hubBin} ${spawnArgs.join(' ')}`)
684
+ const child = spawn(hubBin, spawnArgs, {
618
685
  stdio: 'ignore',
619
686
  detached: true,
620
687
  env: { ...process.env, ...HOME_ENV },
621
688
  })
689
+ log(`[DEBUG:resume] Process spawned, PID=${child.pid}`)
622
690
  child.unref()
623
691
  child.on('error', (err) => {
624
- log(`[codepocket] Resume spawn process error: ${err.message}`)
692
+ log(`[DEBUG:resume] Process error: ${err.message}`)
693
+ })
694
+ child.on('exit', (code, signal) => {
695
+ log(`[DEBUG:resume] Process exited: code=${code}, signal=${signal}, PID=${child.pid}`)
625
696
  })
626
697
 
627
698
  // 3. Poll for session to become active
@@ -635,15 +706,21 @@ async function handleResumeSession(requestId, sessionId) {
635
706
  })
636
707
  const pollData = await pollRes.json()
637
708
  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
+ }
638
712
  const match = sessions.find(s =>
639
713
  s.metadata?.path === directory && s.active && s.id !== sessionId
640
714
  )
641
715
  if (match) {
642
716
  newSession = match
643
717
  resumed = true
718
+ log(`[DEBUG:resume] Poll #${i + 1}: FOUND active session=${match.id}`)
644
719
  break
645
720
  }
646
- } catch {}
721
+ } catch (err) {
722
+ log(`[DEBUG:resume] Poll #${i + 1}: fetch error: ${err.message}`)
723
+ }
647
724
  }
648
725
 
649
726
  if (resumed) {
@@ -653,17 +730,18 @@ async function handleResumeSession(requestId, sessionId) {
653
730
  method: 'DELETE',
654
731
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
655
732
  })
656
- log(`[codepocket] Deleted old session: ${sessionId}`)
733
+ log(`[DEBUG:resume] Deleted old session: ${sessionId}`)
657
734
  } catch (e) {
658
- log(`[codepocket] Failed to delete old session: ${e.message}`)
735
+ log(`[DEBUG:resume] Failed to delete old session: ${e.message}`)
659
736
  }
660
- log(`[codepocket] Session resumed: ${newSession.id} (replaced ${sessionId})`)
737
+ log(`[DEBUG:resume] RESULT: resumed=${newSession.id} (replaced ${sessionId})`)
661
738
  sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: newSession.id })
662
739
  } else {
740
+ log(`[DEBUG:resume] RESULT: no active session found after 30 polls`)
663
741
  sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: null, warning: 'Session resuming' })
664
742
  }
665
743
  } catch (err) {
666
- console.error(`[codepocket] Resume failed: ${err.message}`)
744
+ log(`[DEBUG:resume] EXCEPTION: ${err.message}`)
667
745
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: err.message })
668
746
  }
669
747
  }
@@ -685,22 +763,31 @@ function handleListDir(requestId, dirPath) {
685
763
  // ── Background connect: auth + MCP + SSE + relay ──
686
764
 
687
765
  async function connectInBackground() {
766
+ log(`[DEBUG:bg] connectInBackground called, relayUrl=${relayUrl || 'EMPTY'}`)
688
767
  if (!relayUrl) {
768
+ log(`[DEBUG:bg] No relay URL configured, skipping background connect`)
689
769
  console.log('[codepocket] 未配置 Relay 地址,手机连接功能不可用')
690
770
  return
691
771
  }
692
772
  try {
693
773
  const token = await findHubToken()
694
774
  jwt = await authenticateHub(token)
695
- } catch {}
775
+ log(`[DEBUG:bg] JWT acquired OK`)
776
+ } catch (err) {
777
+ log(`[DEBUG:bg] JWT acquire failed: ${err.message}`)
778
+ }
696
779
 
697
780
  try {
698
781
  const mcpPort = await startMcpServer(sendToRelay)
699
782
  injectMcpConfig(mcpPort)
700
- } catch {}
783
+ log(`[DEBUG:bg] MCP server started on port ${mcpPort}`)
784
+ } catch (err) {
785
+ log(`[DEBUG:bg] MCP server failed: ${err.message}`)
786
+ }
701
787
 
702
788
  startSSE()
703
789
  connectRelay()
790
+ log(`[DEBUG:bg] Background connect complete`)
704
791
  }
705
792
 
706
793
  // ── Main ──
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tina_summer/codepocket",
3
- "version": "2.2.4",
3
+ "version": "2.2.6",
4
4
  "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",