Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Visual plan rail in main chat + retry / skip / abandon for failed steps + auto-recover transient network errors

claw2d4b79c44c2c5
diff --git a/CLAUDE.md b/CLAUDE.md
index cf21c937..3668fa19 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -160,11 +160,15 @@ Members = `commander` + `user` + N `agent` actors (any agent first targeted by `
- **`@<name>` written into prose by commander / agents is NOT recognized as a dispatch signal** (LLM training tends to use `@` as markdown decoration; this used to mis-trigger and produced recurring bugs).
- `dispatch_to` calls only stage; the recipient worker is woken up only after the commander turn fully wraps up (avoiding races; same `pendingPlanAnnouncement` + delayed reconcile pattern as `plan_set`).
-**Single dispatch primitive**: `bus.ts::enqueue(uid, cid, fromActorId, text, [forceTo], ...)` is the only external control-flow entry point for group_chat. `dispatch_to` / `plan_executor` / text @ (user only) / **CLI-backed agent worker turns** (their post-CLI reply still goes back through `bus.enqueue`, no shortcut) all funnel into this single enqueue. **Do not** introduce parallel enqueue functions; new dispatch paths must go through it.
+**Single dispatch primitive**: `bus.ts::enqueue(uid, cid, fromActorId, text, [forceTo], ...)` is the only external control-flow entry point for group_chat. `dispatch_to` / `plan_executor` / text @ (user only) / **CLI-backed agent worker turns** (their post-CLI reply still goes back through `bus.enqueue`, no shortcut) all funnel into this single enqueue. **Do not** introduce parallel enqueue functions; new dispatch paths must go through it. **`groupChat.retryStep / skipStep` are not exceptions** — they only mutate plan state, never enqueue directly; redispatch happens via `planExecutor.reconcileAfterStepTransition → dispatchReady → enqueue`.
+
+**Plan rail (user-facing visualization)**: `<cid>/plan.json` is rendered as a sticky-top rail above `#chat-history` (renderer `modules/plan-rail.js`). The rail is the SOLE frontend display for plan state (the legacy `📋 执行计划` bubble label is just a one-line announcement, not a view of step status). Failed steps surface 重试/跳过/放弃 buttons that route to `groupChat.retryStep / skipStep / abort` IPC. Action buttons hide whenever `state.in_flight` is non-empty to avoid racing user actions against an in-progress turn. Status icon set is FIXED in `plan-rail.js::STATUS_ICON` — single source of truth, no LLM input, no backend / locale duplicates.
+
+**Plan-level transient retry**: `PlanStep.transient_attempts` + `TRANSIENT_ERR_PATTERNS` (in `plan_executor.ts`) form a 2-tier retry stack with core-agent's `maxRetries=3` inner stream-level retry. Pattern matches undici `terminated` / `ECONNRESET` / `ETIMEDOUT` etc.; on hit, the failed step is folded back to `pending` + `transient_attempts++` + immediately redispatched via reconcile. Cap = `MAX_TRANSIENT_RETRIES` (2). **Never include `aborted` / `cancelled` in the pattern** — user-initiated abort must not be silently retried; the literal `'aborted by user'` string is also explicitly excluded by the guard. The plan layer only does state recovery — do NOT add sleep / backoff / socket-reconnect logic here (that's core-agent's job).
**Key constraints**:
- **Visibility slice** (security invariant): agent X sees only messages where `from==X ∨ to∋X ∨ mentions∋X`; workers must go through `visibility.readSlice` and **never read the full `<cid>.jsonl`** (which would leak other actors' private context).
-- **plan**: the commander writes `<cid>/plan.md` only via the `plan_set` tool; **no out-of-tool hand edits** (which would break the first-announcement semantics + UI `plan_changed` event chain).
+- **plan**: the commander writes `<cid>/plan.md` only via the `plan_set` tool; **no out-of-tool hand edits** (which would break the first-announcement semantics + UI `plan_changed` event chain). User-initiated `retryStep` / `skipStep` go through `plan_executor` (which `updateStep`s + reconciles), NOT through hand-editing `plan.json`.
- **abort**: `groupChat.abort(cid)` is the sole group-level stop (clears every actor queue + aborts in-flight + sets `state.json.status='aborted'`; plan.md is preserved as a progress record); **no per-stream stop button**.
- **Infinite-loop guard**: `MAX_WORKER_TURNS=100` (turns dimension, **not time**); paired with the outer `idleTimeout=600s`, two independent fallbacks.
- **Structured outputs**: the commander's `<agent>...</agent>` container (create/edit agent), and the agent's ```agent-input-form``` fenced block (forms); format and pipeline details are in `bus.ts::runTurn` + `prompts/chat_*.md`.
@@ -334,6 +338,10 @@ The commit message is **about the change**, not about how it got here. Sync prov
- Write `@<X>` in commander/agent prose expecting a dispatch — it's no longer recognized; the user just sees text nobody picked up.
- Build a new enqueue / scheduling function in parallel to `bus.enqueue` — single-primitive principle, every dispatch path must go through it.
- Hand-edit `<cid>/plan.md` outside the `plan.ts` tools.
+- Make `retryStep` / `skipStep` enqueue directly (must go through reconcile so the dispatch primitive stays singular).
+- Wire the rail's "重试" button to "send the user message again" — that double-writes user history; the action must go through the dedicated IPC (`groupChat.retryStep`) which only mutates plan state.
+- Add `aborted` / `cancelled` / `Run aborted` to `TRANSIENT_ERR_PATTERNS` — silently retrying user-initiated abort is the wrong behavior. Net new patterns must come from the network layer (undici / fetch / DNS / socket), not from intent layers.
+- Duplicate the plan rail status icon set (`plan-rail.js::STATUS_ICON`) into prompts / locales / backend. Single source of truth; downstream surfaces just read the rendered output.
---
diff --git a/src/main/features/group_chat/index.ts b/src/main/features/group_chat/index.ts
index 0f0b9b94..67229126 100644
--- a/src/main/features/group_chat/index.ts
+++ b/src/main/features/group_chat/index.ts
@@ -19,6 +19,7 @@ import {
USER_ID, readMembers, seedReservedActors, purgeGroupDir,
} from './state';
import { readPlan, type PlanFile } from './plan';
+import * as planExecutor from './plan_executor';
import {
abort as busAbort, dropConv as busDropConv, enqueue, subscribe, isQuiescent,
type GroupEvent,
@@ -134,6 +135,24 @@ export async function readPlanForCid(
return { ok: true, plan: plan || null };
}
+/** User-initiated retry of a failed plan step (rail "Retry" button). */
+export async function retryStep(
+ userId: string, cid: string, stepIndex: number,
+): Promise<{ ok: boolean; error?: string }> {
+ if (!safeId(cid)) return { ok: false, error: 'invalid cid' };
+ if (!Number.isFinite(stepIndex) || stepIndex < 1) return { ok: false, error: 'invalid stepIndex' };
+ return planExecutor.retryStep(userId, cid, stepIndex);
+}
+
+/** User-initiated skip of a failed plan step (rail "Skip" button). */
+export async function skipStep(
+ userId: string, cid: string, stepIndex: number,
+): Promise<{ ok: boolean; error?: string }> {
+ if (!safeId(cid)) return { ok: false, error: 'invalid cid' };
+ if (!Number.isFinite(stepIndex) || stepIndex < 1) return { ok: false, error: 'invalid stepIndex' };
+ return planExecutor.skipStep(userId, cid, stepIndex);
+}
+
// ── Streaming events ─────────────────────────────────────────────────────
export async function* streamEvents(
diff --git a/src/main/features/group_chat/plan.ts b/src/main/features/group_chat/plan.ts
index 48664522..e2489212 100644
--- a/src/main/features/group_chat/plan.ts
+++ b/src/main/features/group_chat/plan.ts
@@ -69,6 +69,11 @@ export interface PlanStep {
output_files?: string[];
output_msg_id?: string;
failure_reason?: string;
+ /** Plan-level safety net: count of times the executor folded a transient
+ * failure (undici `terminated`, ECONNRESET, etc.) back to `pending` for
+ * an automatic redispatch. Cap = `MAX_TRANSIENT_RETRIES` in plan_executor.
+ * Reset to 0 on user-initiated retry / step success. */
+ transient_attempts?: number;
/** Legacy free-form notes (kept for tools that still use it). */
notes?: string;
@@ -131,6 +136,8 @@ function normalizeStep(raw: any, i: number): PlanStep {
...(Array.isArray(raw?.output_files) ? { output_files: raw.output_files.map(String) } : {}),
...(typeof raw?.output_msg_id === 'string' ? { output_msg_id: raw.output_msg_id } : {}),
...(typeof raw?.failure_reason === 'string' ? { failure_reason: raw.failure_reason } : {}),
+ ...(Number.isFinite(Number(raw?.transient_attempts)) && Number(raw.transient_attempts) > 0
+ ? { transient_attempts: Number(raw.transient_attempts) } : {}),
...(typeof raw?.notes === 'string' && raw.notes.trim() ? { notes: String(raw.notes) } : {}),
};
}
@@ -204,7 +211,7 @@ export async function setPlan(
export async function updateStep(
uid: string, cid: string, stepIndex: number, status: StepStatus,
- patch?: { notes?: string; output_summary?: string; output_files?: string[]; output_msg_id?: string; failure_reason?: string },
+ patch?: { notes?: string; output_summary?: string; output_files?: string[]; output_msg_id?: string; failure_reason?: string; transient_attempts?: number },
): Promise<PlanFile | null> {
const cur = await readPlan(uid, cid);
if (!cur) return null;
@@ -218,7 +225,14 @@ export async function updateStep(
if (patch?.output_summary !== undefined) cur.steps[idx].output_summary = patch.output_summary;
if (patch?.output_files !== undefined) cur.steps[idx].output_files = patch.output_files;
if (patch?.output_msg_id !== undefined) cur.steps[idx].output_msg_id = patch.output_msg_id;
- if (patch?.failure_reason !== undefined) cur.steps[idx].failure_reason = patch.failure_reason;
+ if (patch?.failure_reason !== undefined) {
+ if (patch.failure_reason) cur.steps[idx].failure_reason = patch.failure_reason;
+ else delete cur.steps[idx].failure_reason;
+ }
+ if (patch?.transient_attempts !== undefined) {
+ if (patch.transient_attempts > 0) cur.steps[idx].transient_attempts = patch.transient_attempts;
+ else delete cur.steps[idx].transient_attempts;
+ }
await writePlanRaw(uid, cid, cur);
log.info(`plan-update user=${uid} cid=${cid} step=${stepIndex} status=${status}`);
return cur;
diff --git a/src/main/features/group_chat/plan_executor.ts b/src/main/features/group_chat/plan_executor.ts
index 23fb0266..f1f4c44e 100644
--- a/src/main/features/group_chat/plan_executor.ts
+++ b/src/main/features/group_chat/plan_executor.ts
@@ -55,6 +55,42 @@ const log = createLogger('group_chat.plan_executor');
const COMMANDER_ALIASES = new Set(['commander', '指挥官']);
const USER_ALIASES = new Set(['user', '用户']);
+/** Plan-level safety net for transient failures. core-agent's runner already
+ * has its own `maxRetries=3` exponential-backoff retry inside a single
+ * stream call; this kicks in only AFTER that bubbles up — i.e. the network
+ * was down long enough that even the inner retries failed. We then fold
+ * the step back to `pending` so reconcile re-dispatches the whole turn
+ * (fresh stream, fresh provider connection). Capped to avoid infinite
+ * loops when the user is just genuinely offline.
+ *
+ * IMPORTANT — never include `aborted` or `cancelled` in this pattern:
+ * user-initiated abort must not be silently retried; the literal string
+ * `'aborted by user'` is also explicitly excluded by the guard. */
+const TRANSIENT_ERR_PATTERNS = /\b(terminated|fetch failed|ECONNRESET|ETIMEDOUT|ECONNREFUSED|EAI_AGAIN|socket hang up|EPIPE|network error|Connection closed)\b/i;
+const MAX_TRANSIENT_RETRIES = 2;
+
+/** Returns true when `reason` matches a transient network-error pattern AND
+ * this step still has plan-level retry budget. Caller should bail out
+ * (return early) — we've already flipped the step back to `pending` so the
+ * next reconcile will redispatch. */
+async function maybeRetryTransient(
+ uid: string, cid: string, step: PlanStep, reason: string,
+): Promise<boolean> {
+ if (!reason) return false;
+ if (reason === 'aborted by user') return false;
+ if (!TRANSIENT_ERR_PATTERNS.test(reason)) return false;
+ const attempts = step.transient_attempts ?? 0;
+ if (attempts >= MAX_TRANSIENT_RETRIES) return false;
+ await updateStep(uid, cid, step.index, 'pending', {
+ transient_attempts: attempts + 1,
+ failure_reason: '',
+ output_msg_id: '',
+ });
+ log.info(`plan-step transient-retry cid=${cid} step=${step.index} attempts=${attempts + 1}/${MAX_TRANSIENT_RETRIES} reason=${reason}`);
+ _hooks!.emitPlanChanged(uid, cid);
+ return true;
+}
+
// ── Public API ───────────────────────────────────────────────────────────
/** Trigger context attached to a worker QueueItem. Identifies which step (if
@@ -401,6 +437,7 @@ async function transitionStepDone(
output_summary: summary,
output_files: files,
output_msg_id: outputMsgId,
+ transient_attempts: 0,
});
_hooks!.emitPlanChanged(uid, cid);
log.info(`plan-step done cid=${cid} step=${step.index} assignee=${step.assignee}`);
@@ -409,6 +446,7 @@ async function transitionStepDone(
async function transitionStepFailed(
uid: string, cid: string, step: PlanStep, reason: string, outputMsgId: string,
): Promise<void> {
+ if (await maybeRetryTransient(uid, cid, step, reason)) return;
const policy: FailurePolicy = step.on_failure || 'ask_commander';
if (policy === 'continue') {
await updateStep(uid, cid, step.index, 'skipped', {
@@ -442,8 +480,10 @@ async function transitionStepFailed(
_hooks!.emitPlanChanged(uid, cid);
}
-/** Fired after a step transition to dispatch downstream + check terminal. */
-async function reconcileAfterStepTransition(uid: string, cid: string): Promise<void> {
+/** Fired after a step transition to dispatch downstream + check terminal.
+ * Exported so user-driven recovery actions (`retryStep` / `skipStep`) can
+ * reuse the exact same dispatch path the bus uses internally. */
+export async function reconcileAfterStepTransition(uid: string, cid: string): Promise<void> {
const plan = await readPlan(uid, cid);
if (!plan?.steps?.length) return;
await dispatchReady(uid, cid, plan);
@@ -490,6 +530,84 @@ function escapeHtmlForBubble(s: string): string {
.replace(/"/g, '&quot;');
}
+/** User-initiated recovery for a `failed` step. Sets the step back to
+ * `pending`, clears `failure_reason` and resets `transient_attempts`,
+ * then unblocks any downstream steps that were cascade-skipped specifically
+ * because of THIS step's failure (under `abort_plan` policy). Finally calls
+ * the same `reconcileAfterStepTransition` the bus uses internally so
+ * redispatch goes through one path.
+ *
+ * IMPORTANT — never enqueues directly. The single dispatch primitive remains
+ * `bus.enqueue`, and we reach it only via `reconcileAfterStepTransition →
+ * dispatchReady → enqueue`. */
+export async function retryStep(
+ uid: string, cid: string, stepIndex: number,
+): Promise<{ ok: boolean; error?: string }> {
+ if (!_hooks) return { ok: false, error: 'executor not bound' };
+ return _planLock(uid, cid).runExclusive(async () => {
+ const plan = await readPlan(uid, cid);
+ if (!plan) return { ok: false, error: 'no plan' };
+ const step = plan.steps.find((s) => s.index === stepIndex);
+ if (!step) return { ok: false, error: 'step not found' };
+ if (step.status !== 'failed') {
+ return { ok: false, error: `step is not in failed state (current: ${step.status})` };
+ }
+ await updateStep(uid, cid, stepIndex, 'pending', {
+ failure_reason: '',
+ output_msg_id: '',
+ transient_attempts: 0,
+ });
+ // Unblock cascade-skipped downstream: when step N failed under
+ // `abort_plan` policy, applyTermination marked all not-yet-terminal
+ // steps `skipped` with reason `aborted by step N failure`. Retrying
+ // step N should also re-arm those cascade victims; users explicitly
+ // skipped via the rail's "skip" button keep their reason and are NOT
+ // re-armed (their reason is the original failure_reason verbatim).
+ const cascadeReason = `aborted by step ${stepIndex} failure`;
+ const fresh = await readPlan(uid, cid);
+ if (fresh) {
+ for (const s of fresh.steps) {
+ if (s.status === 'skipped' && s.failure_reason === cascadeReason) {
+ await updateStep(uid, cid, s.index, 'pending', {
+ failure_reason: '',
+ });
+ }
+ }
+ }
+ log.info(`plan-step retry-requested cid=${cid} step=${stepIndex}`);
+ _hooks!.emitPlanChanged(uid, cid);
+ await reconcileAfterStepTransition(uid, cid);
+ return { ok: true };
+ });
+}
+
+/** User-initiated skip for a `failed` step. Marks it `skipped` while keeping
+ * `failure_reason` (so the rail can still show why). Downstream that wasn't
+ * in cascade now becomes ready (skipped is treated as terminal in
+ * `findReadySteps`). Cascade-victims of THIS step keep their `skipped`
+ * state — the user opted not to retry, downstream cascade stays. */
+export async function skipStep(
+ uid: string, cid: string, stepIndex: number,
+): Promise<{ ok: boolean; error?: string }> {
+ if (!_hooks) return { ok: false, error: 'executor not bound' };
+ return _planLock(uid, cid).runExclusive(async () => {
+ const plan = await readPlan(uid, cid);
+ if (!plan) return { ok: false, error: 'no plan' };
+ const step = plan.steps.find((s) => s.index === stepIndex);
+ if (!step) return { ok: false, error: 'step not found' };
+ if (step.status !== 'failed') {
+ return { ok: false, error: `step is not in failed state (current: ${step.status})` };
+ }
+ await updateStep(uid, cid, stepIndex, 'skipped', {
+ transient_attempts: 0,
+ });
+ log.info(`plan-step skip-requested cid=${cid} step=${stepIndex}`);
+ _hooks!.emitPlanChanged(uid, cid);
+ await reconcileAfterStepTransition(uid, cid);
+ return { ok: true };
+ });
+}
+
/** Main entry point. Mark the finished step done (if any), then dispatch
* every step that's now ready. Re-entrant: dispatching may itself trigger
* more reconciles via the enqueue chain; the "find ready + dispatch" loop
@@ -572,6 +690,7 @@ async function applyTermination(
}
if (failed) {
const reason = ctx.finishedMessage?.failureReason || '(unknown)';
+ if (await maybeRetryTransient(uid, cid, step, reason)) return;
const policy: FailurePolicy = step.on_failure || 'ask_commander';
if (policy === 'continue') {
await updateStep(uid, cid, step.index, 'skipped', {
@@ -606,6 +725,7 @@ async function applyTermination(
}
} else {
await updateStep(uid, cid, step.index, 'done', {
+ transient_attempts: 0,
output_summary: captureOutput(ctx.finishedMessage?.text || ''),
output_files: ctx.finishedMessage?.files || [],
output_msg_id: ctx.finishedMessage?.id,
diff --git a/src/main/ipc/index.ts b/src/main/ipc/index.ts
index 95232a17..67b4bac2 100644
--- a/src/main/ipc/index.ts
+++ b/src/main/ipc/index.ts
@@ -128,6 +128,16 @@ const invokeHandlers: Record<string, InvokeHandler> = {
return groupChat.readPlanForCid(ctx.userId, cid);
},
+ 'groupChat.retryStep': async ({ cid, stepIndex }, ctx) => {
+ if (!safeId(cid)) throw new Error('invalid cid');
+ return groupChat.retryStep(ctx.userId, cid, Number(stepIndex));
+ },
+
+ 'groupChat.skipStep': async ({ cid, stepIndex }, ctx) => {
+ if (!safeId(cid)) throw new Error('invalid cid');
+ return groupChat.skipStep(ctx.userId, cid, Number(stepIndex));
+ },
+
'groupChat.markFormSubmitted': async ({ cid, msgId, formId, values }, ctx) => {
if (!safeId(cid)) throw new Error('invalid cid');
if (typeof msgId !== 'string' || !msgId) throw new Error('invalid msgId');
diff --git a/src/renderer/index.html b/src/renderer/index.html
index 78ba4d1e..762385fa 100644
--- a/src/renderer/index.html
+++ b/src/renderer/index.html
@@ -102,6 +102,18 @@
pinned right. Chip stays anchored to input-area's top
regardless of attachment count. -->
<div class="chat-input-overlay">
+ <!-- Plan rail floats at left, mirroring the workspace chip
+ on the right. Self-hides when current cid has no plan.
+ Expanded body opens UPWARD (bottom: 100%) over the
+ chat-history. See modules/plan-rail.js. -->
+ <div id="plan-rail" class="plan-rail" style="display:none">
+ <div class="plan-rail-header" data-i18n-title="plan.toggle_title" title="折叠/展开">
+ <span class="plan-rail-title">📋 <span data-i18n="plan.title">执行计划</span></span>
+ <span class="plan-rail-progress" id="plan-rail-progress"></span>
+ <span class="plan-rail-toggle" id="plan-rail-toggle">▴</span>
+ </div>
+ <div class="plan-rail-body" id="plan-rail-body"></div>
+ </div>
<div class="chat-attachments" id="chat-attachments" style="display:none"></div>
<div class="chat-input-toolbar"></div>
</div>
@@ -703,6 +715,7 @@
<script src="./modules/chat-input-form.js"></script>
<script src="./modules/chat-lightbox.js"></script>
<script src="./modules/conversation.js"></script>
+ <script src="./modules/plan-rail.js"></script>
<script src="./modules/queue-draft.js"></script>
<script src="./modules/skills.js"></script>
<script src="./modules/contexts.js"></script>
diff --git a/src/renderer/locales/en.json b/src/renderer/locales/en.json
index d5450544..4f04e61a 100644
--- a/src/renderer/locales/en.json
+++ b/src/renderer/locales/en.json
@@ -60,6 +60,16 @@
"chat.thinking": "Thinking...",
"chat.thinking_short": "Thinking",
"chat.plan_announce": "Execution Plan",
+ "plan.title": "Execution Plan",
+ "plan.toggle_title": "Collapse / Expand",
+ "plan.action.retry": "Retry",
+ "plan.action.skip": "Skip",
+ "plan.action.abort": "Abort plan",
+ "plan.confirm.skip": "Skip this step? Downstream will no longer be blocked by it, but the step itself won't run.",
+ "plan.confirm.abort": "Abort the entire plan? All unfinished steps will be aborted.",
+ "plan.error.retry_failed": "Retry failed: {reason}",
+ "plan.error.skip_failed": "Skip failed: {reason}",
+ "plan.error.abort_failed": "Abort failed: {reason}",
"chat.from_commander": "Commander",
"chat.from_user": "User",
"chat.from_agent_unknown": "Agent",
diff --git a/src/renderer/locales/zh.json b/src/renderer/locales/zh.json
index f9e52f1d..9f43e02b 100644
--- a/src/renderer/locales/zh.json
+++ b/src/renderer/locales/zh.json
@@ -60,6 +60,16 @@
"chat.thinking": "思考中...",
"chat.thinking_short": "思考中",
"chat.plan_announce": "执行计划",
+ "plan.title": "执行计划",
+ "plan.toggle_title": "折叠/展开",
+ "plan.action.retry": "重试",
+ "plan.action.skip": "跳过",
+ "plan.action.abort": "放弃整个计划",
+ "plan.confirm.skip": "确认跳过此步骤?下游不再因这一步阻塞,但本步本身不会再跑。",
+ "plan.confirm.abort": "确认放弃整个执行计划?所有未完成的步骤都会被中止。",
+ "plan.error.retry_failed": "重试失败: {reason}",
+ "plan.error.skip_failed": "跳过失败: {reason}",
+ "plan.error.abort_failed": "放弃失败: {reason}",
"chat.from_commander": "指挥官",
"chat.from_user": "用户",
"chat.from_agent_unknown": "智能体",
diff --git a/src/renderer/modules/conversation.js b/src/renderer/modules/conversation.js
index d25ebe83..bc725bee 100644
--- a/src/renderer/modules/conversation.js
+++ b/src/renderer/modules/conversation.js
@@ -283,6 +283,11 @@ function onEnterConversationView() {
// before the user types. View-enter never reverts to commander (see
// `_evaluateAutoRecipient`); the persisted per-cid pick stays sticky.
if (currentCid) _evaluateAutoRecipient(currentCid);
+ // Bind the plan rail to the active cid on EVERY conversation-view enter,
+ // including the `skipLoad: true` path used by fresh conversations (where
+ // loadConversationHistory is intentionally skipped). Without this hook,
+ // the rail would keep displaying the previous cid's plan content.
+ if (window.PlanRail) window.PlanRail.bind(currentCid || null);
}
// Called by queue-draft.js::_forgetConvLocal when a conv is deleted so we
@@ -1149,6 +1154,8 @@ async function loadConversationHistory(cid) {
container.classList.remove('has-scroll-offset');
container.innerHTML = `<div class="empty">${escapeHtml(t('chat.loading'))}</div>`;
_ensureCreateAgentInlineObserver();
+ // (Plan rail bind happens in onEnterConversationView — covers both this
+ // load path AND the skipLoad freshly-created-conv path.)
try {
// Warm `_agentsCache` if a chat-first session never visited the agents
// tab — `_buildMentionRe` / `_groupActorLabel` both read it for current
@@ -2926,6 +2933,7 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
// when an interactive agent's step enters in_progress, the user's next
// reply should default to that agent without them having to @-mention.
_evaluateAutoRecipient(cid);
+ if (window.PlanRail) window.PlanRail.refresh(cid);
} else if (evData.type === 'state_changed') {
// Each in_flight actor gets a placeholder so its delta tokens / tool
// calls render in its own bubble even before its `message` arrives.
@@ -2945,6 +2953,11 @@ function _handleGroupBusEvent(cid, streamingMsg, evData, { archive = false } = {
// the auto-target so the chip matches the current dispatch state even
// when a plan_changed event was missed (e.g. on first connect).
_evaluateAutoRecipient(cid);
+ // Plan rail hides retry/skip/abort buttons whenever any worker is in
+ // flight (avoids racing user actions against an in-progress turn).
+ if (window.PlanRail) {
+ window.PlanRail.setInFlight(cid, Array.isArray(st.in_flight) ? st.in_flight : []);
+ }
} else if (evData.type === 'aborted') {
// Only drop EMPTY placeholders here (queued-but-not-yet-running workers
// whose queue got cleared by bus.abort never fire runTurn → no follow-up
diff --git a/src/renderer/modules/ipc-shim.js b/src/renderer/modules/ipc-shim.js
index 4d4f829d..81ddf3cc 100644
--- a/src/renderer/modules/ipc-shim.js
+++ b/src/renderer/modules/ipc-shim.js
@@ -59,6 +59,8 @@ const _IPC_ROUTES = [
['POST', /^\/api\/conversations\/([^/]+)\/abort$/, 'groupChat.abort', ['cid']],
['GET', /^\/api\/conversations\/([^/]+)\/members$/, 'groupChat.listMembers', ['cid']],
['GET', /^\/api\/conversations\/([^/]+)\/plan$/, 'groupChat.readPlan', ['cid']],
+ ['POST', /^\/api\/conversations\/([^/]+)\/plan\/steps\/(\d+)\/retry$/, 'groupChat.retryStep', ['cid', 'stepIndex']],
+ ['POST', /^\/api\/conversations\/([^/]+)\/plan\/steps\/(\d+)\/skip$/, 'groupChat.skipStep', ['cid', 'stepIndex']],
['POST', /^\/api\/conversations\/([^/]+)\/events\/stream$/, 'groupChat.events', ['cid'], { stream: true }],
['POST', /^\/api\/conversations\/([^/]+)\/form-submitted$/, 'groupChat.markFormSubmitted', ['cid']],
['GET', /^\/api\/conversations\/([^/]+)\/attachments$/, 'conversations.attachments.list', ['cid']],
diff --git a/src/renderer/modules/plan-rail.js b/src/renderer/modules/plan-rail.js
new file mode 100644
index 00000000..a84849fb
--- /dev/null
+++ b/src/renderer/modules/plan-rail.js
@@ -0,0 +1,274 @@
+/**
+ * Plan rail — sticky-top visualization of `<cid>/plan.json` inside
+ * #panel-conversation. Re-renders on `plan_changed` / `state_changed`
+ * events from the conversation event stream (see conversation.js).
+ *
+ * Responsibilities:
+ * - Render every step with status icon + index + title + assignee
+ * - Show progress count `done/total` in the header
+ * - On `failed` steps (and only when state.in_flight is empty),
+ * surface 重试 / 跳过 / 放弃 actions wired to IPC
+ * - On `pending` steps with `transient_attempts > 0`, render a small
+ * `🔁 N/2` badge so users see the auto-retry in flight (otherwise the
+ * transient retry would silently look like the step is just stuck)
+ * - Click a step row → scroll chat-history to that step's `output_msg_id`
+ *
+ * Status icon set is FIXED — single source of truth in this file's
+ * STATUS_ICON constant. Do not duplicate / template / let the LLM rewrite.
+ */
+
+const _planRailLog = createLogger('plan-rail');
+
+// FIXED status → icon mapping. Single source of truth — no LLM input,
+// no backend, no locales should ever inject a different glyph.
+const STATUS_ICON = {
+ pending: '⏳',
+ in_progress: '▶️',
+ done: '✅',
+ failed: '❌',
+ skipped: '⏭️',
+ blocked: '📝',
+};
+const TRANSIENT_BADGE_ICON = '🔁';
+const MAX_TRANSIENT_RETRIES = 2; // mirrors plan_executor.ts
+
+let _currentCid = null;
+let _currentInFlight = [];
+let _refreshInflight = null; // dedup overlapping refresh requests
+
+function _isStepActionable(step, inFlight) {
+ return step.status === 'failed' && (!inFlight || inFlight.length === 0);
+}
+
+function _buildStepHtml(step) {
+ const icon = STATUS_ICON[step.status] || STATUS_ICON.pending;
+ const num = `${step.index}.`;
+ const title = escapeHtml(step.title || '');
+ const assignee = step.assignee ? escapeHtml(step.assignee) : '';
+ const transient = (step.status === 'pending' || step.status === 'in_progress')
+ && Number(step.transient_attempts) > 0
+ ? `<span class="plan-rail-step-transient">${TRANSIENT_BADGE_ICON} ${step.transient_attempts}/${MAX_TRANSIENT_RETRIES}</span>`
+ : '';
+ const meta = assignee
+ ? `<div class="plan-rail-step-meta">@${assignee}</div>`
+ : '';
+ const reason = step.failure_reason
+ ? `<div class="plan-rail-step-reason">${escapeHtml(step.failure_reason)}</div>`
+ : '';
+ const actions = _isStepActionable(step, _currentInFlight)
+ ? `<div class="plan-rail-step-actions">
+ <button type="button" class="btn btn-sm" data-action="retry" data-i18n="plan.action.retry">${escapeHtml(t('plan.action.retry') || '重试')}</button>
+ <button type="button" class="btn btn-sm" data-action="skip" data-i18n="plan.action.skip">${escapeHtml(t('plan.action.skip') || '跳过')}</button>
+ <button type="button" class="btn btn-sm btn-danger" data-action="abort" data-i18n="plan.action.abort">${escapeHtml(t('plan.action.abort') || '放弃整个计划')}</button>
+ </div>`
+ : '';
+ return `<div class="plan-rail-step is-${step.status}" data-step-index="${step.index}" ${step.output_msg_id ? `data-msg-id="${escapeHtml(step.output_msg_id)}"` : ''}>
+ <div class="plan-rail-step-head">
+ <span class="plan-rail-step-icon" aria-label="${step.status}">${icon}</span>
+ <span class="plan-rail-step-num">${num}</span>
+ <span class="plan-rail-step-title">${title}</span>
+ ${transient}
+ </div>
+ ${meta}
+ ${reason}
+ ${actions}
+ </div>`;
+}
+
+function _buildProgressText(plan) {
+ const done = plan.steps.filter((s) => s.status === 'done' || s.status === 'skipped').length;
+ return `${done}/${plan.steps.length}`;
+}
+
+function _render(plan) {
+ const root = document.getElementById('plan-rail');
+ const body = document.getElementById('plan-rail-body');
+ const progress = document.getElementById('plan-rail-progress');
+ if (!root || !body || !progress) return;
+ if (!plan || !Array.isArray(plan.steps) || plan.steps.length === 0) {
+ root.style.display = 'none';
+ body.innerHTML = '';
+ progress.textContent = '';
+ return;
+ }
+ root.style.display = '';
+ progress.textContent = _buildProgressText(plan);
+ body.innerHTML = plan.steps.map(_buildStepHtml).join('');
+}
+
+async function _fetchPlan(cid) {
+ try {
+ const res = await apiFetch(`/api/conversations/${encodeURIComponent(cid)}/plan`);
+ if (!res.ok) return null;
+ const data = await res.json();
+ if (data?.ok && data.plan) return data.plan;
+ return null;
+ } catch (err) {
+ _planRailLog.warn(`fetch plan failed cid=${cid}: ${err && err.message}`);
+ return null;
+ }
+}
+
+async function _doRefresh(cid) {
+ if (!cid) return;
+ if (cid !== _currentCid) return; // view switched mid-fetch
+ const plan = await _fetchPlan(cid);
+ if (cid !== _currentCid) return;
+ _render(plan);
+}
+
+// ── Public API ───────────────────────────────────────────────────────────
+
+const PlanRail = {
+ /** Bind to a cid: refresh + remember. Call from conversation view-change.
+ * Clears the rail synchronously FIRST so any stale content from the
+ * previous cid is gone before the async fetch resolves. */
+ bind(cid) {
+ _currentCid = cid || null;
+ _currentInFlight = [];
+ // Drop any pending refresh from the previous cid — its result would
+ // race with this bind's fetch and could write stale content into the
+ // DOM. The cid-mismatch guard inside _doRefresh covers most of it,
+ // but resetting the dedup slot also lets the new refresh fire instead
+ // of being coalesced into the old one.
+ _refreshInflight = null;
+ _render(null);
+ if (!cid) return;
+ PlanRail.refresh(cid);
+ },
+
+ /** Detach from any cid. Hides the rail. Call when leaving conversation view. */
+ unbind() {
+ _currentCid = null;
+ _currentInFlight = [];
+ _refreshInflight = null;
+ _render(null);
+ },
+
+ /** Re-fetch + re-render. Coalesces concurrent calls for the SAME cid;
+ * bind() is responsible for clearing the slot when cid changes. */
+ refresh(cid) {
+ if (!cid || cid !== _currentCid) return;
+ if (_refreshInflight) return _refreshInflight;
+ _refreshInflight = (async () => {
+ try { await _doRefresh(cid); }
+ finally { _refreshInflight = null; }
+ })();
+ return _refreshInflight;
+ },
+
+ /** Update the in_flight snapshot used to show/hide action buttons. Called
+ * from conversation.js's `state_changed` handler. Triggers a re-render. */
+ setInFlight(cid, inFlight) {
+ if (cid !== _currentCid) return;
+ _currentInFlight = Array.isArray(inFlight) ? inFlight.slice() : [];
+ PlanRail.refresh(cid);
+ },
+};
+
+// Expose on the global namespace for conversation.js to hook.
+window.PlanRail = PlanRail;
+
+// ── Action wiring ────────────────────────────────────────────────────────
+
+document.addEventListener('click', async (ev) => {
+ const root = document.getElementById('plan-rail');
+ if (!root || !root.contains(ev.target)) return;
+
+ // Whole header is the toggle. Body clicks (action buttons / step rows)
+ // are not inside .plan-rail-header so they fall through to the handlers
+ // further down.
+ const header = ev.target.closest('.plan-rail-header');
+ if (header) {
+ const isCollapsed = root.classList.toggle('is-collapsed');
+ const toggle = document.getElementById('plan-rail-toggle');
+ if (toggle) toggle.textContent = isCollapsed ? '▴' : '▾';
+ try { localStorage.setItem(`plan-rail-collapsed-${_currentCid}`, isCollapsed ? '1' : '0'); }
+ catch { /* ignore */ }
+ return;
+ }
+
+ // Action buttons.
+ const btn = ev.target.closest('[data-action]');
+ if (btn) {
+ ev.stopPropagation();
+ const stepEl = btn.closest('[data-step-index]');
+ const stepIndex = stepEl ? Number(stepEl.dataset.stepIndex) : NaN;
+ const cid = _currentCid;
+ if (!cid || !Number.isFinite(stepIndex)) return;
+ const action = btn.dataset.action;
+ if (action === 'retry') {
+ try {
+ const res = await apiFetch(
+ `/api/conversations/${encodeURIComponent(cid)}/plan/steps/${stepIndex}/retry`,
+ { method: 'POST' },
+ );
+ const data = await res.json().catch(() => ({}));
+ if (!data?.ok) {
+ uiAlert(t('plan.error.retry_failed', { reason: data?.error || 'unknown' }) || `重试失败: ${data?.error || 'unknown'}`);
+ }
+ } catch (err) {
+ uiAlert(t('plan.error.retry_failed', { reason: err && err.message }) || `重试失败: ${err && err.message}`);
+ }
+ return;
+ }
+ if (action === 'skip') {
+ const ok = await uiConfirm(t('plan.confirm.skip') || '确认跳过此步骤?');
+ if (!ok) return;
+ try {
+ const res = await apiFetch(
+ `/api/conversations/${encodeURIComponent(cid)}/plan/steps/${stepIndex}/skip`,
+ { method: 'POST' },
+ );
+ const data = await res.json().catch(() => ({}));
+ if (!data?.ok) {
+ uiAlert(t('plan.error.skip_failed', { reason: data?.error || 'unknown' }) || `跳过失败: ${data?.error || 'unknown'}`);
+ }
+ } catch (err) {
+ uiAlert(t('plan.error.skip_failed', { reason: err && err.message }) || `跳过失败: ${err && err.message}`);
+ }
+ return;
+ }
+ if (action === 'abort') {
+ const ok = await uiConfirm(t('plan.confirm.abort') || '确认放弃整个执行计划?');
+ if (!ok) return;
+ try {
+ await apiFetch(
+ `/api/conversations/${encodeURIComponent(cid)}/abort`,
+ { method: 'POST' },
+ );
+ } catch (err) {
+ uiAlert(t('plan.error.abort_failed', { reason: err && err.message }) || `放弃失败: ${err && err.message}`);
+ }
+ return;
+ }
+ return;
+ }
+
+ // Click step row → scroll chat-history to its output_msg_id.
+ const stepEl = ev.target.closest('[data-step-index]');
+ if (stepEl && stepEl.dataset.msgId) {
+ const target = document.querySelector(`[data-msg-id="${CSS.escape(stepEl.dataset.msgId)}"]`);
+ if (target && typeof target.scrollIntoView === 'function') {
+ target.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ }
+ }
+});
+
+// Restore collapsed state when binding a cid. Default is collapsed (the
+// floating chip UX assumes the panel is opened on demand). localStorage
+// only flips that when the user explicitly opened it last visit.
+const _origBind = PlanRail.bind;
+PlanRail.bind = function (cid) {
+ _origBind.call(PlanRail, cid);
+ const root = document.getElementById('plan-rail');
+ const toggle = document.getElementById('plan-rail-toggle');
+ if (!root || !toggle || !cid) return;
+ let collapsed = true;
+ try {
+ const stored = localStorage.getItem(`plan-rail-collapsed-${cid}`);
+ if (stored === '0') collapsed = false;
+ } catch { /* ignore */ }
+ root.classList.toggle('is-collapsed', collapsed);
+ toggle.textContent = collapsed ? '▴' : '▾';
+};
diff --git a/src/renderer/style.css b/src/renderer/style.css
index cc5715d5..f3a98175 100644
--- a/src/renderer/style.css
+++ b/src/renderer/style.css
@@ -3769,6 +3769,142 @@ body.model-not-configured .main-content { flex-direction: column; }
.btn-sm { padding: 4px 10px; font-size: 12px; }
+/* ────────────────────────────────────────────────────────────────────────
+ Plan rail — pinned to the LEFT of the .chat-input-overlay strip
+ (mirrors the workspace chip pinned right). Collapsed = a compact pill
+ chip sitting just above the input bubble; expanded = a fixed-width,
+ max-height panel that opens UPWARD over the chat history. The whole
+ header is the toggle. Status icon set is fixed; do not theme-swap.
+ See modules/plan-rail.js.
+ ──────────────────────────────────────────────────────────────────── */
+.plan-rail {
+ position: relative; /* anchor for the absolute body */
+ flex: 0 0 auto; /* leftmost item in chat-input-overlay flex row */
+ pointer-events: auto; /* overlay parent has pointer-events:none */
+ font-size: 13px;
+ user-select: none;
+ z-index: 11; /* above chat-input-wrapper (z:10) */
+}
+.plan-rail-header {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 12px;
+ background: #fff;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.08);
+ cursor: pointer;
+ font-weight: 500;
+ transition: box-shadow 0.15s, background 0.15s;
+}
+.plan-rail-header:hover { background: #f8fafc; box-shadow: 0 2px 6px rgba(15, 23, 42, 0.12); }
+.plan-rail-title { flex: 0 0 auto; }
+.plan-rail-progress {
+ flex: 0 0 auto;
+ color: var(--text);
+ opacity: 0.55;
+ font-variant-numeric: tabular-nums;
+ font-size: 12px;
+}
+.plan-rail-toggle {
+ margin-left: 2px;
+ font-size: 11px;
+ color: var(--text);
+ opacity: 0.55;
+ pointer-events: none; /* the whole header handles the click */
+}
+.plan-rail-body {
+ position: absolute;
+ bottom: calc(100% + 6px); /* opens UPWARD from the chip */
+ left: 0;
+ width: 380px;
+ max-width: calc(100vw - 48px);
+ max-height: 50vh;
+ overflow-y: auto;
+ padding: 8px;
+ background: #fff;
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ box-shadow: 0 6px 20px rgba(15, 23, 42, 0.12);
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+.plan-rail.is-collapsed .plan-rail-body { display: none; }
+
+/* Two-row step layout: row 1 is icon + num + title (title may wrap so
+ long Chinese sentences keep readable); row 2 is the assignee chip
+ indented under the title. Reason / actions stack below in their own
+ blocks. Avoids the title-vs-assignee column squish. */
+.plan-rail-step {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 6px 8px;
+ border-radius: 6px;
+ cursor: pointer;
+ transition: background 0.12s;
+}
+.plan-rail-step:hover { background: rgba(148, 163, 184, 0.08); }
+.plan-rail-step-head {
+ display: flex;
+ align-items: baseline;
+ gap: 6px;
+}
+.plan-rail-step-icon { font-size: 14px; line-height: 1; flex: 0 0 auto; }
+.plan-rail-step-num {
+ font-variant-numeric: tabular-nums;
+ opacity: 0.6;
+ flex: 0 0 auto;
+}
+.plan-rail-step-title {
+ color: var(--text);
+ flex: 1 1 auto;
+ word-break: break-word;
+ line-height: 1.4;
+}
+.plan-rail-step-transient {
+ font-size: 12px;
+ color: var(--text);
+ opacity: 0.7;
+ white-space: nowrap;
+ flex: 0 0 auto;
+}
+/* Assignee on its own line, indented under the title text (icon + num
+ take ~32px). Smaller font, primary color, single line with ellipsis. */
+.plan-rail-step-meta {
+ margin-left: 32px;
+ font-size: 11px;
+ color: var(--primary);
+ opacity: 0.8;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.plan-rail-step-reason {
+ margin-left: 32px;
+ font-size: 12px;
+ color: var(--danger);
+ opacity: 0.85;
+ word-break: break-word;
+}
+.plan-rail-step-actions {
+ margin-left: 32px;
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ padding-top: 4px;
+}
+
+/* Per-status accents — only on the title to avoid icon recoloring (the
+ emoji carries its own color). */
+.plan-rail-step.is-done .plan-rail-step-title { opacity: 0.65; text-decoration: line-through; text-decoration-color: rgba(0,0,0,0.2); }
+.plan-rail-step.is-skipped .plan-rail-step-title { opacity: 0.55; }
+.plan-rail-step.is-failed .plan-rail-step-title { color: var(--danger); }
+.plan-rail-step.is-blocked .plan-rail-step-title { color: var(--text); /* neutral — the 📝 icon already conveys "awaiting input" */ }
+.plan-rail-step.is-in_progress .plan-rail-step-title { color: var(--primary); font-weight: 500; }
+
/* Detail-page action button row (shared across skills / agents / contexts).
`margin-left: auto` keeps buttons right-aligned even after flex-wrap. */
.detail-actions {
diff --git a/test/main/features/group_chat/plan-recovery.test.ts b/test/main/features/group_chat/plan-recovery.test.ts
new file mode 100644
index 00000000..810cea04
--- /dev/null
+++ b/test/main/features/group_chat/plan-recovery.test.ts
@@ -0,0 +1,330 @@
+/**
+ * Plan recovery — covers the plan-rail's user-initiated state actions
+ * (`retryStep`, `skipStep`) and the executor's transient-error auto-retry
+ * safety net (the `maybeRetryTransient` guard inside `transitionStepFailed`
+ * and `applyTermination`).
+ *
+ * These are the two recovery paths the rail exposes; together they unlock
+ * the "step failed → plan deadlock" scenario that originally motivated the
+ * rail. See `docs/plans/plan-rail.md` (deleted on acceptance) and CLAUDE.md
+ * §5 Group-chat for the spec.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+// LLM mock — same pattern as plan_executor.test.ts, only triggered for
+// transient-retry redispatch tests.
+const _scripts = new Map<string, Array<any[]>>();
+function _setScript(sessionId: string, events: any[]) {
+ const arr = _scripts.get(sessionId) || [];
+ arr.push(events);
+ _scripts.set(sessionId, arr);
+}
+function _resetScripts() { _scripts.clear(); }
+
+vi.mock('../../../../src/main/model/client', () => ({
+ async *streamChatWithModel(opts: any) {
+ const sid = opts.sessionId || '';
+ const queue = _scripts.get(sid) || [];
+ const events = queue.shift() || [{ type: 'final', text: '' }];
+ _scripts.set(sid, queue);
+ for (const ev of events) yield ev;
+ yield { type: 'done' };
+ },
+ async chatWithModel() { return { ok: true, text: '', error: '', aborted: false }; },
+}));
+
+let tmpDir: string;
+let prevWs: string | undefined;
+const TEST_UID = 'u1';
+const A_ID = 'a1a1a1a1a1a1';
+const A_NAME = 'Alpha';
+
+function newCid(): string { return 'c' + Math.random().toString(16).slice(2, 13); }
+
+beforeEach(async () => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-plan-recovery-'));
+ prevWs = process.env.ORKAS_WORKSPACE_ROOT;
+ process.env.ORKAS_WORKSPACE_ROOT = tmpDir;
+ _resetScripts();
+ vi.resetModules();
+ const users = await import('../../../../src/main/features/users');
+ users.activateUser(TEST_UID);
+
+ const paths = await import('../../../../src/main/paths');
+ const aDir = paths.agentDir(TEST_UID, A_ID);
+ fs.mkdirSync(aDir, { recursive: true });
+ fs.writeFileSync(path.join(aDir, 'agent.json'), JSON.stringify({
+ agent_id: A_ID, name: A_NAME, description: 'Alpha agent', workflow: 'do work',
+ created_at: 't', updated_at: 't',
+ }));
+});
+
+afterEach(async () => {
+ try {
+ const bus = await import('../../../../src/main/features/group_chat/bus');
+ const paths = await import('../../../../src/main/paths');
+ const dir = paths.userChatsDir(TEST_UID);
+ if (fs.existsSync(dir)) {
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
+ if (e.isDirectory() && /^c[0-9a-f]{12}$/.test(e.name)) bus.dropConv(TEST_UID, e.name);
+ }
+ }
+ } catch { /* ignore */ }
+ await new Promise((r) => setTimeout(r, 30));
+ process.env.ORKAS_WORKSPACE_ROOT = prevWs;
+ fs.rmSync(tmpDir, { recursive: true, force: true });
+});
+
+async function seedPlan(uid: string, cid: string, planInput: any) {
+ // Importing bus binds executor hooks (module side effect).
+ await import('../../../../src/main/features/group_chat/bus');
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ const state = await import('../../../../src/main/features/group_chat/state');
+ await plan.setPlan(uid, cid, planInput);
+ await state.seedReservedActors(uid, cid);
+}
+
+// ─────────────────────────────────────────────────────────────────────────
+// retryStep
+// ─────────────────────────────────────────────────────────────────────────
+
+describe('plan recovery › retryStep', () => {
+ it('flips a failed step back to pending, clears reason, resets transient_attempts', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [
+ { title: 'Step 1', assignee: A_NAME, input: 'do step 1', wait_for: [] },
+ { title: 'Step 2', assignee: A_NAME, input: 'do step 2' },
+ ],
+ });
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'failed', {
+ failure_reason: 'something exploded',
+ transient_attempts: 2,
+ });
+
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ const r = await planExecutor.retryStep(TEST_UID, cid, 1);
+ expect(r.ok).toBe(true);
+
+ const fresh = await plan.readPlan(TEST_UID, cid);
+ // Retry returns AFTER reconcileAfterStepTransition runs, which immediately
+ // dispatches the now-ready step. So observed state is "in_progress" once
+ // dispatch fires (or "pending" briefly if the assignee was unresolvable).
+ // What we care about: the step is no longer in failed state, and the
+ // failure marker / transient counter were cleared.
+ expect(fresh?.steps[0].status).not.toBe('failed');
+ expect(fresh?.steps[0].status).not.toBe('skipped');
+ expect(fresh?.steps[0].failure_reason).toBeUndefined();
+ expect(fresh?.steps[0].transient_attempts).toBeUndefined();
+ });
+
+ it('rejects when the step is not in failed state', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] }],
+ });
+ // Fresh setPlan leaves status='pending'.
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ const r = await planExecutor.retryStep(TEST_UID, cid, 1);
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/not in failed state/);
+ });
+
+ it('cascade-unblocks downstream skipped via `aborted by step N failure` reason', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [
+ { title: 'Step 1', assignee: A_NAME, wait_for: [] },
+ { title: 'Step 2', assignee: A_NAME },
+ { title: 'Step 3', assignee: A_NAME },
+ ],
+ });
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'failed', { failure_reason: 'fatal' });
+ await plan.updateStep(TEST_UID, cid, 2, 'skipped', { failure_reason: 'aborted by step 1 failure' });
+ await plan.updateStep(TEST_UID, cid, 3, 'skipped', { failure_reason: 'user did not want this' });
+
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ await planExecutor.retryStep(TEST_UID, cid, 1);
+
+ const fresh = await plan.readPlan(TEST_UID, cid);
+ // Step 1: retry path — out of failed; reconcile may have dispatched.
+ expect(fresh?.steps[0].status).not.toBe('failed');
+ // Step 2: cascade unblocked. wait_for defaults to [previous step], so it
+ // won't dispatch until step 1 completes — should sit at pending.
+ expect(fresh?.steps[1].status).toBe('pending');
+ // Step 3: skipped for an unrelated reason — preserved.
+ expect(fresh?.steps[2].status).toBe('skipped');
+ expect(fresh?.steps[2].failure_reason).toBe('user did not want this');
+ });
+});
+
+// ─────────────────────────────────────────────────────────────────────────
+// skipStep
+// ─────────────────────────────────────────────────────────────────────────
+
+describe('plan recovery › skipStep', () => {
+ it('moves failed → skipped while preserving failure_reason', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] }],
+ });
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'failed', { failure_reason: 'reason X' });
+
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ const r = await planExecutor.skipStep(TEST_UID, cid, 1);
+ expect(r.ok).toBe(true);
+
+ const fresh = await plan.readPlan(TEST_UID, cid);
+ expect(fresh?.steps[0].status).toBe('skipped');
+ expect(fresh?.steps[0].failure_reason).toBe('reason X');
+ });
+
+ it('rejects when not in failed state', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] }],
+ });
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ const r = await planExecutor.skipStep(TEST_UID, cid, 1);
+ expect(r.ok).toBe(false);
+ });
+
+ it('does NOT touch other cascade-skipped steps', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [
+ { title: 'Step 1', assignee: A_NAME, wait_for: [] },
+ { title: 'Step 2', assignee: A_NAME },
+ ],
+ });
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'failed', { failure_reason: 'boom' });
+ await plan.updateStep(TEST_UID, cid, 2, 'skipped', { failure_reason: 'aborted by step 1 failure' });
+
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ await planExecutor.skipStep(TEST_UID, cid, 1);
+
+ const fresh = await plan.readPlan(TEST_UID, cid);
+ expect(fresh?.steps[0].status).toBe('skipped');
+ expect(fresh?.steps[1].status).toBe('skipped');
+ expect(fresh?.steps[1].failure_reason).toBe('aborted by step 1 failure');
+ });
+});
+
+// ─────────────────────────────────────────────────────────────────────────
+// Transient auto-retry (A safety-net)
+// ─────────────────────────────────────────────────────────────────────────
+
+describe('plan recovery › transient auto-retry', () => {
+ async function buildEvtForStep(stepIndex: number, errText: string) {
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ return {
+ actor: { id: A_ID, kind: 'agent' as const },
+ finalText: '',
+ errText,
+ aborted: false,
+ produced: [] as string[],
+ trigger: { kind: 'plan_step' as const, step_index: stepIndex },
+ activityEvents: 0,
+ } as Parameters<typeof planExecutor.onTurnFinished>[2];
+ }
+
+ it('folds a step back to pending on undici "terminated" and increments transient_attempts', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] }],
+ });
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'in_progress');
+
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ const evt = await buildEvtForStep(1, 'TypeError: terminated');
+ await planExecutor.onTurnFinished(TEST_UID, cid, evt);
+
+ const fresh = await plan.readPlan(TEST_UID, cid);
+ // After transient retry + reconcileAfterStepTransition, the step gets
+ // re-dispatched right away → in_progress. The invariant is that the step
+ // is NOT in failed state and the attempts counter was bumped.
+ expect(fresh?.steps[0].status).not.toBe('failed');
+ expect(fresh?.steps[0].transient_attempts).toBe(1);
+ expect(fresh?.steps[0].failure_reason).toBeUndefined();
+ });
+
+ it('respects the MAX_TRANSIENT_RETRIES cap (2) and falls through to failed', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] }],
+ });
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'in_progress', { transient_attempts: 2 });
+
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ const evt = await buildEvtForStep(1, 'TypeError: terminated');
+ await planExecutor.onTurnFinished(TEST_UID, cid, evt);
+
+ const fresh = await plan.readPlan(TEST_UID, cid);
+ expect(fresh?.steps[0].status).toBe('failed');
+ expect(fresh?.steps[0].failure_reason).toMatch(/terminated/);
+ });
+
+ it('does NOT retry on user-initiated abort (errText="aborted by user")', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] }],
+ });
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'in_progress');
+
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ // The aborted=true path uses literal 'aborted by user' inside applyPlanStepTurn.
+ const evt = await buildEvtForStep(1, '');
+ (evt as any).aborted = true;
+ await planExecutor.onTurnFinished(TEST_UID, cid, evt);
+
+ const fresh = await plan.readPlan(TEST_UID, cid);
+ expect(fresh?.steps[0].status).toBe('failed');
+ expect(fresh?.steps[0].transient_attempts).toBeUndefined();
+ });
+
+ it('does NOT retry on non-transient errors (e.g. auth)', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] }],
+ });
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'in_progress');
+
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ const evt = await buildEvtForStep(1, 'auth invalid: missing api key');
+ await planExecutor.onTurnFinished(TEST_UID, cid, evt);
+
+ const fresh = await plan.readPlan(TEST_UID, cid);
+ expect(fresh?.steps[0].status).toBe('failed');
+ expect(fresh?.steps[0].transient_attempts).toBeUndefined();
+ });
+
+ it('clears transient_attempts when a step ultimately completes', async () => {
+ const cid = newCid();
+ await seedPlan(TEST_UID, cid, {
+ steps: [{ title: 'Step 1', assignee: A_NAME, wait_for: [] }],
+ });
+ const plan = await import('../../../../src/main/features/group_chat/plan');
+ await plan.updateStep(TEST_UID, cid, 1, 'in_progress', { transient_attempts: 1 });
+
+ const planExecutor = await import('../../../../src/main/features/group_chat/plan_executor');
+ const evt = await buildEvtForStep(1, '');
+ (evt as any).finalText = 'done!';
+ await planExecutor.onTurnFinished(TEST_UID, cid, evt);
+
+ const fresh = await plan.readPlan(TEST_UID, cid);
+ expect(fresh?.steps[0].status).toBe('done');
+ expect(fresh?.steps[0].transient_attempts).toBeUndefined();
+ });
+});