@hienlh/ppm 0.9.72 → 0.9.73

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 (28) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/dist/web/assets/{chat-tab-BIXfzq-R.js → chat-tab-ByDDO6Pl.js} +2 -2
  3. package/dist/web/assets/{code-editor-DiFWfbbf.js → code-editor-D8VveTUt.js} +1 -1
  4. package/dist/web/assets/{database-viewer-BXHyTgAk.js → database-viewer-CcTlsR2D.js} +1 -1
  5. package/dist/web/assets/{diff-viewer-qdcj9_Bg.js → diff-viewer-CXU5BvCX.js} +1 -1
  6. package/dist/web/assets/{extension-webview-CYyNGX7Q.js → extension-webview-Dzkyl-2t.js} +1 -1
  7. package/dist/web/assets/{git-graph-BaRxrAyx.js → git-graph-Ce8pbmQX.js} +1 -1
  8. package/dist/web/assets/{index-DmuOwe2C.js → index-Y-Kfye7A.js} +3 -3
  9. package/dist/web/assets/keybindings-store-DoRbfX4Q.js +1 -0
  10. package/dist/web/assets/{markdown-renderer-BP1o2VVM.js → markdown-renderer-BinWj98E.js} +1 -1
  11. package/dist/web/assets/{port-forwarding-tab-DTCNdTnl.js → port-forwarding-tab-D15vANLc.js} +1 -1
  12. package/dist/web/assets/{postgres-viewer-Cj7U16lk.js → postgres-viewer-Nlg7DV9i.js} +1 -1
  13. package/dist/web/assets/{settings-tab-C_VMlB_J.js → settings-tab-BY9LX5Du.js} +1 -1
  14. package/dist/web/assets/{sql-query-editor-CqVt5FDX.js → sql-query-editor-njmHoOsX.js} +1 -1
  15. package/dist/web/assets/{sqlite-viewer-BuzTVRKG.js → sqlite-viewer-jSYguEYD.js} +1 -1
  16. package/dist/web/assets/{terminal-tab-BqFOxgtv.js → terminal-tab-DUz3dmkj.js} +1 -1
  17. package/dist/web/assets/{use-monaco-theme-COffNaVJ.js → use-monaco-theme-Dl6w9X-L.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/message-list.tsx +5 -0
  27. package/src/web/hooks/use-chat.ts +7 -0
  28. 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 }
@@ -618,6 +618,11 @@ function InterleavedEvents({ events, isStreaming, projectName }: { events: ChatE
618
618
  groups.push({ kind: "thinking", content: thinkingBuffer });
619
619
  thinkingBuffer = "";
620
620
  }
621
+ if (event.type === "status_update") {
622
+ if (textBuffer) { groups.push({ kind: "text", content: textBuffer }); textBuffer = ""; }
623
+ groups.push({ kind: "text", content: `\n\n> ⟳ ${event.message}\n\n` });
624
+ continue;
625
+ }
621
626
  if (event.type === "account_retry") {
622
627
  if (textBuffer) { groups.push({ kind: "text", content: textBuffer }); textBuffer = ""; }
623
628
  const label = (event as any).accountLabel ?? "another account";
@@ -185,6 +185,13 @@ export function useChat(sessionId: string | null, providerId = "claude", project
185
185
  break;
186
186
  }
187
187
 
188
+ case "status_update": {
189
+ // Surface status as a transient event in the stream
190
+ streamingEventsRef.current.push(ev as ChatEvent);
191
+ syncMessages();
192
+ break;
193
+ }
194
+
188
195
  case "text": {
189
196
  const pid = ev.parentToolUseId as string | undefined;
190
197
  if (pid && routeToParent(ev as ChatEvent, pid)) {
@@ -1 +0,0 @@
1
- import"./react-nm2Ru1Pt.js";import"./api-client-BfBM3I7n.js";import{G as e}from"./index-DmuOwe2C.js";export{e as useKeybindingsStore};