@hienlh/ppm 0.25.4 → 0.25.5

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,12 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.25.5] - 2026-11-14
4
+
5
+ ### Fixed
6
+
7
+ - **A background agent resumed with SendMessage is no longer killed** when the chat's sign-in token is renewed: PPM tracks background work by task, so the chat is woken when the agent finishes instead of going silent.
8
+ - **Token renewal waits** while a chat's CLI has reported background activity in the last 3 minutes.
9
+
3
10
  ## [0.25.4] - 2026-11-14
4
11
 
5
12
  ### Changed
@@ -83,4 +83,4 @@ This skill covers the `ppm` CLI, its HTTP API, and its config DB. It does **not*
83
83
  - Third-party extensions (inspect via `ppm ext list`).
84
84
  - The Claude Agent SDK internals (separate skill).
85
85
 
86
- <!-- Generated for PPM v0.25.4 at build time. Re-run `ppm export skill --install` to refresh. -->
86
+ <!-- Generated for PPM v0.25.5 at build time. Re-run `ppm export skill --install` to refresh. -->
@@ -842,4 +842,4 @@ Authenticate with `?token=<token>` (see Authentication).
842
842
  - `/ws/android`
843
843
  - `/ws/project/<project>/<type>/<id>` — `<type>`: `terminal`, `chat`, `group`, `lsp` (for `chat`, `<id>` is the session id)
844
844
 
845
- <!-- Generated from src/server/routes/ for PPM v0.25.4 -->
845
+ <!-- Generated from src/server/routes/ for PPM v0.25.5 -->
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hienlh/ppm",
3
- "version": "0.25.4",
3
+ "version": "0.25.5",
4
4
  "description": "Personal Project Manager — mobile-first web IDE with AI assistance",
5
5
  "author": "hienlh",
6
6
  "license": "SEE LICENSE IN LICENSE",
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Which SDK background tasks are running in a session's subprocess, keyed by the SDK's own task id.
3
+ *
4
+ * The CLI reports every task it runs past a tool call (a backgrounded Agent, a background Bash, an
5
+ * agent woken again by `SendMessage`) with `task_started`, and its end with a terminal status on
6
+ * `task_updated` / `task_notification`. Reading liveness from those, rather than from the text of
7
+ * the tool result that launched the task, is what covers an agent resumed by `SendMessage`: its
8
+ * result says "Resuming agent …", not the launch acknowledgement, and the task id is one that
9
+ * already ended once. Missing it let the token rotation close the CLI under a reviewer still at
10
+ * work, which killed the reviewer and left the chat waiting for a notification that never came.
11
+ *
12
+ * Kept free of the chat layer so the bookkeeping can be tested on its own; `chat.ts` owns the
13
+ * state on each session entry.
14
+ */
15
+
16
+ /** Statuses after which a task is no longer running. */
17
+ const TERMINAL_TASK_STATUSES = new Set(["completed", "failed", "stopped", "killed"]);
18
+
19
+ /**
20
+ * How long after the subprocess last showed signs of background work (a subagent's own events, a
21
+ * task progress tick) the token rotation still leaves it alone. A safety net under the task
22
+ * tracking, for work the CLI runs without reporting a task: closing the subprocess kills that
23
+ * work silently, while waiting costs nothing, since an early renewal has two hours of slack.
24
+ */
25
+ export const BACKGROUND_EVENT_QUIET_MS = 3 * 60_000;
26
+
27
+ export interface BackgroundTaskState {
28
+ /** SDK task ids that have started and not yet reported a terminal status. */
29
+ runningTaskIds?: Set<string>;
30
+ /** When the subprocess last emitted a subagent event or a task progress tick (ms epoch). */
31
+ lastBackgroundEventAt?: number;
32
+ }
33
+
34
+ export function isTerminalTaskStatus(status: string | undefined): boolean {
35
+ return !!status && TERMINAL_TASK_STATUSES.has(status);
36
+ }
37
+
38
+ /**
39
+ * Fold one `task_*` system event into the state. A `task_started` marks the task running even if
40
+ * it already ended once, which is what an agent resumed by `SendMessage` looks like; a terminal
41
+ * status on any of the three ends it. Returns whether the set of running tasks changed.
42
+ */
43
+ export function noteTaskEvent(
44
+ state: BackgroundTaskState,
45
+ subtype: string,
46
+ taskId: string | undefined,
47
+ status: string | undefined,
48
+ ): boolean {
49
+ if (!taskId) return false;
50
+ if (isTerminalTaskStatus(status)) return state.runningTaskIds?.delete(taskId) ?? false;
51
+ if (subtype !== "task_started") return false;
52
+ const running = (state.runningTaskIds ??= new Set());
53
+ if (running.has(taskId)) return false;
54
+ running.add(taskId);
55
+ return true;
56
+ }
57
+
58
+ export function hasRunningTasks(state: BackgroundTaskState): boolean {
59
+ return (state.runningTaskIds?.size ?? 0) > 0;
60
+ }
61
+
62
+ /** Record that the subprocess just showed background activity. */
63
+ export function noteBackgroundEvent(state: BackgroundTaskState, now = Date.now()): void {
64
+ state.lastBackgroundEventAt = now;
65
+ }
66
+
67
+ /** Whether background activity was seen within the quiet window. */
68
+ export function backgroundEventRecent(
69
+ state: BackgroundTaskState,
70
+ now = Date.now(),
71
+ quietMs = BACKGROUND_EVENT_QUIET_MS,
72
+ ): boolean {
73
+ return state.lastBackgroundEventAt != null && now - state.lastBackgroundEventAt < quietMs;
74
+ }
75
+
76
+ /**
77
+ * Forget every task: the subprocess that ran them is gone, so nothing it started is still
78
+ * running. Without this, a task whose end was never reported would keep the session busy forever.
79
+ */
80
+ export function clearBackgroundTasks(state: BackgroundTaskState): void {
81
+ state.runningTaskIds?.clear();
82
+ state.lastBackgroundEventAt = undefined;
83
+ }
@@ -35,6 +35,13 @@ export interface LiveSubprocess {
35
35
  credential: SubprocessCredential;
36
36
  /** A turn, an approval or background work is running in it — dropping it would lose work. */
37
37
  busy: boolean;
38
+ /**
39
+ * Not busy, but showed background activity a moment ago: renewing now would revoke the token
40
+ * work it runs without reporting may still need, so the early renewal waits. Unlike `busy` it
41
+ * never keeps a subprocess on a token already replaced — that token is revoked, and whatever
42
+ * still runs on it fails at its next request either way.
43
+ */
44
+ holdRenewal?: boolean;
38
45
  }
39
46
 
40
47
  export interface RenewalCandidate {
@@ -44,7 +51,7 @@ export interface RenewalCandidate {
44
51
  renewable: boolean;
45
52
  }
46
53
 
47
- /** Accounts to renew now: in use by some subprocess, near expiry, and busy in none. */
54
+ /** Accounts to renew now: in use by some subprocess, near expiry, and busy or holding in none. */
48
55
  export function accountsToRenewNow(candidates: RenewalCandidate[], live: LiveSubprocess[], nowS: number): string[] {
49
56
  const inUse = new Set<string>();
50
57
  const busy = new Set<string>();
@@ -52,7 +59,7 @@ export function accountsToRenewNow(candidates: RenewalCandidate[], live: LiveSub
52
59
  const id = p.credential.accountId;
53
60
  if (!id || !p.credential.oauthToken) continue;
54
61
  inUse.add(id);
55
- if (p.busy) busy.add(id);
62
+ if (p.busy || p.holdRenewal) busy.add(id);
56
63
  }
57
64
  return candidates
58
65
  .filter((c) => {
@@ -26,6 +26,14 @@ import { configService } from "../../services/config.service.ts";
26
26
  import { prefixTokens } from "../../shared/turn-usage.ts";
27
27
  import type { PromptCacheState } from "../../shared/prompt-cache-idle.ts";
28
28
  import { isAsyncAgentLaunchAck, isTerminalAgentStatus } from "../../shared/background-agent-status.ts";
29
+ import {
30
+ backgroundEventRecent,
31
+ clearBackgroundTasks,
32
+ hasRunningTasks,
33
+ noteBackgroundEvent,
34
+ noteTaskEvent,
35
+ type BackgroundTaskState,
36
+ } from "./chat-background-tasks.ts";
29
37
  import { cacheReleaseDelayMs, selectWarmIdleEvictions } from "../../services/subprocess-retention.ts";
30
38
  import { needsAuthServerNames } from "../../services/mcp-oauth/mcp-oauth-redirect.ts";
31
39
  import { mcpStatusEvent, registerMcpSignInSync } from "./chat-mcp-sign-in-sync.ts";
@@ -299,7 +307,7 @@ export function chatSocketData(sessionId: string, projectName: string, query: UR
299
307
  };
300
308
  }
301
309
 
302
- export interface SessionEntry {
310
+ export interface SessionEntry extends BackgroundTaskState {
303
311
  providerId: string;
304
312
  clients: Set<ChatWsSocket>;
305
313
  projectPath?: string;
@@ -633,9 +641,16 @@ export function dropIdleSubprocess(sessionId: string, reason: string, note: stri
633
641
  log.info(`session=${sessionId} released subprocess (${reason}): ${note}`);
634
642
  }
635
643
 
636
- /** Whether a background agent or shell the session started is still running in its subprocess. */
644
+ /**
645
+ * Whether a background agent or shell the session started is still running in its subprocess.
646
+ * The SDK's own task lifecycle is the primary signal (`chat-background-tasks.ts`): it is the only
647
+ * one that sees an agent resumed by `SendMessage`. The launch-ack set and the shell registry stay
648
+ * as well, since each was the only signal for its kind of work before.
649
+ */
637
650
  export function hasBackgroundWork(sessionId: string): boolean {
638
- if ((activeSessions.get(sessionId)?.backgroundToolUseIds?.size ?? 0) > 0) return true;
651
+ const entry = activeSessions.get(sessionId);
652
+ if (entry && hasRunningTasks(entry)) return true;
653
+ if ((entry?.backgroundToolUseIds?.size ?? 0) > 0) return true;
639
654
  return backgroundShellRegistry.list(sessionId).some((sh) => sh.status !== "stopped");
640
655
  }
641
656
 
@@ -791,7 +806,10 @@ const tokenRotationDeps: TokenRotationDeps = {
791
806
  // `idle` with `isStreamingActive` still set. A subprocess with no entry here belongs to
792
807
  // something else (a scheduled run) and is never ours to judge idle.
793
808
  const busy = !entry || entry.phase !== "idle" || !!entry.pendingApprovalEvent || hasBackgroundWork(sessionId);
794
- return { sessionId, credential, busy };
809
+ // A renewal revokes the token and can wait, so it also holds off while the CLI is still
810
+ // emitting background events: the safety net for work it runs without reporting a task.
811
+ const holdRenewal = !!entry && !busy && backgroundEventRecent(entry);
812
+ return { sessionId, credential, busy, holdRenewal };
795
813
  });
796
814
  },
797
815
  dropIdle: (sessionId) => dropIdleSubprocess(
@@ -1563,6 +1581,7 @@ async function startSessionConsumer(sessionId: string, providerId: string, conte
1563
1581
  // Child streams can outlive the root turn. Their content and terminal
1564
1582
  // events belong to the Agent card, never to the root turn's lifecycle.
1565
1583
  if (ev.parentToolUseId) {
1584
+ noteBackgroundEvent(entry);
1566
1585
  emitNestedChild(sessionId, event);
1567
1586
  continue;
1568
1587
  }
@@ -1605,12 +1624,21 @@ async function startSessionConsumer(sessionId: string, providerId: string, conte
1605
1624
  entry.compactStatus = null;
1606
1625
  log.debug(`session=${sessionId} compact_status=done (via compact_boundary)`);
1607
1626
  broadcast(sessionId, { type: "compact_status", status: "done" });
1627
+ } else if (sub === "task_progress") {
1628
+ // One per step of a running task, still arriving after the turn that started it ended.
1629
+ // Not a timer: a task blocked on one long command sends none, which the task tracking covers.
1630
+ noteBackgroundEvent(entry);
1608
1631
  } else if (sub === "task_started" || sub === "task_updated" || sub === "task_notification") {
1609
1632
  // Background command (local_bash) lifecycle. shellId === SDK task_id.
1610
1633
  const taskId = (ev as any).taskId as string | undefined;
1611
1634
  const taskStatus = (ev as any).taskStatus as string | undefined;
1612
1635
  const taskToolUseId = (ev as any).taskToolUseId as string | undefined;
1613
1636
  const outputFile = (ev as any).outputFile as string | undefined;
1637
+ // What the subprocess counts as running. An agent woken again by SendMessage appears
1638
+ // only here: its tool result is not the launch ack, and its task id already ended once.
1639
+ if (noteTaskEvent(entry, sub, taskId, taskStatus)) {
1640
+ bgShellLog.info(`session=${sessionId} task ${taskId} ${entry.runningTaskIds?.has(taskId!) ? "running" : `ended (${taskStatus})`} tasksRunning=${entry.runningTaskIds?.size ?? 0}`);
1641
+ }
1614
1642
  // A backgrounded Agent reports its outcome only here — its tool_result was a
1615
1643
  // launch ack the card must not read as "finished". Forward the terminal state so
1616
1644
  // the card can settle. Harmless for background bash tasks: no card matches them.
@@ -2054,6 +2082,10 @@ async function startSessionConsumer(sessionId: string, providerId: string, conte
2054
2082
  bashOutputSpy.stopAllForSession(sessionId);
2055
2083
  // SDK subprocess teardown kills its background children — reflect as stopped
2056
2084
  backgroundShellRegistry.markAllStopped(sessionId);
2085
+ // and forget the tasks and launches it was running, or one whose end never arrived would keep
2086
+ // the session busy (never released, never moved onto a renewed token) for good.
2087
+ clearBackgroundTasks(entry);
2088
+ entry.backgroundToolUseIds?.clear();
2057
2089
  broadcastBackgroundRegistry(sessionId);
2058
2090
  // Cleanup team watchers
2059
2091
  for (const w of entry.teamWatchers.values()) w.cleanup();
@@ -15,4 +15,4 @@
15
15
  - **Restart semantics are the old ones, on purpose**: commands used to live in `ppm.service` and die with it (`KillMode=mixed`); now they live outside it. So `gracefulShutdown` stops every `ppmcmd-*` scope and the startup pass stops those left by a server that died without one; units the agent made itself survive a restart, as they always did. The startup pass ignores "busy": it runs in the same tick routing is switched on, so nothing in a slice can be this server's yet.
16
16
  - **`systemctl stop a b c` stops none of them when any one is gone**: systemd 262 answers "Failed to enqueue jobs: Unit … not loaded." (exit 5) whatever the order, and a command scope ending between the cgroupfs listing and the stop is ordinary. So `stopUnits` and `stopCommandScopesSync` stop everything in one call and, when that fails, one unit at a time, taking exit 5 as "gone already". The shutdown test raced on exactly this — `agentUnit()`'s own `systemd-run` scope is still being torn down — and was red or green per run; the two "…gone already" tests make it deterministic with a `ppmcmd-*.scope` directory made in cgroupfs that systemd has no unit for.
17
17
  - **A fork's first CLI is untracked**: it resumes the source session under an id the CLI picks itself, so `chatSessionIdOf` returns nothing rather than filing its processes under the session it was forked from.
18
- - **A running background Bash task keeps its session busy**: `hasBackgroundWork` counts `run_in_background` shells, so a dev server started that way holds back the sweep of everything else the session left until the shell stops or the session entry is cleaned up. It is attached to the live CLI anyway, so the sweep would not stop it itself.
18
+ - **A running background task keeps its session busy**: `hasBackgroundWork` counts every task the CLI reports as started and not yet ended (`chat-background-tasks.ts`): `run_in_background` shells, backgrounded agents, an agent resumed by `SendMessage`, and shells a subagent started or the CLI moved to the background after its timeout. So a dev server started that way holds back the sweep of everything else the session left until the shell stops or the session entry is cleaned up. It is attached to the live CLI anyway, so the sweep would not stop it itself.