@hienlh/ppm 0.9.72 → 0.9.74

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 (30) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/web/assets/chat-tab-Balv7WLR.js +10 -0
  3. package/dist/web/assets/{code-editor-DiFWfbbf.js → code-editor--iQ3p6pv.js} +1 -1
  4. package/dist/web/assets/{database-viewer-BXHyTgAk.js → database-viewer-j_rE2HtW.js} +1 -1
  5. package/dist/web/assets/{diff-viewer-qdcj9_Bg.js → diff-viewer-BsNNXZOH.js} +1 -1
  6. package/dist/web/assets/{extension-webview-CYyNGX7Q.js → extension-webview-DBFlb9vJ.js} +1 -1
  7. package/dist/web/assets/{git-graph-BaRxrAyx.js → git-graph-4T0UY_11.js} +1 -1
  8. package/dist/web/assets/{index-DmuOwe2C.js → index-BEWc9Jna.js} +3 -3
  9. package/dist/web/assets/keybindings-store-jU8-zEoI.js +1 -0
  10. package/dist/web/assets/{markdown-renderer-BP1o2VVM.js → markdown-renderer-DoHfaBus.js} +1 -1
  11. package/dist/web/assets/{port-forwarding-tab-DTCNdTnl.js → port-forwarding-tab-zP7tA3ms.js} +1 -1
  12. package/dist/web/assets/{postgres-viewer-Cj7U16lk.js → postgres-viewer-h6eod6pQ.js} +1 -1
  13. package/dist/web/assets/{settings-tab-C_VMlB_J.js → settings-tab-c_CRbliY.js} +1 -1
  14. package/dist/web/assets/{sql-query-editor-CqVt5FDX.js → sql-query-editor-DhuulOCp.js} +1 -1
  15. package/dist/web/assets/{sqlite-viewer-BuzTVRKG.js → sqlite-viewer-FTb_sKqq.js} +1 -1
  16. package/dist/web/assets/{terminal-tab-BqFOxgtv.js → terminal-tab--DxApS1a.js} +1 -1
  17. package/dist/web/assets/{use-monaco-theme-COffNaVJ.js → use-monaco-theme-CHzQ7wm2.js} +1 -1
  18. package/dist/web/index.html +1 -1
  19. package/dist/web/sw.js +1 -1
  20. package/docs/project-changelog.md +22 -1
  21. package/docs/system-architecture.md +1 -1
  22. package/package.json +1 -1
  23. package/src/providers/claude-agent-sdk.ts +59 -22
  24. package/src/services/account-selector.service.ts +25 -7
  25. package/src/types/chat.ts +1 -0
  26. package/src/web/components/chat/chat-tab.tsx +2 -0
  27. package/src/web/components/chat/message-list.tsx +9 -4
  28. package/src/web/hooks/use-chat.ts +11 -0
  29. package/dist/web/assets/chat-tab-BIXfzq-R.js +0 -10
  30. package/dist/web/assets/keybindings-store-DUcpLoKq.js +0 -1
@@ -18,7 +18,7 @@ import { mcpConfigService } from "../services/mcp-config.service.ts";
18
18
  import { updateFromSdkEvent } from "../services/claude-usage.service.ts";
19
19
  import { getSessionMapping, getSessionProjectPath, setSessionMapping, getSessionTitles } from "../services/db.service.ts";
20
20
  import { accountSelector } from "../services/account-selector.service.ts";
21
- import { accountService } from "../services/account.service.ts";
21
+ import { accountService, type AccountWithTokens } from "../services/account.service.ts";
22
22
  import { resolve } from "node:path";
23
23
  import { existsSync, readdirSync, unlinkSync } from "node:fs";
24
24
  import { homedir } from "node:os";
@@ -657,28 +657,65 @@ export class ClaudeAgentSdkProvider implements AIProvider {
657
657
  // Account-based auth injection (multi-account mode)
658
658
  // Fallback to existing env (ANTHROPIC_API_KEY) when no accounts configured.
659
659
  const accountsEnabled = accountSelector.isEnabled();
660
- let account = accountsEnabled ? accountSelector.next() : null;
661
- if (accountsEnabled && !account) {
662
- // All accounts in DB but none usable
663
- const reason = accountSelector.lastFailReason;
664
- const hint = reason === "all_decrypt_failed"
665
- ? "Account tokens were encrypted with a different machine key. Re-add your accounts in Settings, or copy ~/.ppm/account.key from the original machine."
666
- : "All accounts are disabled or in cooldown. Check Settings → Accounts.";
667
- console.error(`[sdk] session=${sessionId} account auth failed (${reason}): ${hint}`);
668
- yield { type: "error" as const, message: `Authentication failed: ${hint}` };
669
- yield { type: "done" as const, sessionId, resultSubtype: "error_auth" };
670
- return;
671
- }
672
- // Pre-flight: ensure OAuth token is fresh before sending to SDK
673
- if (account) {
674
- const nowS = Math.floor(Date.now() / 1000);
675
- const expiresIn = account.expiresAt ? account.expiresAt - nowS : null;
676
- console.log(`[sdk] Using account ${account.id} (${account.email ?? "no-email"}) token_expires_in=${expiresIn}s`);
677
- const fresh = await accountService.ensureFreshToken(account.id);
678
- if (fresh) {
679
- account = fresh;
660
+ let account: AccountWithTokens | null = null;
661
+
662
+ if (accountsEnabled) {
663
+ const excludeIds = new Set<string>();
664
+
665
+ // Pre-flight loop: select account refresh token retry with next if refresh fails
666
+ while (true) {
667
+ yield { type: "status_update" as const, phase: "routing" as const, message: "Selecting account..." };
668
+ account = accountSelector.next(excludeIds);
669
+
670
+ if (!account) {
671
+ const reason = accountSelector.lastFailReason;
672
+ let hint: string;
673
+ if (reason === "all_decrypt_failed") {
674
+ hint = "Account tokens were encrypted with a different machine key. Re-add your accounts in Settings, or copy ~/.ppm/account.key from the original machine.";
675
+ } else if (reason === "all_excluded") {
676
+ hint = "All accounts failed token refresh. Check Settings → Accounts.";
677
+ } else {
678
+ hint = "All accounts are disabled or in cooldown. Check Settings → Accounts.";
679
+ }
680
+ console.error(`[sdk] session=${sessionId} account auth failed (${reason}): ${hint}`);
681
+ yield { type: "error" as const, message: `Authentication failed: ${hint}` };
682
+ yield { type: "done" as const, sessionId, resultSubtype: "error_auth" };
683
+ return;
684
+ }
685
+
686
+ const accountLabel = account.label ?? account.email ?? "Unknown";
687
+ const nowS = Math.floor(Date.now() / 1000);
688
+ const expiresIn = account.expiresAt ? account.expiresAt - nowS : null;
689
+ console.log(`[sdk] Using account ${account.id} (${account.email ?? "no-email"}) token_expires_in=${expiresIn}s`);
690
+
691
+ // Check if token needs refresh
692
+ const isOAuth = account.accessToken.startsWith("sk-ant-oat");
693
+ const needsRefresh = isOAuth && account.expiresAt && (account.expiresAt - nowS <= 3600);
694
+
695
+ if (!needsRefresh) {
696
+ // Token fresh or API key — proceed
697
+ yield { type: "account_info" as const, accountId: account.id, accountLabel };
698
+ break;
699
+ }
700
+
701
+ // Token expiring — attempt refresh
702
+ yield { type: "status_update" as const, phase: "refreshing" as const, message: `Refreshing token for ${accountLabel}...`, accountLabel };
703
+ const fresh = await accountService.ensureFreshToken(account.id);
704
+
705
+ if (fresh) {
706
+ account = fresh;
707
+ const freshLabel = account.label ?? account.email ?? "Unknown";
708
+ yield { type: "account_info" as const, accountId: account.id, accountLabel: freshLabel };
709
+ break;
710
+ }
711
+
712
+ // Refresh failed — cooldown this account, try next
713
+ console.warn(`[sdk] session=${sessionId} pre-flight refresh failed for ${account.id} — trying next account`);
714
+ yield { type: "status_update" as const, phase: "switching" as const, message: `Token expired for ${accountLabel}, trying next account...`, accountLabel };
715
+ accountSelector.onPreflightFail(account.id);
716
+ excludeIds.add(account.id);
717
+ // continue loop → pick next account
680
718
  }
681
- yield { type: "account_info" as const, accountId: account.id, accountLabel: account.label ?? account.email ?? "Unknown" };
682
719
  }
683
720
  const queryEnv = this.buildQueryEnv(meta.projectPath, account);
684
721
 
@@ -40,10 +40,10 @@ class AccountSelectorService {
40
40
  }
41
41
 
42
42
  /** Reason for the last null return from next() */
43
- private _lastFailReason: "none" | "no_active" | "all_decrypt_failed" = "none";
43
+ private _lastFailReason: "none" | "no_active" | "all_decrypt_failed" | "all_excluded" = "none";
44
44
 
45
45
  /** Why the last next() call returned null */
46
- get lastFailReason(): "none" | "no_active" | "all_decrypt_failed" {
46
+ get lastFailReason(): "none" | "no_active" | "all_decrypt_failed" | "all_excluded" {
47
47
  return this._lastFailReason;
48
48
  }
49
49
 
@@ -51,7 +51,7 @@ class AccountSelectorService {
51
51
  * Pick next available account (skips cooldown/disabled).
52
52
  * Returns null if no active accounts available.
53
53
  */
54
- next(): AccountWithTokens | null {
54
+ next(excludeIds?: Set<string>): AccountWithTokens | null {
55
55
  this._lastFailReason = "none";
56
56
  const now = Math.floor(Date.now() / 1000);
57
57
  const allAccounts = accountService.list();
@@ -71,17 +71,19 @@ class AccountSelectorService {
71
71
  }
72
72
 
73
73
  const active = accountService.list().filter((a) => a.status === "active");
74
- if (active.length === 0) {
75
- this._lastFailReason = "no_active";
74
+ // Skip accounts excluded by caller (e.g., pre-flight loop)
75
+ const notExcluded = excludeIds?.size ? active.filter((a) => !excludeIds.has(a.id)) : active;
76
+ if (notExcluded.length === 0) {
77
+ this._lastFailReason = active.length > 0 ? "all_excluded" : "no_active";
76
78
  return null;
77
79
  }
78
80
 
79
81
  // Proactive: skip accounts whose 5-hour utilization >= 95%
80
- const usable = active.filter((a) => {
82
+ const usable = notExcluded.filter((a) => {
81
83
  const snap = getLatestSnapshotForAccount(a.id);
82
84
  return !snap || (snap.five_hour_util ?? 0) < FIVE_HOUR_SKIP_THRESHOLD;
83
85
  });
84
- const candidates = usable.length > 0 ? usable : active; // fallback to all if every account is near limit
86
+ const candidates = usable.length > 0 ? usable : notExcluded; // fallback to all if every account is near limit
85
87
 
86
88
  let pickedId: string;
87
89
  const strategy = this.getStrategy();
@@ -195,6 +197,22 @@ class AccountSelectorService {
195
197
  console.log(`[accounts] ${accountId} auth error — cooldown ${Math.round(backoffMs / 1000)}s (retry #${retries})`);
196
198
  }
197
199
 
200
+ private static readonly PREFLIGHT_BACKOFF_BASE_MS = 60_000; // 1 minute
201
+ private static readonly PREFLIGHT_BACKOFF_MAX_MS = 5 * 60_000; // 5 minutes
202
+
203
+ /** Called when pre-flight token refresh fails — short cooldown.
204
+ * Shares retryCounts with onRateLimit/onAuthError (cumulative penalty by design). */
205
+ onPreflightFail(accountId: string): void {
206
+ const retries = (this.retryCounts.get(accountId) ?? 0) + 1;
207
+ this.retryCounts.set(accountId, retries);
208
+ const backoffMs = Math.min(
209
+ AccountSelectorService.PREFLIGHT_BACKOFF_BASE_MS * Math.pow(2, retries - 1),
210
+ AccountSelectorService.PREFLIGHT_BACKOFF_MAX_MS,
211
+ );
212
+ accountService.setCooldown(accountId, Date.now() + backoffMs);
213
+ console.log(`[accounts] ${accountId} preflight refresh failed — cooldown ${Math.round(backoffMs / 1000)}s (retry #${retries})`);
214
+ }
215
+
198
216
  /** Called on successful request — reset retry count + track usage */
199
217
  onSuccess(accountId: string): void {
200
218
  this.retryCounts.delete(accountId);
package/src/types/chat.ts CHANGED
@@ -120,6 +120,7 @@ export type ChatEvent =
120
120
  | { type: "session_migrated"; oldSessionId: string; newSessionId: string }
121
121
  | { type: "account_info"; accountId: string; accountLabel: string }
122
122
  | { type: "account_retry"; reason: string; accountId?: string; accountLabel?: string }
123
+ | { type: "status_update"; phase: "routing" | "refreshing" | "switching"; message: string; accountLabel?: string }
123
124
  | { type: "system"; subtype: string }
124
125
  | { type: "team_detected"; teamName: string }
125
126
  | { type: "team_updated"; teamName: string; team: unknown }
@@ -90,6 +90,7 @@ export function ChatTab({ metadata, tabId }: ChatTabProps) {
90
90
  pendingApproval,
91
91
  contextWindowPct,
92
92
  compactStatus,
93
+ statusMessage,
93
94
  sessionTitle,
94
95
  migratedSessionId,
95
96
  sendMessage,
@@ -342,6 +343,7 @@ export function ChatTab({ metadata, tabId }: ChatTabProps) {
342
343
  isStreaming={isStreaming}
343
344
  phase={phase}
344
345
  connectingElapsed={connectingElapsed}
346
+ statusMessage={statusMessage}
345
347
  projectName={projectName}
346
348
  onFork={!isStreaming ? handleFork : undefined}
347
349
  onSelectSession={handleSelectSession}
@@ -42,6 +42,7 @@ interface MessageListProps {
42
42
  isStreaming: boolean;
43
43
  phase?: SessionPhase;
44
44
  connectingElapsed?: number;
45
+ statusMessage?: string | null;
45
46
  projectName?: string;
46
47
  /** Called when user clicks Fork/Rewind — opens new forked chat tab */
47
48
  onFork?: (userMessage: string, messageId?: string) => void;
@@ -58,6 +59,7 @@ export function MessageList({
58
59
  phase,
59
60
  onSelectSession,
60
61
  connectingElapsed,
62
+ statusMessage,
61
63
  projectName,
62
64
  onFork,
63
65
  }: MessageListProps) {
@@ -114,7 +116,7 @@ export function MessageList({
114
116
  : <ApprovalCard approval={pendingApproval} onRespond={onApprovalResponse} />
115
117
  )}
116
118
 
117
- {isStreaming && <ThinkingIndicator lastMessage={messages[messages.length - 1]} phase={phase} elapsed={connectingElapsed} />}
119
+ {isStreaming && <ThinkingIndicator lastMessage={messages[messages.length - 1]} phase={phase} elapsed={connectingElapsed} statusMessage={statusMessage} />}
118
120
  </StickToBottom.Content>
119
121
  <ScrollToBottomButton />
120
122
  </StickToBottom>
@@ -766,10 +768,11 @@ function StreamingText({ content, animate: isStreaming, projectName }: { content
766
768
  * - After tool: "Processing..."
767
769
  * - Text streaming: hidden
768
770
  */
769
- function ThinkingIndicator({ lastMessage, phase, elapsed }: { lastMessage?: ChatMessage; phase?: SessionPhase; elapsed?: number }) {
771
+ function ThinkingIndicator({ lastMessage, phase, elapsed, statusMessage }: { lastMessage?: ChatMessage; phase?: SessionPhase; elapsed?: number; statusMessage?: string | null }) {
770
772
  // Show indicator when:
771
773
  // 1. No assistant message yet (waiting for first response)
772
774
  // 2. Last event is tool_result (Claude thinking after tool execution)
775
+ // 3. statusMessage is active (account routing/refreshing)
773
776
  // Hide when text is actively streaming (text itself is the indicator)
774
777
 
775
778
  const isWaiting = !lastMessage || lastMessage.role !== "assistant";
@@ -779,9 +782,11 @@ function ThinkingIndicator({ lastMessage, phase, elapsed }: { lastMessage?: Chat
779
782
  return last.type === "tool_result";
780
783
  })();
781
784
 
782
- if (!isWaiting && !isAfterTool) return null;
785
+ if (!statusMessage && !isWaiting && !isAfterTool) return null;
783
786
 
784
- const label = phase === "initializing" ? "Initializing"
787
+ const label = statusMessage
788
+ ? statusMessage
789
+ : phase === "initializing" ? "Initializing"
785
790
  : phase === "connecting" ? "Connecting"
786
791
  : phase === "thinking" ? "Thinking"
787
792
  : "Processing";
@@ -42,6 +42,7 @@ interface UseChatReturn {
42
42
  pendingApproval: ApprovalRequest | null;
43
43
  contextWindowPct: number | null;
44
44
  compactStatus: "compacting" | null;
45
+ statusMessage: string | null;
45
46
  sessionTitle: string | null;
46
47
  /** When CLI provider assigns a different session ID, this holds the new ID */
47
48
  migratedSessionId: string | null;
@@ -78,6 +79,7 @@ export function useChat(sessionId: string | null, providerId = "claude", project
78
79
  const [pendingApproval, setPendingApproval] = useState<ApprovalRequest | null>(null);
79
80
  const [contextWindowPct, setContextWindowPct] = useState<number | null>(null);
80
81
  const [compactStatus, setCompactStatus] = useState<"compacting" | null>(null);
82
+ const [statusMessage, setStatusMessage] = useState<string | null>(null);
81
83
  const [sessionTitle, setSessionTitle] = useState<string | null>(null);
82
84
  const [isConnected, setIsConnected] = useState(false);
83
85
  const [migratedSessionId, setMigratedSessionId] = useState<string | null>(null);
@@ -171,6 +173,7 @@ export function useChat(sessionId: string | null, providerId = "claude", project
171
173
  switch (evType) {
172
174
  case "account_info": {
173
175
  streamingAccountRef.current = { accountId: ev.accountId, accountLabel: ev.accountLabel };
176
+ setStatusMessage(null);
174
177
  break;
175
178
  }
176
179
 
@@ -185,6 +188,12 @@ export function useChat(sessionId: string | null, providerId = "claude", project
185
188
  break;
186
189
  }
187
190
 
191
+ case "status_update": {
192
+ const label = ev.accountLabel ? ` (${ev.accountLabel})` : "";
193
+ setStatusMessage(`${ev.message}${label}`);
194
+ break;
195
+ }
196
+
188
197
  case "text": {
189
198
  const pid = ev.parentToolUseId as string | undefined;
190
199
  if (pid && routeToParent(ev as ChatEvent, pid)) {
@@ -329,6 +338,7 @@ export function useChat(sessionId: string | null, providerId = "claude", project
329
338
  streamingContentRef.current = "";
330
339
  streamingEventsRef.current = [];
331
340
  streamingAccountRef.current = null;
341
+ setStatusMessage(null);
332
342
  // Phase transition to idle comes from BE via phase_changed
333
343
  break;
334
344
  }
@@ -659,6 +669,7 @@ export function useChat(sessionId: string | null, providerId = "claude", project
659
669
  pendingApproval,
660
670
  contextWindowPct,
661
671
  compactStatus,
672
+ statusMessage,
662
673
  sessionTitle,
663
674
  migratedSessionId,
664
675
  teamActivity,