🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(goal): separate machine gates and ask goal decisions through one card, the island and the inbox (#20437)
Arvin Xuf24c547ebb2b
diff --git a/apps/server/src/routers/lambda/__tests__/acceptance.reject.test.ts b/apps/server/src/routers/lambda/__tests__/acceptance.reject.test.tsindex a261b889904..53a4e9b2f03 100644--- a/apps/server/src/routers/lambda/__tests__/acceptance.reject.test.ts+++ b/apps/server/src/routers/lambda/__tests__/acceptance.reject.test.ts@@ -2,7 +2,7 @@import { randomUUID } from 'node:crypto';import type { LobeChatDatabase } from '@lobechat/database';-import { acceptances, agents, topics, verifyRuns } from '@lobechat/database/schemas';+import { acceptances, agents, briefs, topics, verifyRuns } from '@lobechat/database/schemas';import { getTestDB } from '@lobechat/database/test-utils';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -340,4 +340,55 @@ describe('acceptanceRouter reject', () => {.where(eq(acceptances.id, acceptanceId));expect(acceptance.status).toBe('delivered');});++ // The list and header controls decide an acceptance without the accept /+ // reject procedures; the goal sign-off it carried must not stay open.+ describe('goal sign-off', () => {+ const seedSignOff = async () => {+ const [brief] = await serverDB+ .insert(briefs)+ .values({+ metadata: {+ goal: {+ goalId: 'goal_1',+ goalTitle: 'Goal',+ kind: 'signOff',+ signOffAcceptanceId: acceptanceId,+ },+ },+ summary: 'Sign it off',+ title: 'Goal is done',+ trigger: 'goal',+ type: 'decision',+ userId,+ })+ .returning();+ return brief.id;+ };+ const readBrief = async (id: string) =>+ (await serverDB.select().from(briefs).where(eq(briefs.id, id)))[0];++ it.each([+ ['closed', 'closed'],+ ['rejected', 'requestChanges'],+ ] as const)('settles it when the status is set to %s', async (status, action) => {+ const briefId = await seedSignOff();+ const caller = acceptanceRouter.createCaller(createTestContext(userId));++ await caller.updateStatus({ id: acceptanceId, status });++ const brief = await readBrief(briefId);+ expect(brief.resolvedAt).not.toBeNull();+ expect(brief.resolvedAction).toBe(action);+ });++ it('settles it when a batch sweep closes the acceptance', async () => {+ const briefId = await seedSignOff();+ const caller = acceptanceRouter.createCaller(createTestContext(userId));++ await caller.updateStatusBatch({ ids: [acceptanceId], status: 'closed' });++ expect((await readBrief(briefId)).resolvedAt).not.toBeNull();+ });+ });});diff --git a/apps/server/src/routers/lambda/_helpers/goalBriefAction.ts b/apps/server/src/routers/lambda/_helpers/goalBriefAction.tsnew file mode 100644index 00000000000..7de2bce914b--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/goalBriefAction.ts@@ -0,0 +1,72 @@+import type { BriefItem } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { GoalService } from '@/server/services/goal';+import { GoalBriefService } from '@/server/services/goal/goalBriefs';+import { scheduleGoalAdvance } from '@/server/services/goal/scheduler';++import { resolveAcceptanceForWrite } from '../acceptance';+import { dispatchAcceptanceRepair } from './acceptanceRepairDispatch';++type GoalBriefContext = Parameters<typeof dispatchAcceptanceRepair>[0] & {+ serverDB: LobeChatDatabase;+ userId: string;+ workspaceId?: string | null;+};++/** Actions that only move the brief itself, never the goal behind it. */+const PASSIVE_ACTIONS = new Set(['ignore', 'openGoal', 'read']);++/**+ * Answer a goal brief from the inbox the same way the goal page would: a gate+ * option is a `decide`, a sign-off is the Goal-level acceptance's accept or+ * reject. The brief is settled by that write — the goal is the state, the+ * brief only carried the question — so the caller re-reads it afterwards.+ *+ * Returns whether the action was a goal action.+ */+export const applyGoalBriefAction = async (+ ctx: GoalBriefContext,+ brief: BriefItem,+ action?: string,+ comment?: string,+): Promise<boolean> => {+ const goal = brief.metadata?.goal;+ if (!goal || !action || PASSIVE_ACTIONS.has(action)) return false;+ const workspaceId = ctx.workspaceId ?? undefined;++ if (goal.kind === 'decision' && goal.decisionId) {+ await new GoalService(ctx.serverDB, ctx.userId, workspaceId).decide(+ goal.goalId,+ goal.decisionId,+ action,+ comment?.trim() || undefined,+ );+ await scheduleGoalAdvance({+ goalId: goal.goalId,+ trigger: 'decide',+ userId: ctx.userId,+ workspaceId,+ });+ return true;+ }++ if (goal.kind === 'signOff' && goal.signOffAcceptanceId) {+ const { acceptance, service } = await resolveAcceptanceForWrite(ctx, goal.signOffAcceptanceId);+ if (action === 'signOff') {+ await service.accept(acceptance.id, comment?.trim() || undefined);+ } else if (action === 'requestChanges') {+ await service.reject(acceptance.id, comment?.trim() || undefined);+ await dispatchAcceptanceRepair(ctx, service, acceptance, comment?.trim() || undefined);+ } else {+ return false;+ }+ await new GoalBriefService(ctx.serverDB, ctx.userId, workspaceId).settleSignOff(+ acceptance.id,+ action,+ comment,+ );+ return true;+ }++ return false;+};diff --git a/apps/server/src/routers/lambda/acceptance.ts b/apps/server/src/routers/lambda/acceptance.tsindex ac1ad5959b6..cb25a9dc5d9 100644--- a/apps/server/src/routers/lambda/acceptance.ts+++ b/apps/server/src/routers/lambda/acceptance.ts@@ -32,6 +32,7 @@ import { isUuid } from '@/database/utils/uuid';import { publicProcedure, router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { FileService } from '@/server/services/file';+import { GoalBriefService } from '@/server/services/goal/goalBriefs';import { parseChangeRequestUrl } from '@/server/services/scm/changeRequestUrl';import {AcceptanceService,@@ -172,7 +173,7 @@ const acceptanceWriteProcedure = acceptanceProcedure.use(requireWorkspaceRoleWhe* `decidedBy` and an audit trail that credits a teammate's verdict to the* author is worse than one nobody can sign.*/-const resolveAcceptanceForWrite = async (+export const resolveAcceptanceForWrite = async (ctx: { serverDB: LobeChatDatabase; userId: string },id: string,): Promise<{ acceptance: AcceptanceItem; service: AcceptanceService }> => {@@ -244,6 +245,22 @@ const PURGE_PREVIEW_LIMIT = 20;const acceptanceStatusOverrideSchema = z.enum(['delivered', 'accepted', 'closed', 'rejected']);+/**+ * A decided acceptance has nothing left to sign: whichever control decided it,+ * the inbox and the island stop asking for the goal sign-off it carried.+ */+const settleGoalSignOff = (+ db: LobeChatDatabase,+ acceptance: AcceptanceItem,+ action: string,+ comment?: string,+) =>+ new GoalBriefService(db, acceptance.userId, acceptance.workspaceId ?? undefined).settleSignOff(+ acceptance.id,+ action,+ comment,+ );+/*** Apply one user-facing lifecycle override to an already-resolved,* already-authorized aggregate. Shared by the single-row menu action and the@@ -257,22 +274,26 @@ const acceptanceStatusOverrideSchema = z.enum(['delivered', 'accepted', 'closed'* not be forced back to a decision-pending state by hand.*/const applyAcceptanceStatus = async (+ db: LobeChatDatabase,service: AcceptanceService,acceptance: AcceptanceItem,status: z.infer<typeof acceptanceStatusOverrideSchema>,) => {if (status === 'accepted') {await service.accept(acceptance.id);+ await settleGoalSignOff(db, acceptance, 'signOff');return;}if (status === 'closed') {await service.acceptanceModel.updateStatus(acceptance.id, 'closed');+ await settleGoalSignOff(db, acceptance, 'closed');return;}if (status === 'rejected') {await service.reject(acceptance.id, 'Rejected from the acceptance list — needs another round.');+ await settleGoalSignOff(db, acceptance, 'requestChanges');return;}@@ -420,7 +441,10 @@ export const acceptanceRouter = router({.mutation(async ({ ctx, input }) => {const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);- return service.accept(acceptance.id, input.comment);+ const accepted = await service.accept(acceptance.id, input.comment);+ // Signed where it lives — the inbox stops asking for the same sign-off.+ await settleGoalSignOff(ctx.serverDB, acceptance, 'signOff', input.comment);+ return accepted;}),/**@@ -1345,6 +1369,12 @@ export const acceptanceRouter = router({const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);const rejected = await service.reject(acceptance.id, input.comment || undefined);+ await settleGoalSignOff(+ ctx.serverDB,+ acceptance,+ 'requestChanges',+ input.comment || undefined,+ );if (input.dispatch === false) {return { ...rejected, repairDispatch: { dispatched: false, reason: 'skipped' } };}@@ -1474,7 +1504,7 @@ export const acceptanceRouter = router({const { acceptance, service } = await resolveAcceptanceForWrite(ctx, input.id);try {- await applyAcceptanceStatus(service, acceptance, input.status);+ await applyAcceptanceStatus(ctx.serverDB, service, acceptance, input.status);} catch (error) {if (error instanceof TRPCError) throw error;throw new TRPCError({@@ -1510,7 +1540,7 @@ export const acceptanceRouter = router({for (const id of new Set(input.ids)) {try {const { acceptance, service } = await resolveAcceptanceForWrite(ctx, id);- await applyAcceptanceStatus(service, acceptance, input.status);+ await applyAcceptanceStatus(ctx.serverDB, service, acceptance, input.status);updated += 1;} catch (error) {console.error('[acceptance] batch status update failed for %s', id, error);diff --git a/apps/server/src/routers/lambda/brief.ts b/apps/server/src/routers/lambda/brief.tsindex 8b29ab3d780..7e48b449c56 100644--- a/apps/server/src/routers/lambda/brief.ts+++ b/apps/server/src/routers/lambda/brief.ts@@ -11,6 +11,8 @@ import { AgentSignalSelfReviewBriefService } from '@/server/services/agentSignalimport { NIGHTLY_REVIEW_BRIEF_TRIGGER } from '@/server/services/agentSignal/services/selfIteration/review/brief';import { BriefService } from '@/server/services/brief';+import { applyGoalBriefAction } from './_helpers/goalBriefAction';+const briefProcedure = wsCompatProcedure.use(serverDatabase);/**@@ -220,6 +222,14 @@ export const briefRouter = router({const currentBrief = await model.findById(input.id);if (!currentBrief) throw new TRPCError({ code: 'NOT_FOUND', message: 'Brief not found' });+ // A goal brief carries a question the goal owns: answering it here+ // answers the goal, and that write settles the brief.+ if (await applyGoalBriefAction(ctx, currentBrief, input.action, input.comment)) {+ const settled = await model.findById(input.id);+ if (!settled) throw new TRPCError({ code: 'NOT_FOUND', message: 'Brief not found' });+ return { data: settled, message: 'Brief resolved', success: true };+ }+const resolveOptions = {action: input.action,comment: input.comment,diff --git a/apps/server/src/routers/lambda/goal.ts b/apps/server/src/routers/lambda/goal.tsindex 13cd85d1184..6dd6d5b620b 100644--- a/apps/server/src/routers/lambda/goal.ts+++ b/apps/server/src/routers/lambda/goal.ts@@ -781,6 +781,14 @@ export const goalRouter = router({}),/** Clarifications still waiting on the user, grouped by goal. */+ pendingForIsland: goalProcedure.query(async ({ ctx }) => {+ try {+ return { data: await ctx.goalService.pendingForIsland(), success: true };+ } catch (error) {+ mapGoalError(error, 'list pending decisions for');+ }+ }),+pendingClarifications: goalProcedure.query(async ({ ctx }) => {try {return { data: await ctx.goalService.pendingClarifications(), success: true };diff --git a/apps/server/src/services/goal/failureClass.test.ts b/apps/server/src/services/goal/failureClass.test.tsnew file mode 100644index 00000000000..0fe925e271e--- /dev/null+++ b/apps/server/src/services/goal/failureClass.test.ts@@ -0,0 +1,137 @@+import { describe, expect, it } from 'vitest';++import { classifyGoalFailure, parseQuotaResetAt } from './failureClass';++/**+ * Fixtures are the reasons real Goal decision gates were opened with (36 goals,+ * 35 gates). Most of them were machine problems the coordinator put up for+ * judgment; these pin which class each one lands in.+ */+describe('classifyGoalFailure', () => {+ it.each([+ "You've hit your session limit · resets 4:30am (Asia/Shanghai)",+ "You've hit your session limit · resets 2am (Asia/Hong_Kong)",+ "You've hit your session limit · resets 7:40am (Asia/Shanghai)",+ "You've hit your usage limit. Upgrade to Pro or try again at 5:00 PM (America/New_York).",+ "You've hit your weekly limit · resets Oct 9, 5pm (America/New_York)",+ ])('reads %s as a usage limit', (error) => {+ expect(classifyGoalFailure(error).class).toBe('quota');+ });++ it.each([+ '{"error":"TIMEOUT","success":false}',+ "Server discarded the agent's output (operation-not-running): this run is no longer the topic's active operation, so nothing it produced was saved",+ 'Failed to persist tool_result for message msg_8ggMzr8jCOsJL51nwA',+ '{"error":"DEVICE_GATEWAY_ERROR","success":false}',+ 'The device connection service hit an error while starting this run. Nothing started on the device. This is usually temporary — try again in a moment.',+ 'fetch failed: ECONNRESET',+ 'RateLimitExceeded',+ ])('reads %s as transient', (error) => {+ expect(classifyGoalFailure(error).class).toBe('transient');+ });++ it('reads a missing working directory as a setup problem naming the path', () => {+ expect(+ classifyGoalFailure(+ 'Working directory does not exist: /Users/user/CodeProjects/LobeHub/lobehub',+ ),+ ).toEqual({+ class: 'environment',+ problem: { kind: 'workingDirectory', path: '/Users/user/CodeProjects/LobeHub/lobehub' },+ });+ });++ it.each([+ ['Claude Code CLI was not found. Install it and make sure `claude` can be executed.', 'cli'],+ [+ 'The device this agent is bound to is no longer registered with the connection service. Reconnect the device, or bind this agent to another online device.',+ 'device',+ ],+ [+ "The device this agent runs on is offline, so the run couldn't start. Check that the LobeHub desktop app (or the `lh` CLI) is running and connected, then try again.",+ 'device',+ ],+ ['GATEWAY_NOT_CONFIGURED', 'gateway'],+ ['InvalidProviderAPIKey', 'credentials'],+ ])('reads %s as a setup problem (%s)', (error, kind) => {+ expect(classifyGoalFailure(error)).toMatchObject({ class: 'environment', problem: { kind } });+ });++ it.each([+ 'Task attempt budget was exhausted',+ 'Task canceled',+ 'Acceptance review could not judge the delivery from evidence alone; the criterion needs a judge that can act on the system.',+ 'Acceptance review could not run; the delivery passed its verifiers but was never reviewed.',+ 'Delivery did not pass verification.',+ '',+ ])('leaves %s to judgment', (error) => {+ expect(classifyGoalFailure(error).class).toBe('judgment');+ });++ it('attaches the reset time a usage limit names', () => {+ const failedAt = new Date('2026-10-05T19:50:01.285Z');+ expect(+ classifyGoalFailure(+ "You've hit your session limit · resets 4:30am (Asia/Shanghai)",+ failedAt,+ ),+ ).toEqual({ class: 'quota', resetAt: new Date('2026-10-05T20:30:00.000Z') });+ });+});++describe('parseQuotaResetAt', () => {+ it('places a bare wall-clock time in its zone, on the next occurrence after the failure', () => {+ // 03:50 Shanghai → 04:30 the same morning.+ expect(+ parseQuotaResetAt(+ 'resets 4:30am (Asia/Shanghai)',+ new Date('2026-10-05T19:50:00.000Z'),+ )?.toISOString(),+ ).toBe('2026-10-05T20:30:00.000Z');+ // 05:00 Shanghai → 04:30 the next morning.+ expect(+ parseQuotaResetAt(+ 'resets 4:30am (Asia/Shanghai)',+ new Date('2026-10-05T21:00:00.000Z'),+ )?.toISOString(),+ ).toBe('2026-10-06T20:30:00.000Z');+ expect(+ parseQuotaResetAt(+ 'resets 2am (Asia/Hong_Kong)',+ new Date('2026-10-05T12:00:00.000Z'),+ )?.toISOString(),+ ).toBe('2026-10-05T18:00:00.000Z');+ });++ it('honours daylight saving in the named zone', () => {+ // New York is UTC-4 in October.+ expect(+ parseQuotaResetAt(+ "You've hit your weekly limit · resets Oct 9, 5pm (America/New_York)",+ new Date('2026-10-05T12:00:00.000Z'),+ )?.toISOString(),+ ).toBe('2026-10-09T21:00:00.000Z');+ });++ it('reads ISO and relative reset times', () => {+ const failedAt = new Date('2026-10-05T12:00:00.000Z');+ expect(+ parseQuotaResetAt(+ 'Usage limit reached; resets at 2026-10-05T17:00:00Z',+ failedAt,+ )?.toISOString(),+ ).toBe('2026-10-05T17:00:00.000Z');+ expect(+ parseQuotaResetAt(+ 'Usage limit reached, try again in 2 hours 15 minutes',+ failedAt,+ )?.toISOString(),+ ).toBe('2026-10-05T14:15:00.000Z');+ });++ it('gives no reset time when it cannot place one', () => {+ const failedAt = new Date('2026-10-05T12:00:00.000Z');+ expect(parseQuotaResetAt("You've hit your session limit", failedAt)).toBeUndefined();+ expect(parseQuotaResetAt('resets 4:30am (Not/AZone)', failedAt)).toBeUndefined();+ });+});diff --git a/apps/server/src/services/goal/failureClass.ts b/apps/server/src/services/goal/failureClass.tsnew file mode 100644index 00000000000..8ac6c425f64--- /dev/null+++ b/apps/server/src/services/goal/failureClass.ts@@ -0,0 +1,278 @@+import { HETERO_DISPATCH_ERROR_HEADLINES } from '@/server/services/aiAgent/helpers/heteroErrors';++/**+ * What kind of problem stopped a Goal Task, read off the error it was paused with.+ *+ * Most gates the coordinator opened were not questions about the work: a usage+ * limit that reset on its own a few hours later, a run whose output the server+ * discarded, a working directory that does not exist on the device. Every one of+ * them offered the same Retry / Retire choice, and people picked Retry almost+ * every time. Classifying the failure first lets the coordinator wait out what+ * fixes itself, retry what a retry plausibly fixes, and ask a person only for+ * what needs a person — saying what is broken instead of asking them to judge.+ *+ * - `quota` — a provider or CLI usage limit; it resets on its own.+ * - `transient` — a transport or runtime fault a retry plausibly fixes.+ * - `environment` — the setup is broken and a person has to change it.+ * - `judgment` — everything else, including a delivery that really failed.+ */+export type GoalFailureClass = 'environment' | 'judgment' | 'quota' | 'transient';++/** What a person has to fix, for an `environment` failure. */+export type GoalEnvironmentProblem =+ | { kind: 'cli' }+ | { kind: 'credentials' }+ | { kind: 'device' }+ | { kind: 'gateway' }+ | { kind: 'workingDirectory'; path: string };++export interface GoalFailureClassification {+ class: GoalFailureClass;+ /** `environment` only: what is broken. */+ problem?: GoalEnvironmentProblem;+ /** `quota` only: when the limit says it resets, if it says so. */+ resetAt?: Date;+}++const headline = (code: string) => HETERO_DISPATCH_ERROR_HEADLINES[code];++/** Dispatch failures stored either as the raw gateway code or as its headline. */+const matchesDispatchCode = (error: string, codes: readonly string[]) =>+ codes.some(+ (code) => error.includes(code) || (!!headline(code) && error.includes(headline(code))),+ );++const QUOTA_PATTERNS = [+ // Claude Code: "You've hit your session limit · resets 4:30am (Asia/Shanghai)";+ // Codex: "You've hit your usage limit. ... try again at 5:00 PM".+ /\byou'?ve (?:hit|reached) your (?:[\w-]+ )?limit\b/i,+ /\b(?:session|usage|weekly|daily|5-hour|five-hour) limit\b/i,+ /\bQuotaLimitReached\b/,+];++/** The setup is broken; a retry fails the same way until someone changes it. */+const ENVIRONMENT_RULES: Array<{+ pattern: RegExp;+ problem: (match: RegExpExecArray) => GoalEnvironmentProblem;+}> = [+ {+ pattern: /Working directory (?:does not exist|is not a directory)(?: on [^:]+)?: (\S+)/i,+ problem: (match) => ({ kind: 'workingDirectory', path: match[1].replace(/[.,;]+$/, '') }),+ },+ {+ pattern: /\bwas not found\. Install it\b|\bcli_not_found\b/i,+ problem: () => ({ kind: 'cli' }),+ },+ {+ pattern:+ /\b(?:InvalidProviderAPIKey|NoAvailableProvider|InsufficientQuota|InsufficientBudgetForModel|AccountDeactivated|ModelNotFound)\b|not logged in|please run \/login|auth(?:entication)? required/i,+ problem: () => ({ kind: 'credentials' }),+ },+];++/**+ * Device codes a person has to act on. `DEVICE_OFFLINE` / `DEVICE_CHANNEL_UNAVAILABLE`+ * are waited out by the offline schedule first and only reach a person once it+ * is spent, at which point the fix is the same: bring the device back.+ */+const ENVIRONMENT_DEVICE_CODES = [+ 'DEVICE_NOT_FOUND',+ 'DEVICE_OFFLINE',+ 'DEVICE_CHANNEL_UNAVAILABLE',+ // The device did not answer, so whether the run started is unknown: a person+ // checks the device before anything is started again.+ 'DEVICE_RESPONSE_TIMEOUT',+];+const ENVIRONMENT_GATEWAY_CODES = ['DEVICE_GATEWAY_UNAUTHORIZED', 'GATEWAY_NOT_CONFIGURED'];++/**+ * Transport and runtime faults seen ending real Goal runs, each of which a fresh+ * attempt got past: the gateway timing out, the server discarding a run's output+ * because another operation took over its topic, a tool result that did not+ * persist, the device connection service erroring before anything started.+ */+const TRANSIENT_DISPATCH_CODES = [+ 'DEVICE_GATEWAY_ERROR',+ 'DEVICE_GATEWAY_UNREACHABLE',+ 'DEVICE_GATEWAY_RATE_LIMITED',+];+const TRANSIENT_PATTERNS = [+ /"error"\s*:\s*"TIMEOUT"/,+ /\boperation-not-running\b|\bstale-operation\b/,+ /\bFailed to persist tool_result\b/i,+ /\b(?:RateLimitExceeded|ProviderServiceUnavailable|ProviderNetworkError|GatewayTimeout)\b/,+ /ECONNRESET|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|ENOTFOUND|fetch failed|network error|socket hang up|service unavailable|bad gateway|gateway timeout|\boverloaded\b|\b50[234]\b/i,+];++export const classifyGoalFailure = (+ error: string | null | undefined,+ /** When the failure happened; a wall-clock reset time is read relative to it. */+ failedAt: Date = new Date(),+): GoalFailureClassification => {+ const text = error?.trim();+ if (!text) return { class: 'judgment' };++ if (QUOTA_PATTERNS.some((pattern) => pattern.test(text))) {+ const resetAt = parseQuotaResetAt(text, failedAt);+ return { class: 'quota', ...(resetAt ? { resetAt } : {}) };+ }++ for (const rule of ENVIRONMENT_RULES) {+ const match = rule.pattern.exec(text);+ if (match) return { class: 'environment', problem: rule.problem(match) };+ }+ if (matchesDispatchCode(text, ENVIRONMENT_GATEWAY_CODES))+ return { class: 'environment', problem: { kind: 'gateway' } };+ if (matchesDispatchCode(text, ENVIRONMENT_DEVICE_CODES))+ return { class: 'environment', problem: { kind: 'device' } };++ if (+ matchesDispatchCode(text, TRANSIENT_DISPATCH_CODES) ||+ TRANSIENT_PATTERNS.some((pattern) => pattern.test(text))+ )+ return { class: 'transient' };++ return { class: 'judgment' };+};++/** Machine-class failures are the coordinator's to recover or to explain, not to put up for judgment. */+export const isMachineFailureClass = (failureClass: GoalFailureClass): boolean =>+ failureClass !== 'judgment';++// ---------------------------------------------------------------------------+// Reset time+// ---------------------------------------------------------------------------++const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];++const ISO_RESET =+ /\b(?:resets?|try again|retry)\s+(?:at\s+|after\s+)?(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:?\d{2}))/i;+const RELATIVE_RESET =+ /\b(?:try again|retry|resets?)\s+in\s+((?:\d+(?:\.\d+)?\s*(?:seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d)\b[\s,]*(?:and\s+)?)+)/i;+const RELATIVE_PART =+ /(\d+(?:\.\d+)?)\s*(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d)\b/gi;+const WALL_CLOCK_RESET =+ /\b(?:resets?|try again at)\s+(?:(?:on\s+)?([A-Z]{3,9})\.?\s+(\d{1,2}),?\s+(?:at\s+)?)?(\d{1,2})(?::(\d{2}))?\s*(?:(am|pm)\s*)?\(([^()]+)\)/i;++const UNIT_MS: Record<string, number> = { d: 86_400_000, h: 3_600_000, m: 60_000, s: 1000 };++const unitMs = (unit: string) => {+ const lower = unit.toLowerCase();+ if (lower.startsWith('d')) return UNIT_MS.d;+ if (lower.startsWith('h')) return UNIT_MS.h;+ if (lower.startsWith('m')) return UNIT_MS.m;+ return UNIT_MS.s;+};++const zonedParts = (at: number, timeZone: string) => {+ const parts = new Intl.DateTimeFormat('en-US', {+ day: '2-digit',+ hour: '2-digit',+ hourCycle: 'h23',+ minute: '2-digit',+ month: '2-digit',+ second: '2-digit',+ timeZone,+ year: 'numeric',+ }).formatToParts(new Date(at));+ const value = (type: Intl.DateTimeFormatPartTypes) =>+ Number(parts.find((part) => part.type === type)?.value);+ return {+ day: value('day'),+ hour: value('hour'),+ minute: value('minute'),+ month: value('month'),+ second: value('second'),+ year: value('year'),+ };+};++const zoneOffsetMs = (at: number, timeZone: string) => {+ const p = zonedParts(at, timeZone);+ return (+ Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second) - Math.floor(at / 1000) * 1000+ );+};++/** The instant a wall-clock time in `timeZone` names; the second pass settles DST edges. */+const zonedWallClockToEpoch = (+ wall: { day: number; hour: number; minute: number; month: number; year: number },+ timeZone: string,+) => {+ const guess = Date.UTC(wall.year, wall.month - 1, wall.day, wall.hour, wall.minute);+ const first = guess - zoneOffsetMs(guess, timeZone);+ return guess - zoneOffsetMs(first, timeZone);+};++const parseWallClockReset = (match: RegExpExecArray, failedAt: Date): Date | undefined => {+ const [, rawMonth, rawDay, rawHour, rawMinute, meridiem, rawZone] = match;+ const timeZone = rawZone.trim();+ let hour = Number(rawHour);+ const minute = rawMinute ? Number(rawMinute) : 0;+ if (minute > 59) return;+ if (meridiem) {+ if (hour < 1 || hour > 12) return;+ hour = (hour % 12) + (meridiem.toLowerCase() === 'pm' ? 12 : 0);+ } else if (hour > 23) return;++ try {+ const now = failedAt.getTime();+ const today = zonedParts(now, timeZone);+ if (rawMonth) {+ const month = MONTHS.indexOf(rawMonth.slice(0, 3).toLowerCase()) + 1;+ const day = Number(rawDay);+ if (!month || day < 1 || day > 31) return;+ let at = zonedWallClockToEpoch({ day, hour, minute, month, year: today.year }, timeZone);+ // "resets Jan 2" read on Dec 30 is next year's.+ if (at <= now)+ at = zonedWallClockToEpoch({ day, hour, minute, month, year: today.year + 1 }, timeZone);+ return new Date(at);+ }+ // A bare time is the next time the clock in that zone reads it.+ let at = zonedWallClockToEpoch({ ...today, hour, minute }, timeZone);+ if (at <= now) {+ const tomorrow = new Date(Date.UTC(today.year, today.month - 1, today.day + 1));+ at = zonedWallClockToEpoch(+ {+ day: tomorrow.getUTCDate(),+ hour,+ minute,+ month: tomorrow.getUTCMonth() + 1,+ year: tomorrow.getUTCFullYear(),+ },+ timeZone,+ );+ }+ return new Date(at);+ } catch {+ // An unknown IANA zone: the text gave a time nobody can place.+ return;+ }+};++/**+ * When a usage-limit message says the limit lifts, relative to when it failed.+ * Handles "resets 4:30am (Asia/Shanghai)", "resets Oct 9, 5pm (America/New_York)",+ * "resets at 2026-10-06T04:30:00Z", "try again at 5:00 PM (UTC)" and+ * "try again in 2 hours 13 minutes". A wall-clock time without a zone cannot be+ * placed, so it reads as no reset time.+ */+export const parseQuotaResetAt = (text: string, failedAt: Date): Date | undefined => {+ const iso = ISO_RESET.exec(text);+ if (iso) {+ const at = Date.parse(iso[1]);+ return Number.isNaN(at) ? undefined : new Date(at);+ }++ const relative = RELATIVE_RESET.exec(text);+ if (relative) {+ let total = 0;+ for (const part of relative[1].matchAll(RELATIVE_PART))+ total += Number(part[1]) * unitMs(part[2]);+ return total > 0 ? new Date(failedAt.getTime() + total) : undefined;+ }++ const wall = WALL_CLOCK_RESET.exec(text);+ if (wall) return parseWallClockReset(wall, failedAt);+ return undefined;+};diff --git a/apps/server/src/services/goal/goalBriefs.test.ts b/apps/server/src/services/goal/goalBriefs.test.tsnew file mode 100644index 00000000000..2c2e6e65189--- /dev/null+++ b/apps/server/src/services/goal/goalBriefs.test.ts@@ -0,0 +1,344 @@+// @vitest-environment node+import { randomUUID } from 'node:crypto';++import { GOAL_BRIEF_TRIGGER } from '@lobechat/const/goal';+import { and, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '@/database/core/getTestDB';+import { BriefModel } from '@/database/models/brief';+import { GoalModel } from '@/database/models/goal';+import { TaskModel } from '@/database/models/task';+import {+ acceptances,+ agents,+ briefs,+ goalEdges,+ goalEvents,+ goalNodeDecisions,+ goalNodes,+ goals,+ tasks,+ taskTopics,+ users,+ userSettings,+ workspaces,+} from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { applyGoalBriefAction } from '@/server/routers/lambda/_helpers/goalBriefAction';++import { GoalBriefService } from './goalBriefs';+import { GoalService } from './index';+import * as scheduler from './scheduler';++const serverDB: LobeChatDatabase = await getTestDB();+const userId = 'goal-brief-test-user';+const agentId = 'goal-brief-test-agent';++beforeEach(async () => {+ await serverDB.insert(users).values({ id: userId }).onConflictDoNothing();+ await serverDB.insert(agents).values({ id: agentId, userId }).onConflictDoNothing();+ vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();+});++afterEach(async () => {+ vi.restoreAllMocks();+ await serverDB.delete(briefs);+ await serverDB.delete(acceptances);+ await serverDB.delete(goalNodeDecisions);+ await serverDB.delete(goalEdges);+ await serverDB.delete(goalEvents);+ await serverDB.delete(goalNodes);+ await serverDB.delete(goals);+ await serverDB.delete(taskTopics);+ await serverDB.delete(tasks);+ await serverDB.delete(agents);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+});++const goalBriefs = () =>+ serverDB.select().from(briefs).where(eq(briefs.trigger, GOAL_BRIEF_TRIGGER));++/** A goal parked on the coordinator's gate for its one failed Task. */+const gatedGoal = async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Risky task'], title: 'Gate goal' });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });+ expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');+ const [decision] = (await service.graph(graph.goal.id)).decisions;+ return { decision, goalId: graph.goal.id, service, taskId: created.taskId!, taskModel };+};++describe('goal decision briefs', () => {+ it('tells the inbox when a gate opens, and stops once the goal page answers it', async () => {+ const { decision, goalId, service } = await gatedGoal();++ const [brief] = await goalBriefs();+ expect(brief).toMatchObject({+ priority: 'urgent',+ resolvedAt: null,+ type: 'decision',+ metadata: {+ goal: {+ decisionId: decision.id,+ goalId,+ goalTitle: 'Gate goal',+ kind: 'decision',+ // The inbox draws the advised answer as its primary button.+ recommendedAction: 'retry',+ },+ },+ });+ // The advised answer leads, so the obvious click is the recommended one.+ expect(brief.actions!.map((action: { key: string }) => action.key)).toEqual([+ 'retry',+ 'retire',+ 'openGoal',+ ]);++ await service.decide(goalId, decision.id, 'retire', 'Not worth it');++ const [settled] = await goalBriefs();+ expect(settled).toMatchObject({ resolvedAction: 'retire', resolvedComment: 'Not worth it' });+ expect(settled.resolvedAt).not.toBeNull();+ });++ it('answers the gate from the inbox and carries the note into the next attempt', async () => {+ const { decision, goalId, service, taskId, taskModel } = await gatedGoal();+ const [brief] = await goalBriefs();++ const applied = await applyGoalBriefAction(+ { serverDB, userId } as never,+ brief,+ 'retry',+ 'Use the staging database this time',+ );++ expect(applied).toBe(true);+ const after = await service.graph(goalId);+ expect(after.decisions.find((d) => d.id === decision.id)).toMatchObject({+ resolvedOptionId: 'retry',+ status: 'resolved',+ });+ expect((await taskModel.findById(taskId))!.status).toBe('backlog');+ const comments = await taskModel.getComments(taskId);+ expect(comments.at(-1)!.content).toContain('Guidance: Use the staging database this time');+ expect(scheduler.scheduleGoalAdvance).toHaveBeenCalledWith(+ expect.objectContaining({ goalId, trigger: 'decide' }),+ );+ expect((await goalBriefs())[0].resolvedAt).not.toBeNull();+ });++ it('adds nothing to the next attempt for a bare retry', async () => {+ const { decision, goalId, service, taskId, taskModel } = await gatedGoal();+ await service.decide(goalId, decision.id, 'retry');+ expect(await taskModel.getComments(taskId)).toHaveLength(0);+ });++ it('leaves an inbox-only action to the brief', async () => {+ await gatedGoal();+ const [brief] = await goalBriefs();+ expect(await applyGoalBriefAction({ serverDB, userId } as never, brief, 'openGoal')).toBe(+ false,+ );+ });+});++describe('machine gate briefs', () => {+ it("says the retry follows a fix, in the reader's words", async () => {+ await serverDB+ .insert(userSettings)+ .values({ general: { responseLanguage: 'zh-CN' }, id: userId })+ .onConflictDoNothing();+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Machine goal' });+ const goal = (await serverDB.query.goals.findFirst({ where: eq(goals.id, graph.goal.id) }))!;++ await new GoalBriefService(serverDB, userId).openDecision(goal, {+ decisionId: '00000000-0000-4000-8000-000000000001',+ options: [+ { id: 'retry', label: 'I fixed it — retry' },+ { id: 'retire', label: 'Retire task' },+ ],+ question:+ 'Setup problem: Working directory does not exist: /tmp/x. Create /tmp/x on the device the agent runs on, or point the agent at a working directory that exists there. Fix it, then retry or retire this task node?',+ recommendedOptionId: 'retry',+ });++ const [brief] = await goalBriefs();+ expect(brief.actions![0]).toMatchObject({ key: 'retry', label: '已修好,重试' });+ expect(brief.summary).toContain('工作目录 /tmp/x');+ expect(brief.summary).toContain('推荐:已修好,重试');+ });+});++describe('goal progress', () => {+ it('records the finding as the agent that did the work, without an inbox brief', async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({ tasks: ['Survey the market'], title: 'Office goal' });+ const created = await service.tick(graph.goal.id);+ await taskModel.update(created.taskId!, { assigneeAgentId: agentId });+ await serverDB.insert(taskTopics).values({+ handoff: {+ content: 'I surveyed nine products and wrote the doc.',+ keyFindings: ['九款产品里七款走 OOXML 直写', '协作编辑都靠 CRDT'],+ nextAction: '对比两种编辑内核的成本',+ summary: '市面方案分成直写文件和在线内核两类。',+ title: '办公套件实现路线有两类',+ },+ operationId: 'op-delivered',+ seq: 1,+ status: 'completed',+ taskId: created.taskId!,+ userId,+ });+ await taskModel.updateStatus(created.taskId!, 'completed');++ await service.tick(graph.goal.id);++ const finding = (await service.graph(graph.goal.id)).nodes.find((n) => n.kind === 'finding');+ expect(finding).toMatchObject({+ createdByAgentId: agentId,+ createdByUserId: null,+ description: 'I surveyed nine products and wrote the doc.',+ title: '办公套件实现路线有两类',+ });+ // A finding is read on the goal page; it does not become an inbox brief.+ expect(await goalBriefs()).toHaveLength(0);+ });+});++const acceptanceRow = async (+ values: { status?: 'accepted' | 'pending' | 'rejected'; workspaceId?: string } = {},+) => {+ const [row] = await serverDB+ .insert(acceptances)+ .values({ subjectId: randomUUID(), subjectType: 'standalone', userId, ...values })+ .returning();+ return row.id;+};++describe('goal sign-off briefs', () => {+ it('asks once per acceptance and stops once it is signed elsewhere', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Signed goal' });+ const goal = (await serverDB.query.goals.findFirst({ where: eq(goals.id, graph.goal.id) }))!;+ const goalBriefService = new GoalBriefService(serverDB, userId);+ const acceptanceId = await acceptanceRow();++ await goalBriefService.openSignOff(goal, acceptanceId);+ await goalBriefService.openSignOff(goal, acceptanceId);++ expect(await goalBriefService.listOpenSignOffs()).toEqual([+ expect.objectContaining({ acceptanceId, goalId: goal.id, goalTitle: 'Signed goal' }),+ ]);++ await goalBriefService.settleSignOff(acceptanceId, 'signOff');++ expect(await goalBriefService.listOpenSignOffs()).toEqual([]);+ const [brief] = await serverDB+ .select()+ .from(briefs)+ .where(and(eq(briefs.trigger, GOAL_BRIEF_TRIGGER), eq(briefs.userId, userId)));+ expect(brief.resolvedAction).toBe('signOff');+ });++ it('asks nothing for an acceptance the owner has already decided', async () => {+ const service = new GoalService(serverDB, userId);+ const graph = await service.create({ title: 'Signed early' });+ const goal = (await serverDB.query.goals.findFirst({ where: eq(goals.id, graph.goal.id) }))!;+ const goalBriefService = new GoalBriefService(serverDB, userId);++ await goalBriefService.openSignOff(goal, await acceptanceRow({ status: 'accepted' }));+ await goalBriefService.openSignOff(goal, await acceptanceRow({ status: 'rejected' }));++ expect(await goalBriefs()).toHaveLength(0);+ });++ it('keeps a workspace sign-off in that workspace', async () => {+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: userId, slug: 'goal-brief-ws' })+ .returning();+ const service = new GoalService(serverDB, userId, workspace.id);+ const graph = await service.create({ title: 'Workspace goal' });+ const goal = (await serverDB.query.goals.findFirst({ where: eq(goals.id, graph.goal.id) }))!;+ const acceptanceId = await acceptanceRow({ workspaceId: workspace.id });+ const inWorkspace = new GoalBriefService(serverDB, userId, workspace.id);+ const personal = new GoalBriefService(serverDB, userId);++ await inWorkspace.openSignOff(goal, acceptanceId);++ expect(await personal.listOpenSignOffs()).toEqual([]);+ await personal.settleSignOff(acceptanceId, 'signOff');+ expect(await inWorkspace.listOpenSignOffs()).toEqual([+ expect.objectContaining({ acceptanceId, goalTitle: 'Workspace goal' }),+ ]);++ await inWorkspace.settleSignOff(acceptanceId, 'signOff');+ expect(await inWorkspace.listOpenSignOffs()).toEqual([]);+ });+});++describe('pending gates in a shared workspace', () => {+ // Every member sees a workspace goal, but its gate is asked of one person.+ it('lists a gate only for the member it was asked of', async () => {+ const memberId = 'goal-brief-test-member';+ await serverDB.insert(users).values({ id: memberId }).onConflictDoNothing();+ const [workspace] = await serverDB+ .insert(workspaces)+ .values({ name: 'ws', primaryOwnerId: userId, slug: 'goal-brief-gate-ws' })+ .returning();+ const service = new GoalService(serverDB, userId, workspace.id);+ const taskModel = new TaskModel(serverDB, userId, workspace.id);+ const graph = await service.create({ tasks: ['Risky task'], title: 'Shared goal' });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'Verifier rejected output' });+ expect((await service.tick(graph.goal.id)).outcome).toBe('waiting_human');++ const asked = await new GoalModel(serverDB, userId, workspace.id).listPendingDecisions();+ const member = await new GoalModel(serverDB, memberId, workspace.id).listPendingDecisions();++ expect(asked).toEqual([expect.objectContaining({ goalId: graph.goal.id })]);+ expect(member).toEqual([]);+ });+});++describe('goal sign-off on achievement', () => {+ const achieveGoal = async () => {+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ requirement: 'A short report with evidence',+ tasks: ['Write the report'],+ title: 'Sign me off',+ });+ const created = await service.tick(graph.goal.id);+ await taskModel.updateStatus(created.taskId!, 'completed');+ await service.tick(graph.goal.id);+ await service.tick(graph.goal.id);+ const acceptanceTask = await service.tick(graph.goal.id);+ await taskModel.updateStatus(acceptanceTask.taskId!, 'completed');+ await service.tick(graph.goal.id);+ return { goalId: graph.goal.id, service };+ };++ // Nothing ticks an achieved goal again, so a sign-off that failed to write+ // after the goal turned terminal would never be asked.+ it('keeps the goal open and retries when the sign-off cannot be written', async () => {+ const { goalId, service } = await achieveGoal();+ vi.spyOn(BriefModel.prototype, 'create').mockRejectedValueOnce(new Error('db down'));++ await expect(service.tick(goalId)).rejects.toThrow('db down');+ expect((await service.graph(goalId)).goal.status).not.toBe('achieved');++ expect(await service.tick(goalId)).toMatchObject({ outcome: 'achieved' });+ expect(await new GoalBriefService(serverDB, userId).listOpenSignOffs()).toEqual([+ expect.objectContaining({ goalId, goalTitle: 'Sign me off' }),+ ]);+ });+});diff --git a/apps/server/src/services/goal/goalBriefs.ts b/apps/server/src/services/goal/goalBriefs.tsnew file mode 100644index 00000000000..9ad499c7dc9--- /dev/null+++ b/apps/server/src/services/goal/goalBriefs.ts@@ -0,0 +1,309 @@+import { GOAL_BRIEF_TRIGGER, GOAL_CLARIFICATION_OPTION } from '@lobechat/const/goal';+import type { BriefAction, BriefGoalMetadata, GoalDecisionOption, GoalItem } from '@lobechat/types';+import { coordinatorGateReason, coordinatorReasonCopy } from '@lobechat/utils/goalCopy';+import { and, eq, isNull, sql } from 'drizzle-orm';++import { BriefModel } from '@/database/models/brief';+import { acceptances, briefs } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { translation } from '@/libs/i18n/serverTranslation';+import { SystemAgentService } from '@/server/services/systemAgent';++/** Option ids the coordinator writes; anything else is the main Agent's or the planner's. */+const COORDINATOR_OPTION_KEYS: Record<string, string> = {+ fail: 'goalProcess.gate.option.fail',+ retire: 'goalProcess.gate.option.retire',+ retry: 'goalProcess.gate.option.retry',+ [GOAL_CLARIFICATION_OPTION.assume]: 'goalProcess.gate.option.assume',+};++/** How the coordinator words a machine gate's question (see `openFailureDecisionLocked`). */+const MACHINE_GATE_TAIL = /Fix it, then retry or retire this task node\?$/;++const SUMMARY_LIMIT = 600;++const DECIDED_ACCEPTANCE_STATUSES = new Set<string>(['accepted', 'closed', 'rejected']);++const signOffFor = (acceptanceId: string) =>+ sql`${briefs.metadata} -> 'goal' ->> 'signOffAcceptanceId' = ${acceptanceId}`;++const clip = (text: string, limit = SUMMARY_LIMIT) =>+ text.length > limit ? `${text.slice(0, limit - 1).trimEnd()}…` : text;++/** Root-relative so the inbox routes it inside the SPA, workspace prefix included. */+export const goalPagePath = (goal: Pick<GoalItem, 'agentId' | 'id'>) =>+ goal.agentId ? `/agent/${goal.agentId}/goal/${goal.id}` : `/goal/${goal.id}`;++export interface GoalSignOffRequest {+ acceptanceId: string;+ agentId: string | null;+ briefId: string;+ createdAt: Date;+ goalId: string;+ goalTitle: string;+}++interface DecisionInput {+ decisionId: string;+ options?: GoalDecisionOption[] | null;+ question: string;+ recommendedOptionId?: string | null;+}++/**+ * The goal's half of the inbox. A gate the coordinator opens and the sign-off+ * a finished goal waits for are written as briefs, so the person hears about them wherever they are instead of only+ * when they happen to open the goal page.+ *+ * Gate writes are best-effort: a brief is the notification, never the state —+ * the gate exists whether or not its brief could be written, and the goal page+ * still asks it. The sign-off is the exception: once the goal is achieved no+ * other surface asks for it, so `openSignOff` throws and its caller retries.+ */+export class GoalBriefService {+ private briefModel: BriefModel;+ private db: LobeChatDatabase;+ private userId: string;+ private workspaceId?: string;++ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ this.db = db;+ this.userId = userId;+ this.workspaceId = workspaceId;+ this.briefModel = new BriefModel(db, userId, workspaceId);+ }++ /** A failure gate, or a question the main Agent escalated with its own options. */+ openDecision = async (goal: GoalItem, input: DecisionInput) =>+ this.safely('openDecision', async () => {+ const { t } = await this.chatCopy();+ const { t: tHome } = await this.homeCopy();+ const reason = coordinatorGateReason(input.question) ?? input.question;+ const reasonCopy = coordinatorReasonCopy(reason);+ const localizedReason = reasonCopy ? t(reasonCopy.key, reasonCopy.params) : reason;+ // The machine gate's retry means "I fixed the setup", not "try again".+ const machine = MACHINE_GATE_TAIL.test(input.question);+ const label = (option: GoalDecisionOption) => {+ const key =+ machine && option.id === 'retry'+ ? 'goalProcess.gate.option.fixedRetry'+ : COORDINATOR_OPTION_KEYS[option.id];+ return key ? t(key) : option.label;+ };+ const recommended = input.options?.find((o) => o.id === input.recommendedOptionId);++ const actions: BriefAction[] = [+ ...(input.options ?? []).map((option): BriefAction => ({+ key: option.id,+ label: label(option),+ // The planner's free answer is the note itself.+ type: option.id === GOAL_CLARIFICATION_OPTION.answer ? 'comment' : 'resolve',+ })),+ {+ key: 'openGoal',+ label: tHome('brief.action.openGoal'),+ type: 'link',+ url: goalPagePath(goal),+ },+ ];+ // The inbox card leads with its first non-comment action; keep the+ // recommended answer there so the obvious click is the advised one.+ if (recommended) {+ actions.sort((a, b) => Number(b.key === recommended.id) - Number(a.key === recommended.id));+ }++ await this.create(goal, {+ actions,+ metadata: {+ decisionId: input.decisionId,+ kind: 'decision',+ ...(recommended ? { recommendedAction: recommended.id } : {}),+ },+ priority: 'urgent',+ summary: clip(+ recommended+ ? `${localizedReason}\n\n${tHome('brief.goal.recommended', { option: label(recommended) })}`+ : localizedReason,+ ),+ title: tHome('brief.goal.decision.title', { goal: goal.title }),+ type: 'decision',+ });+ });++ /**+ * A clarification round is one form on the goal page, so it is one brief —+ * answering question by question from the inbox would re-plan on half of them.+ */+ openClarification = async (goal: GoalItem, decisionIds: string[], questions: string[]) =>+ this.safely('openClarification', async () => {+ const { t: tHome } = await this.homeCopy();+ await this.create(goal, {+ actions: [+ {+ key: 'answer',+ label: tHome('brief.action.answer'),+ type: 'link',+ url: goalPagePath(goal),+ },+ ],+ // The round settles with its last question; any one id keeps the+ // brief tied to it, and the first is the one asked first.+ metadata: { decisionId: decisionIds[0], kind: 'decision' },+ priority: 'urgent',+ summary: clip(questions.map((q, i) => `${i + 1}. ${q}`).join('\n')),+ title: tHome('brief.goal.clarify.title', { goal: goal.title }),+ type: 'decision',+ });+ });++ /**+ * The goal-level acceptance passed: the owner signs the result off or sends it back.+ *+ * The acceptance row is locked while the brief is written, so a decision that+ * lands meanwhile either is seen here (and nothing is asked) or waits for this+ * brief to exist and then settles it — never an open ask for a decided result.+ * Throws on failure: the caller opens it before the goal turns terminal, so+ * the next tick retries.+ */+ openSignOff = async (goal: GoalItem, acceptanceId: string): Promise<void> => {+ const { t: tHome } = await this.homeCopy();+ await this.db.transaction(async (tx) => {+ const [acceptance] = await tx+ .select({ status: acceptances.status })+ .from(acceptances)+ .where(and(eq(acceptances.id, acceptanceId), eq(acceptances.userId, this.userId)))+ .for('update');+ // Already decided — accepted, sent back or closed — nothing is left+ // to sign, and the card could never be answered.+ if (!acceptance || DECIDED_ACCEPTANCE_STATUSES.has(acceptance.status)) return;++ const briefModel = new BriefModel(tx, this.userId, this.workspaceId);+ const existing = await tx+ .select({ id: briefs.id })+ .from(briefs)+ .where(and(briefModel.ownership(), isNull(briefs.resolvedAt), signOffFor(acceptanceId)))+ .limit(1);+ if (existing.length > 0) return;++ await this.create(+ goal,+ {+ actions: [+ { key: 'signOff', label: tHome('brief.action.signOff'), type: 'resolve' },+ {+ key: 'requestChanges',+ label: tHome('brief.action.requestChanges'),+ type: 'comment',+ },+ {+ key: 'openGoal',+ label: tHome('brief.action.openGoal'),+ type: 'link',+ url: goalPagePath(goal),+ },+ ],+ metadata: {+ kind: 'signOff',+ recommendedAction: 'signOff',+ signOffAcceptanceId: acceptanceId,+ },+ priority: 'normal',+ summary: tHome('brief.goal.signOff.summary'),+ title: tHome('brief.goal.signOff.title', { goal: goal.title }),+ type: 'decision',+ },+ briefModel,+ );+ });+ };++ /** The sign-off was given or refused somewhere else — the acceptance itself, the goal page. */+ settleSignOff = async (acceptanceId: string, action: string, comment?: string) =>+ this.safely('settleSignOff', async () => {+ await this.db+ .update(briefs)+ .set({ resolvedAction: action, resolvedAt: new Date(), resolvedComment: comment ?? null })+ .where(+ and(this.briefModel.ownership(), isNull(briefs.resolvedAt), signOffFor(acceptanceId)),+ );+ });++ /** Goals waiting on the person's sign-off — the island asks for these too. */+ listOpenSignOffs = async (): Promise<GoalSignOffRequest[]> => {+ const rows = await this.db+ .select({+ agentId: briefs.agentId,+ briefId: briefs.id,+ createdAt: briefs.createdAt,+ metadata: briefs.metadata,+ })+ .from(briefs)+ .where(+ and(+ this.briefModel.ownership(),+ eq(briefs.trigger, GOAL_BRIEF_TRIGGER),+ isNull(briefs.resolvedAt),+ sql`${briefs.metadata} -> 'goal' ->> 'kind' = 'signOff'`,+ ),+ )+ .orderBy(briefs.createdAt);+ return rows.flatMap((row) => {+ const goal = row.metadata?.goal;+ if (!goal?.signOffAcceptanceId) return [];+ return [+ {+ acceptanceId: goal.signOffAcceptanceId,+ agentId: row.agentId,+ briefId: row.briefId,+ createdAt: row.createdAt,+ goalId: goal.goalId,+ goalTitle: goal.goalTitle,+ },+ ];+ });+ };++ private create = async (+ goal: GoalItem,+ input: {+ actions: BriefAction[];+ metadata: Omit<BriefGoalMetadata, 'goalId' | 'goalTitle'>;+ priority: 'info' | 'normal' | 'urgent';+ summary: string;+ title: string;+ type: 'decision';+ },+ briefModel = this.briefModel,+ ) =>+ briefModel.create({+ actions: input.actions,+ agentId: goal.agentId,+ metadata: { goal: { ...input.metadata, goalId: goal.id, goalTitle: goal.title } },+ priority: input.priority,+ summary: input.summary,+ title: input.title,+ trigger: GOAL_BRIEF_TRIGGER,+ type: input.type,+ });++ private locale?: Promise<string>;++ private readLocale = () => {+ this.locale ??= new SystemAgentService(this.db, this.userId, this.workspaceId)+ .getUserLocale()+ .catch(() => 'en-US');+ return this.locale;+ };++ private chatCopy = async () => translation('chat', await this.readLocale());++ private homeCopy = async () => translation('home', await this.readLocale());++ private safely = async (label: string, run: () => Promise<void>) => {+ try {+ await run();+ } catch (error) {+ console.error(`[GoalBriefService.${label}]`, error);+ }+ };+}diff --git a/apps/server/src/services/goal/index.test.ts b/apps/server/src/services/goal/index.test.tsindex 9c054fbe8bc..3580624c667 100644--- a/apps/server/src/services/goal/index.test.ts+++ b/apps/server/src/services/goal/index.test.ts@@ -1,5 +1,10 @@// @vitest-environment node-import { DEVICE_OFFLINE_RUN_STATUS, GOAL_COORDINATOR_ACTOR_ID } from '@lobechat/const/goal';+import {+ DEVICE_OFFLINE_RUN_STATUS,+ GOAL_COORDINATOR_ACTOR_ID,+ GOAL_MACHINE_GATE_TITLE,+ QUOTA_LIMITED_RUN_STATUS,+} from '@lobechat/const/goal';import type { ChatTopicMetadata } from '@lobechat/types';import * as goalGraphUtils from '@lobechat/utils/goalGraph';import { eq, sql } from 'drizzle-orm';@@ -48,8 +53,10 @@ import {} from './decideNextMove';import { GoalExplorationPlanner } from './explorationPlanner';import { GoalService } from './index';+import { MAX_QUOTA_RETRIES } from './machineRecovery';import { DEVICE_OFFLINE_GATE_REASON, VERIFY_SETTLE_GRACE_MS } from './recoveryPolicy';import * as scheduler from './scheduler';+import { LocalGoalScheduler } from './scheduler/impls';import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';import type { GoalTickObservation } from './traceObservation';@@ -3932,6 +3939,37 @@ describe('GoalService', () => {expect(after.goal.config?.supervisorState?.incidents ?? []).toHaveLength(0);});+ // The refusal's text names the limit, so its runs are uncharged and the+ // attempt budget cannot end a window that keeps refusing. The uncharged+ // quota schedule does: once spent, a person is asked instead of another wait.+ it('stops waiting once the uncharged usage-limit retries are spent', async () => {+ const schedule = vi.spyOn(scheduler, 'scheduleGoalAdvance').mockResolvedValue();+ const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask');+ const { created, graph, service } = await setup(+ 'Session limit keeps refusing',+ Date.now() + 2 * 60 * 60 * 1000,+ );+ for (let seq = 1; seq <= MAX_QUOTA_RETRIES + 1; seq++) {+ const topicId = `tpc_quota_${seq}`;+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB.insert(taskTopics).values({+ seq,+ status: QUOTA_LIMITED_RUN_STATUS,+ taskId: created.taskId!,+ topicId,+ updatedAt: new Date(Date.now() - (MAX_QUOTA_RETRIES + 1 - seq) * 60 * 1000),+ userId,+ });+ }++ const gated = await service.tick(graph.goal.id);++ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ expect(runSpy).not.toHaveBeenCalled();+ expect(schedule.mock.calls.filter(([params]) => params.trigger === 'wake')).toHaveLength(0);+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(1);+ });+it('retries through ordinary recovery once the window has reset', async () => {const runSpy = vi.spyOn(TaskRunnerService.prototype, 'runTask')@@ -4232,3 +4270,149 @@ describe('GoalService', () => {expect(next).toMatchObject({ nodeId: dependent.id, outcome: 'advanced' });});});++/**+ * Most real gates were machine problems pushed onto a person: a usage limit that+ * reset on its own hours later, a working directory missing on the device. These+ * pin that the coordinator waits out the first and asks about the second as a+ * machine gate rather than a judgment.+ */+describe('GoalService machine failures', () => {+ const MINUTE = 60 * 1000;+ const SESSION_LIMIT = "You've hit your session limit · resets 4:30am (Asia/Shanghai)";+ // 03:51 in Shanghai, a minute after the run hit the limit.+ const FAILED_AT = new Date('2026-10-05T19:50:01.000Z');++ const setup = async (title: string) => {+ const runSpy = vi+ .spyOn(TaskRunnerService.prototype, 'runTask')+ .mockResolvedValue({ operationId: 'op-retry', success: true } as never);+ const scheduleSpy = vi+ .spyOn(LocalGoalScheduler.prototype, 'scheduleAdvance')+ .mockResolvedValue('scheduled');+ const service = new GoalService(serverDB, userId);+ const taskModel = new TaskModel(serverDB, userId);+ const graph = await service.create({+ // One attempt: a limited run that spent it would gate the retry.+ config: { recovery: { maxAttemptsPerTask: 1 } },+ tasks: ['Run on Claude Code'],+ title,+ });+ const created = await service.tick(graph.goal.id);+ runSpy.mockClear();+ return { created, graph, runSpy, scheduleSpy, service, taskModel };+ };++ const failRun = async (taskId: string, status: string, error: string, at: Date) => {+ const topicId = `tpc_machine_${taskId}`;+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB+ .insert(taskTopics)+ .values({ seq: 1, status, taskId, topicId, updatedAt: at, userId });+ const taskModel = new TaskModel(serverDB, userId);+ await taskModel.update(taskId, { totalTopics: 1 });+ await taskModel.updateStatus(taskId, 'paused', { error });+ await serverDB.update(tasks).set({ updatedAt: at }).where(eq(tasks.id, taskId));+ };++ afterEach(() => {+ vi.useRealTimers();+ });++ it('waits for a usage limit to reset, then retries without charging the attempt', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true, toFake: ['Date'] });+ vi.setSystemTime(new Date(FAILED_AT.getTime() + MINUTE));+ const { created, graph, runSpy, scheduleSpy, service } = await setup('Session limit');+ await failRun(created.taskId!, QUOTA_LIMITED_RUN_STATUS, SESSION_LIMIT, FAILED_AT);++ const waiting = await service.tick(graph.goal.id);++ expect(waiting).toMatchObject({+ message: expect.stringContaining('retrying at 2026-10-05T20:31:00.000Z'),+ outcome: 'waiting_external',+ taskId: created.taskId,+ });+ expect(runSpy).not.toHaveBeenCalled();+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ // The tick that saw the failure books the advance for the reset.+ expect(scheduleSpy).toHaveBeenCalledWith(+ expect.objectContaining({ delay: 39 * 60 + 59, goalId: graph.goal.id, trigger: 'wake' }),+ );++ vi.setSystemTime(new Date('2026-10-05T20:33:00.000Z'));+ const retried = await service.tick(graph.goal.id);++ expect(runSpy).toHaveBeenCalledWith(+ expect.objectContaining({ taskId: created.taskId, trigger: 'goal' }),+ );+ expect(retried).toMatchObject({ outcome: 'waiting_external', taskId: created.taskId });+ expect((await service.graph(graph.goal.id)).decisions).toHaveLength(0);+ });++ it('opens a machine gate that names the missing working directory', async () => {+ const { created, graph, runSpy, service } = await setup('Missing working directory');+ const error = 'Working directory does not exist: /Users/user/CodeProjects/LobeHub/lobehub';+ await failRun(created.taskId!, 'failed', error, new Date());++ const gated = await service.tick(graph.goal.id);++ expect(gated).toMatchObject({ outcome: 'waiting_human', taskId: created.taskId });+ expect(runSpy).not.toHaveBeenCalled();+ const after = await service.graph(graph.goal.id);+ const gate = after.nodes.find((node) => node.kind === 'decision')!;+ expect(gate.title).toBe(GOAL_MACHINE_GATE_TITLE);+ const [decision] = after.decisions;+ expect(decision.question).toBe(+ 'Setup problem: Working directory does not exist: /Users/user/CodeProjects/LobeHub/lobehub. Create /Users/user/CodeProjects/LobeHub/lobehub on the device the agent runs on, or point the agent at a working directory that exists there. Fix it, then retry or retire this task node?',+ );+ expect(decision.options).toEqual([+ { id: 'retry', label: 'I fixed it — retry' },+ { id: 'retire', label: 'Retire task' },+ ]);+ });++ it('keeps a judgment failure on the ordinary gate', async () => {+ const { created, graph, service } = await setup('Unjudgeable delivery');+ await failRun(+ created.taskId!,+ 'failed',+ 'Acceptance review could not run; the delivery passed its verifiers but was never reviewed.',+ new Date(),+ );++ await service.tick(graph.goal.id);++ const gate = (await service.graph(graph.goal.id)).nodes.find(+ (node) => node.kind === 'decision',+ )!;+ expect(gate.title).toBe('Choose how to recover failed task');+ });++ it('asks about a device that stayed offline with a machine gate', async () => {+ const { created, graph, service, taskModel } = await setup('Device never came back');+ await taskModel.update(created.taskId!, { totalTopics: 7 });+ for (let seq = 1; seq <= 7; seq++) {+ const topicId = `tpc_machine_offline_${seq}`;+ await serverDB.insert(topics).values({ id: topicId, userId });+ await serverDB.insert(taskTopics).values({+ seq,+ status: DEVICE_OFFLINE_RUN_STATUS,+ taskId: created.taskId!,+ topicId,+ updatedAt: new Date(Date.now() - (17 - seq) * 60 * MINUTE),+ userId,+ });+ }+ await taskModel.updateStatus(created.taskId!, 'paused', { error: 'DEVICE_OFFLINE' });++ await service.tick(graph.goal.id);++ const gate = (await service.graph(graph.goal.id)).nodes.find(+ (node) => node.kind === 'decision',+ )!;+ expect(gate).toMatchObject({+ description: DEVICE_OFFLINE_GATE_REASON,+ title: GOAL_MACHINE_GATE_TITLE,+ });+ });+});diff --git a/apps/server/src/services/goal/index.ts b/apps/server/src/services/goal/index.tsindex c26ac3da0db..b5f4706f3d6 100644--- a/apps/server/src/services/goal/index.ts+++ b/apps/server/src/services/goal/index.ts@@ -5,6 +5,7 @@ import {GOAL_CLARIFICATION_OPTION,GOAL_CLARIFICATION_TITLE,GOAL_COORDINATOR_ACTOR_ID,+ GOAL_MACHINE_GATE_TITLE,} from '@lobechat/const/goal';import type {ChatTopicMetadata,@@ -15,6 +16,7 @@ import type {GoalGraphNode,GoalGraphSnapshot,GoalItem,+ GoalManagerAsk,GoalMetricCriterion,GoalNodeAcceptance,GoalNodeKind,@@ -67,6 +69,9 @@ import {TERMINAL_NODE_STATUSES,} from './decideNextMove';import { experimentResults, exploreGraph } from './exploreGraph';+import { classifyGoalFailure, isMachineFailureClass } from './failureClass';+import { GoalBriefService } from './goalBriefs';+import { lastAnsweredGateAt, planMachineRecovery } from './machineRecovery';import { answeredProblem, GoalManagerService, problemKey } from './manager';import {classifyRunFailure,@@ -85,7 +90,9 @@ import {import { isGoalReportNode, withoutGoalReport } from './report';import { GoalReportService } from './reportService';import { GoalReportStore } from './reportStore';+import { scheduleGoalAdvance } from './scheduler';import { GoalSupervisorService } from './supervisor';+import { statusAuthoredByActor } from './supervisor/policy';import { claimGoalTask } from './taskClaim';import { TaskRecoveryCoordinator } from './taskRecoveryCoordinator';import {@@ -195,9 +202,53 @@ export interface CreateGoalNodeInput {*/const DELIVERABLE_EVENTS_PER_RUN = 200;+/**+ * What answering a gate does to the Task it was opened for. The coordinator's+ * own options say it through their fixed ids; an option the main Agent wrote+ * for its own question names its effect, and one that names none only records+ * the answer — the Agent reads it on its next turn.+ */+const decisionOptionEffect = (+ option: GoalDecisionOption | undefined,+ sourceTitle?: string,+): 'fail' | 'retire' | 'retry' | undefined => {+ if (!option) return undefined;+ if (option.effect) return option.effect;+ if (option.id === 'retry' || option.id === 'retire') return option.id;+ if (option.id === 'fail' && sourceTitle === GOAL_ACCEPTANCE_TASK_TITLE) return 'fail';+ return undefined;+};++/**+ * The comment a retried Task carries into its next attempt. A bare "retry"+ * adds nothing the run does not already know; a chosen direction or a note is+ * exactly what the owner wants the next attempt to act on.+ */+const decisionGuidance = (+ question: string,+ option: GoalDecisionOption | undefined,+ note?: string,+): string | undefined => {+ const custom = option && option.id !== 'retry' ? option : undefined;+ const trimmed = note?.trim();+ if (!custom && !trimmed) return undefined;+ return [+ 'Owner decision on the recovery gate for this Task.',+ `Question: ${question}`,+ custom+ ? `Chosen: ${custom.label}${custom.description ? ` — ${custom.description}` : ''}`+ : undefined,+ trimmed ? `Guidance: ${trimmed}` : undefined,+ ]+ .filter(Boolean)+ .join('\n');+};+export class GoalService {private readonly acceptanceService: AcceptanceService;private readonly agentModel: AgentModel;+ /** What the goal tells the person through the inbox: gates, sign-off, findings. */+ private readonly briefs: GoalBriefService;private readonly goalModel: GoalModel;/*** Graph writes attributed to the person who asked for them: seeding a goal,@@ -223,6 +274,7 @@ export class GoalService {) {this.acceptanceService = new AcceptanceService(db, userId, workspaceId);this.agentModel = new AgentModel(db, userId, workspaceId);+ this.briefs = new GoalBriefService(db, userId, workspaceId);this.goalModel = new GoalModel(db, userId, workspaceId);this.graphModel = new GoalGraphModel(db, userId, workspaceId);this.coordinatorGraph = new GoalGraphModel(db, userId, workspaceId, {@@ -857,6 +909,23 @@ export class GoalService {return Object.keys(result).length > 0 ? result : undefined;};+ /**+ * The coordinator calls a goal achieved once its own acceptance passes, but+ * the person who asked for it has not said so yet. Ask them — wherever they+ * are — through the inbox, tied to the Goal-level acceptance they sign.+ */+ private requestSignOff = async (graph: GoalGraphSnapshot) => {+ const terminal = graph.nodes.find(+ (node) => node.kind === 'task' && node.title === GOAL_ACCEPTANCE_TASK_TITLE && !!node.taskId,+ );+ if (!terminal) return;+ const acceptance = (await this.collectAcceptances(graph))?.[terminal.id];+ if (!acceptance) return;+ // `openSignOff` re-reads the acceptance under a row lock: one the owner+ // already signed asks nothing.+ await this.briefs.openSignOff(graph.goal, acceptance.id);+ };+/*** Verification state per task node.*@@ -1931,6 +2000,7 @@ export class GoalService {if (optionId === GOAL_CLARIFICATION_OPTION.answer && !resolution?.trim()) {throw new TRPCError({ code: 'BAD_REQUEST', message: 'This answer needs a note' });}+ const chosen = decision.options?.find((option) => option.id === optionId);const resolved = await this.graphModel.resolveDecision(goalId,decisionId,@@ -1951,23 +2021,33 @@ export class GoalService {source.taskId,true,);- if (optionId === 'retry' && source.taskId) {+ const effect = decisionOptionEffect(chosen, source.title);+ if (effect === 'retry' && source.taskId) {await this.taskModel.updateStatus(source.taskId, 'backlog', { error: null });await this.graphModel.updateNodeStatus(goalId, source.id, 'active', resolution);- } else if (- optionId === 'retire' ||- (optionId === 'fail' && source.title === GOAL_ACCEPTANCE_TASK_TITLE)- ) {+ // The note is guidance for the next attempt, so it goes where that+ // attempt reads: the Task's comments are part of every run prompt.+ // On the node status alone it was recorded and never read again.+ const guidance = decisionGuidance(decision.question, chosen, resolution);+ if (guidance)+ await this.taskModel.addComment({+ authorUserId: this.userId,+ content: guidance,+ taskId: source.taskId,+ userId: this.userId,+ });+ } else if (effect === 'retire') {await this.graphModel.updateNodeStatus(goalId, source.id, 'retired', resolution);}}// Ending the terminal acceptance ends the Goal: `fail` is a verdict that// the Goal failed, `retire` abandons it without one.const terminalAcceptance = source?.title === GOAL_ACCEPTANCE_TASK_TITLE;+ const terminalEffect = decisionOptionEffect(chosen, source?.title);const nextStatus =- terminalAcceptance && optionId === 'fail'+ terminalAcceptance && terminalEffect === 'fail'? 'failed'- : terminalAcceptance && optionId === 'retire'+ : terminalAcceptance && terminalEffect === 'retire'? 'canceled': 'running';// Serialized with `close`, which commits under this row lock: a goal that@@ -2074,6 +2154,22 @@ export class GoalService {}};+ /**+ * Everything the approval island asks outside a goal's page: the gates+ * waiting on the person (clarification rounds have their own form) and the+ * finished goals waiting for their sign-off.+ */+ pendingForIsland = async () => {+ const [decisions, signOffs] = await Promise.all([+ this.goalModel.listPendingDecisions(),+ this.briefs.listOpenSignOffs(),+ ]);+ return {+ decisions: decisions.map((row) => ({ ...row, options: row.options ?? [] })),+ signOffs,+ };+ };+/** Pending clarifications grouped by goal, for surfaces outside the goal page. */pendingClarifications = async () => {const rows = await this.goalModel.listPendingClarifications();@@ -2350,14 +2446,20 @@ export class GoalService {(await this.waitForDevice(graph, acting!.id, task, effects)) ??(await this.waitForQuotaReset(graph, acting!.id, task, effects));if (waiting) return observe(waiting);+ const held = await this.holdForMachineFailure(graph, acting!.id, task, effects);+ if (held) return observe(held);const supervision = await new GoalSupervisorService(this.db,this.userId,this.workspaceId,).reviewFailure(graph, acting!.id, task);if (supervision) return observe(supervision);+ // A machine failure the supervisor gave up on still asks for a fix,+ // not a judgment about the work.return observe(- await this.gateOrTakeOver(graph, acting!.id, task.id, move.message, effects),+ await this.gateOrTakeOver(graph, acting!.id, task.id, move.message, effects, {+ machine: isMachineFailureClass(classifyGoalFailure(task.error).class),+ }),);}@@ -2425,6 +2527,11 @@ export class GoalService {await this.coordinatorGraph.updateNodeStatus(goalId, node.id, 'resolved', 'Goal achieved');effects.push({ detail: 'resolved', nodeId: node.id, type: 'node_status' });}+ // Ask for the sign-off before the goal turns terminal: nothing ticks an+ // achieved goal again, so a failed write after the transition would lose+ // the ask for good. Failing here leaves the goal open for the next tick,+ // and the write is idempotent per acceptance.+ await this.requestSignOff(graph);await this.transitionStatus(graph.goal, 'achieved', 'Goal-level acceptance passed');effects.push({ type: 'goal_status', detail: 'achieved' });return { goalId, message: move.message, outcome: 'achieved' };@@ -2717,7 +2824,9 @@ export class GoalService {: recovery.outcome === 'exhausted-rounds'? 'Task attempt budget was exhausted': 'Automatic recovery could not start the next attempt';- return this.gateOrTakeOver(graph, nodeId, task.id, exhaustedReason, effects);+ return this.gateOrTakeOver(graph, nodeId, task.id, exhaustedReason, effects, {+ machine: recovery.outcome === 'spawn-failed',+ });};/** Claim the task for dispatch and start its run. */@@ -3066,7 +3175,79 @@ export class GoalService {: recovery.outcome === 'exhausted-rounds'? 'Task attempt budget was exhausted after an operation was abandoned': 'Automatic recovery could not restart an abandoned operation';- return this.gateOrTakeOver(graph, nodeId, task.id, reason, effects);+ return this.gateOrTakeOver(graph, nodeId, task.id, reason, effects, {+ machine: recovery.outcome === 'spawn-failed',+ });+ };++ /** The machine-recovery plan for a paused Task, over its runs since a person last answered its gate. */+ private planMachineRecoveryFor = async (+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ now = new Date(),+ ) => {+ // A person's Retry restarts the schedule they overrode.+ const answeredAt = lastAnsweredGateAt(graph, nodeId);+ const runs = (await this.taskTopicModel.findByTaskId(task.id)).filter(+ (run) => !answeredAt || new Date(run.updatedAt) > answeredAt,+ );+ return planMachineRecovery({ error: task.error, now, runs, taskUpdatedAt: task.updatedAt });+ };++ /**+ * Recover a Task stopped by a machine problem without asking anyone to judge it+ * (see `planMachineRecovery`): a usage limit is waited out until it resets, a+ * transport fault is retried a few times, and neither run spends the attempt+ * budget. A broken setup — or a schedule that ran out — opens a machine gate+ * that says what to fix. Judgment failures return nothing and keep the+ * supervisor and the ordinary gate.+ */+ private holdForMachineFailure = async (+ graph: GoalGraphSnapshot,+ nodeId: string,+ task: TaskItem,+ effects: GoalAdvanceEffect[],+ ): Promise<GoalTickResult | undefined> => {+ if (task.status !== 'paused' || !task.error) return;+ // A supervised goal already has an owner for transport faults: the supervisor+ // diagnoses and retries them (see `recoveryEligibility`), so the deterministic+ // schedule stays out of its way rather than racing it for the same Task.+ const supervised = !!graph.goal.config?.supervision?.enabled || !!graph.goal.config?.manager;+ if (supervised && classifyGoalFailure(task.error).class === 'transient') return;+ const now = new Date();+ const plan = await this.planMachineRecoveryFor(graph, nodeId, task, now);+ if (plan.action === 'none') return;+ // A pause somebody made is theirs; the error text it kept proves nothing.+ if (statusAuthoredByActor(await this.taskModel.getActivities(task.id, 20), task.status)) return;++ if (plan.action === 'gate')+ return this.gateOrTakeOver(graph, nodeId, task.id, plan.reason, effects, { machine: true });+ if (plan.action === 'retry')+ return this.resumeAbandonedTaskRecovery(graph, nodeId, task, effects);++ // The sweep re-ticks a held goal, but only on its own cadence; the tick that+ // first sees the failure also books an advance for the retry time. Later+ // sweep ticks do not, so a long hold does not pile up queued advances.+ if (now.getTime() - plan.failedAt.getTime() <= MACHINE_HOLD_SCHEDULE_WINDOW_MS) {+ await scheduleGoalAdvance({+ delay: Math.max(+ 1,+ Math.min(MAX_ADVANCE_DELAY_S, Math.ceil((plan.retryAt.getTime() - now.getTime()) / 1000)),+ ),+ goalId: graph.goal.id,+ trigger: 'wake',+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ }+ return {+ goalId: graph.goal.id,+ message: `Task ${task.identifier}: ${plan.message}`,+ nodeId,+ outcome: 'waiting_external',+ taskId: task.id,+ };};/**@@ -3116,6 +3297,15 @@ export class GoalService {).findById(latest.operationId);const failure = classifyRunFailure(operation?.error, task.error ?? '');if (failure.kind !== 'quota_reset') return;+ // A refusal whose text names the limit is recorded as an uncharged run+ // (`resolveFailedRunStatus`), so the attempt budget no longer bounds a window+ // that keeps refusing; the uncharged quota schedule does. Once it is spent,+ // fall through and `holdForMachineFailure` asks a person to fix the account.+ if (+ classifyGoalFailure(task.error).class === 'quota' &&+ (await this.planMachineRecoveryFor(graph, nodeId, task)).action === 'gate'+ )+ return;const retryAt = failure.resetsAt! + QUOTA_RESET_MARGIN_MS;if (retryAt <= Date.now()) {// The retry is a paid run, and recovery only checks the Task's own attempts@@ -3178,7 +3368,9 @@ export class GoalService {const lastFailureAt = new Date(offlineRuns ? runs[0].updatedAt : task.updatedAt);const retryAt = nextDeviceOfflineRetryAt(offlineRuns, lastFailureAt);if (!retryAt)- return this.gateOrTakeOver(graph, nodeId, task.id, DEVICE_OFFLINE_GATE_REASON, effects);+ return this.gateOrTakeOver(graph, nodeId, task.id, DEVICE_OFFLINE_GATE_REASON, effects, {+ machine: true,+ });if (retryAt.getTime() <= Date.now()) return;const [latest] = await this.taskTopicModel.findWithHandoff(task.id, 1);@@ -3336,6 +3528,7 @@ export class GoalService {},];+ const askedDecisions: { id: string; question: string }[] = [];// Only the current lease owner may commit. The model call above does not// hold a database lock; all graph changes below share one short transaction.const committed = await this.db.transaction(async (tx) => {@@ -3399,12 +3592,13 @@ export class GoalService {});if (!node) throw new Error('Failed to open a clarification decision');await writer.createEdge(goalId, currentProblem.id, node.id, 'leads_to');- await writer.createDecision(goalId, node.id, {+ const decision = await writer.createDecision(goalId, node.id, {authority: 'user',options: clarificationOptions(question),question: question.question,requestedUserId: this.userId,});+ if (decision) askedDecisions.push({ id: decision.id, question: question.question });committedEffects.push({detail: question.question,nodeId: currentProblem.id,@@ -3473,6 +3667,11 @@ export class GoalService {const asked = committed.filter((effect) => effect.type === 'opened_decision').length;if (asked > 0) {+ await this.briefs.openClarification(+ graph.goal,+ askedDecisions.map((decision) => decision.id),+ askedDecisions.map((decision) => decision.question),+ );return {goalId,message: `Asked ${asked} clarification question${asked > 1 ? 's' : ''} before planning`,@@ -3689,16 +3888,21 @@ export class GoalService {);if (!existingFinding) {const handoff = latest?.handoff as TaskTopicHandoff | null;+ const title =+ handoff?.title ??+ handoff?.summary ??+ `Completed: ${graph.nodes.find((node) => node.id === nodeId)?.title}`;+ // The finding is written by whoever did the work. Recorded as the owner,+ // it read as something the person had said themselves.+ const author = (await this.taskModel.findById(taskId))?.assigneeAgentId ?? graph.goal.agentId;const finding = await this.coordinatorGraph.createNode(graph.goal.id, {confidence: 1,+ createdByAgentId: author ?? undefined,description: handoff?.content ?? handoff?.summary ?? undefined,kind: 'finding',scopeId: experimentOwner(graph, nodeId),status: 'resolved',- title:- handoff?.title ??- handoff?.summary ??- `Completed: ${graph.nodes.find((node) => node.id === nodeId)?.title}`,+ title,});if (finding) {effects.push({ detail: 'finding', nodeId, targetId: finding.id, type: 'created_node' });@@ -3743,6 +3947,7 @@ export class GoalService {taskId: string,reason: string,effects: GoalAdvanceEffect[] = [],+ gate: FailureGateOptions = {},): Promise<GoalTickResult> => {const takeover = await new GoalManagerService(this.db, this.userId, this.workspaceId).takeOver(graph,@@ -3753,14 +3958,22 @@ export class GoalService {// said: the person answering should see the Agent's reasoning, not just the// coordinator's own reason for stopping.const answered = answeredProblem(graph.goal.config?.managerState);- const diagnosis =- answered?.key === problemKey({ reason, taskId }) ? answered.reason.slice(0, 600) : undefined;+ const own = answered?.key === problemKey({ reason, taskId }) ? answered : undefined;+ // An Agent that asked a real question gets it asked as written, with its+ // own answers as the buttons; its diagnosis is what the gate stands on.+ if (own?.ask)+ return this.openFailureDecision(graph, nodeId, taskId, reason, effects, {+ ...gate,+ ask: { ...own.ask, diagnosis: own.reason },+ });+ const diagnosis = own ? own.reason.slice(0, 600) : undefined;return this.openFailureDecision(graph,nodeId,taskId,diagnosis ? `${reason} — main Agent: ${diagnosis}` : reason,effects,+ gate,);};@@ -3770,6 +3983,7 @@ export class GoalService {taskId: string,reason: string,effects: GoalAdvanceEffect[] = [],+ gate: FailureGateOptions = {},): Promise<GoalTickResult> => {return this.db.transaction(async (tx) => {const currentGoal = await new GoalModel(tx, this.userId, this.workspaceId).lockById(@@ -3797,7 +4011,7 @@ export class GoalService {taskId,};}- return service.openFailureDecisionLocked(current, nodeId, taskId, reason, effects);+ return service.openFailureDecisionLocked(current, nodeId, taskId, reason, effects, gate);});};@@ -3807,45 +4021,78 @@ export class GoalService {taskId: string,reason: string,effects: GoalAdvanceEffect[],+ gate: FailureGateOptions = {},): Promise<GoalTickResult> => {const existingDecisionNode = graph.edges.filter((edge) => edge.sourceNodeId === nodeId && edge.kind === 'leads_to').map((edge) => graph.nodes.find((node) => node.id === edge.targetNodeId)).find((node) => node?.kind === 'decision' && node.status !== 'resolved');if (!existingDecisionNode) {+ const terminalAcceptance =+ graph.nodes.find((candidate) => candidate.id === nodeId)?.title ===+ GOAL_ACCEPTANCE_TASK_TITLE;+ // The terminal acceptance gate keeps its own three-way shape: ending the+ // Goal is a verdict even when a machine problem is what stopped it.+ const machine = !!gate.machine && !terminalAcceptance;+ const { ask } = gate;const node = await this.coordinatorGraph.createNode(graph.goal.id, {- description: reason,+ // What the gate stands on: the main Agent's diagnosis when it asked,+ // else the coordinator's own reason for stopping.+ description: ask ? `${reason}\n\n${ask.diagnosis}` : reason,kind: 'decision',status: 'waiting',- title: 'Choose how to recover failed task',+ title: machine ? GOAL_MACHINE_GATE_TITLE : 'Choose how to recover failed task',scopeId: experimentOwner(graph, nodeId),});if (node) {effects.push({ detail: reason, nodeId, targetId: node.id, type: 'opened_decision' });await this.coordinatorGraph.createEdge(graph.goal.id, nodeId, node.id, 'leads_to');- const terminalAcceptance =- graph.nodes.find((candidate) => candidate.id === nodeId)?.title ===- GOAL_ACCEPTANCE_TASK_TITLE;- await this.coordinatorGraph.createDecision(graph.goal.id, node.id, {- authority: 'user',- options: terminalAcceptance- ? [- { id: 'retry', label: 'Retry goal acceptance' },- // Drop the acceptance Task and end the Goal without a verdict —- // unlike `fail`, which records that the Goal was judged failed.- { id: 'retire', label: 'Abandon goal acceptance' },- { id: 'fail', label: 'Fail goal' },- ]- : [- { id: 'retry', label: 'Retry task' },- { id: 'retire', label: 'Retire task' },- ],- question: terminalAcceptance- ? `${reason}. Retry Goal acceptance, abandon it, or fail this Goal?`- : `${reason}. Retry or retire this task node?`,- recommendedOptionId: 'retry',- requestedUserId: this.userId,- });+ const decision = await this.coordinatorGraph.createDecision(+ graph.goal.id,+ node.id,+ ask+ ? {+ authority: 'user',+ options: ask.options,+ question: ask.question,+ recommendedOptionId: ask.recommendedOptionId,+ requestedUserId: this.userId,+ }+ : {+ authority: 'user',+ options: machine+ ? [+ { id: 'retry', label: 'I fixed it — retry' },+ { id: 'retire', label: 'Retire task' },+ ]+ : terminalAcceptance+ ? [+ { id: 'retry', label: 'Retry goal acceptance' },+ // Drop the acceptance Task and end the Goal without a verdict —+ // unlike `fail`, which records that the Goal was judged failed.+ { id: 'retire', label: 'Abandon goal acceptance' },+ { id: 'fail', label: 'Fail goal' },+ ]+ : [+ { id: 'retry', label: 'Retry task' },+ { id: 'retire', label: 'Retire task' },+ ],+ question: machine+ ? `${reason}. Fix it, then retry or retire this task node?`+ : terminalAcceptance+ ? `${reason}. Retry Goal acceptance, abandon it, or fail this Goal?`+ : `${reason}. Retry or retire this task node?`,+ recommendedOptionId: 'retry',+ requestedUserId: this.userId,+ },+ );+ if (decision)+ await this.briefs.openDecision(graph.goal, {+ decisionId: decision.id,+ options: decision.options,+ question: decision.question,+ recommendedOptionId: decision.recommendedOptionId,+ });}}await this.coordinatorGraph.updateNodeStatus(graph.goal.id, nodeId, 'waiting', reason);@@ -3860,6 +4107,21 @@ export class GoalService {};}+interface FailureGateOptions {+ /** The main Agent's own question for this gate, asked as written with its diagnosis. */+ ask?: GoalManagerAsk & { diagnosis: string };+ /**+ * The gate is about a machine problem (broken setup, spent retry schedule), not+ * the work: it opens as a machine gate that asks for a fix, not a judgment.+ */+ machine?: boolean;+}++/** A machine hold books its own advance only from the tick that first saw the failure. */+const MACHINE_HOLD_SCHEDULE_WINDOW_MS = 15 * 60 * 1000;+/** Queue delays are bounded; the sweep covers anything further out. */+const MAX_ADVANCE_DELAY_S = 86_400;+/*** Whether a Task topic is still `running` although its run has already ended.*diff --git a/apps/server/src/services/goal/machineRecovery.test.ts b/apps/server/src/services/goal/machineRecovery.test.tsnew file mode 100644index 00000000000..fdf4aca2585--- /dev/null+++ b/apps/server/src/services/goal/machineRecovery.test.ts@@ -0,0 +1,178 @@+import { QUOTA_LIMITED_RUN_STATUS, TRANSIENT_FAILED_RUN_STATUS } from '@lobechat/const/goal';+import { describe, expect, it } from 'vitest';++import { lastAnsweredGateAt, planMachineRecovery } from './machineRecovery';+import { QUOTA_RESET_MARGIN_MS } from './recoveryPolicy';++const MINUTE = 60 * 1000;+const HOUR = 60 * MINUTE;++const SESSION_LIMIT = "You've hit your session limit · resets 4:30am (Asia/Shanghai)";+// 03:50 in Shanghai: the real gate opened 40 minutes before this reset.+const FAILED_AT = new Date('2026-10-05T19:50:01.285Z');+const RESET_AT = new Date('2026-10-05T20:30:00.000Z');++const run = (status: string, updatedAt: Date) => ({ status, updatedAt });++describe('planMachineRecovery', () => {+ describe('usage limits', () => {+ it('waits for the reset the limit names instead of asking anyone', () => {+ const plan = planMachineRecovery({+ error: SESSION_LIMIT,+ now: new Date(FAILED_AT.getTime() + MINUTE),+ runs: [run(QUOTA_LIMITED_RUN_STATUS, FAILED_AT)],+ taskUpdatedAt: FAILED_AT,+ });+ expect(plan).toMatchObject({+ action: 'wait',+ failedAt: FAILED_AT,+ failureClass: 'quota',+ retryAt: new Date(RESET_AT.getTime() + QUOTA_RESET_MARGIN_MS),+ });+ });++ it('retries once the reset (plus margin) has passed', () => {+ expect(+ planMachineRecovery({+ error: SESSION_LIMIT,+ now: new Date(RESET_AT.getTime() + 3 * MINUTE),+ runs: [run(QUOTA_LIMITED_RUN_STATUS, FAILED_AT)],+ taskUpdatedAt: FAILED_AT,+ }),+ ).toEqual({ action: 'retry', failureClass: 'quota' });+ });++ it('backs off 30m, 1h, 2h … when the limit names no reset time', () => {+ const error = "You've hit your session limit";+ const at = (n: number) => new Date(FAILED_AT.getTime() - (n - 1) * MINUTE);+ const first = planMachineRecovery({+ error,+ now: FAILED_AT,+ runs: [run(QUOTA_LIMITED_RUN_STATUS, FAILED_AT)],+ taskUpdatedAt: FAILED_AT,+ });+ expect(first).toMatchObject({ retryAt: new Date(FAILED_AT.getTime() + 30 * MINUTE) });+ const third = planMachineRecovery({+ error,+ now: FAILED_AT,+ runs: [1, 2, 3].map((n) => run(QUOTA_LIMITED_RUN_STATUS, at(n))),+ taskUpdatedAt: FAILED_AT,+ });+ expect(third).toMatchObject({ retryAt: new Date(FAILED_AT.getTime() + 2 * HOUR) });+ });++ it('asks a person once the retries are spent, saying how long it tried', () => {+ const runs = Array.from({ length: 7 }, (_, i) =>+ run(QUOTA_LIMITED_RUN_STATUS, new Date(FAILED_AT.getTime() - i * 3 * HOUR)),+ );+ const plan = planMachineRecovery({+ error: "You've hit your session limit",+ now: FAILED_AT,+ runs,+ taskUpdatedAt: FAILED_AT,+ });+ expect(plan.action).toBe('gate');+ expect(plan.action === 'gate' && plan.reason).toContain('Retried 6 time(s) over 18h');+ });++ it('asks at once when the limit resets more than a day away', () => {+ const plan = planMachineRecovery({+ error: "You've hit your weekly limit · resets Oct 9, 5pm (America/New_York)",+ now: FAILED_AT,+ runs: [run(QUOTA_LIMITED_RUN_STATUS, FAILED_AT)],+ taskUpdatedAt: FAILED_AT,+ });+ expect(plan.action).toBe('gate');+ expect(plan.action === 'gate' && plan.reason).toContain('more than a day away');+ });++ it('does not count limited runs from before the streak was broken', () => {+ const plan = planMachineRecovery({+ error: "You've hit your session limit",+ now: FAILED_AT,+ runs: [+ run(QUOTA_LIMITED_RUN_STATUS, FAILED_AT),+ run('completed', new Date(FAILED_AT.getTime() - HOUR)),+ ...Array.from({ length: 6 }, (_, i) =>+ run(QUOTA_LIMITED_RUN_STATUS, new Date(FAILED_AT.getTime() - (i + 2) * HOUR)),+ ),+ ],+ taskUpdatedAt: FAILED_AT,+ });+ expect(plan).toMatchObject({ action: 'wait', failureClass: 'quota' });+ });+ });++ describe('transient faults', () => {+ const error = '{"error":"TIMEOUT","success":false}';++ it('retries a few times on a short schedule, then asks', () => {+ const one = planMachineRecovery({+ error,+ now: new Date(FAILED_AT.getTime() + MINUTE),+ runs: [run(TRANSIENT_FAILED_RUN_STATUS, FAILED_AT)],+ taskUpdatedAt: FAILED_AT,+ });+ expect(one).toMatchObject({+ action: 'wait',+ retryAt: new Date(FAILED_AT.getTime() + 2 * MINUTE),+ });++ const spent = planMachineRecovery({+ error,+ now: FAILED_AT,+ runs: [0, 30, 40, 42].map((ago) =>+ run(TRANSIENT_FAILED_RUN_STATUS, new Date(FAILED_AT.getTime() - ago * MINUTE)),+ ),+ taskUpdatedAt: FAILED_AT,+ });+ expect(spent.action).toBe('gate');+ expect(spent.action === 'gate' && spent.reason).toContain('Retried 3 time(s)');+ });+ });++ it('gates a broken setup at once, naming what to fix', () => {+ const plan = planMachineRecovery({+ error: 'Working directory does not exist: /Users/user/CodeProjects/LobeHub/lobehub',+ now: FAILED_AT,+ runs: [run('failed', FAILED_AT)],+ taskUpdatedAt: FAILED_AT,+ });+ expect(plan).toEqual({+ action: 'gate',+ reason:+ 'Setup problem: Working directory does not exist: /Users/user/CodeProjects/LobeHub/lobehub. Create /Users/user/CodeProjects/LobeHub/lobehub on the device the agent runs on, or point the agent at a working directory that exists there',+ });+ });++ it('leaves judgment failures alone', () => {+ expect(+ planMachineRecovery({+ error: 'Task attempt budget was exhausted',+ now: FAILED_AT,+ runs: [],+ taskUpdatedAt: FAILED_AT,+ }),+ ).toEqual({ action: 'none' });+ });+});++describe('lastAnsweredGateAt', () => {+ it('returns when a person last resolved a gate opened for the node', () => {+ const graph = {+ decisions: [+ { nodeId: 'gate-1', resolvedAt: new Date('2026-10-01T00:00:00Z'), status: 'resolved' },+ { nodeId: 'gate-2', resolvedAt: new Date('2026-10-03T00:00:00Z'), status: 'resolved' },+ { nodeId: 'other', resolvedAt: new Date('2026-10-04T00:00:00Z'), status: 'resolved' },+ { nodeId: 'gate-3', resolvedAt: null, status: 'pending' },+ ],+ edges: [+ { kind: 'leads_to', sourceNodeId: 'task', targetNodeId: 'gate-1' },+ { kind: 'leads_to', sourceNodeId: 'task', targetNodeId: 'gate-2' },+ { kind: 'leads_to', sourceNodeId: 'task', targetNodeId: 'gate-3' },+ ],+ } as any;+ expect(lastAnsweredGateAt(graph, 'task')).toEqual(new Date('2026-10-03T00:00:00Z'));+ expect(lastAnsweredGateAt(graph, 'none')).toBeUndefined();+ });+});diff --git a/apps/server/src/services/goal/machineRecovery.ts b/apps/server/src/services/goal/machineRecovery.tsnew file mode 100644index 00000000000..38e39a4f391--- /dev/null+++ b/apps/server/src/services/goal/machineRecovery.ts@@ -0,0 +1,202 @@+import { QUOTA_LIMITED_RUN_STATUS, TRANSIENT_FAILED_RUN_STATUS } from '@lobechat/const/goal';+import type { GoalGraphSnapshot } from '@lobechat/types';++import type { GoalEnvironmentProblem, GoalFailureClassification } from './failureClass';+import { classifyGoalFailure } from './failureClass';+import { countConsecutiveRunsWithStatus, QUOTA_RESET_MARGIN_MS } from './recoveryPolicy';++/**+ * How the coordinator recovers a Task stopped by a machine problem, mirroring the+ * offline-device schedule in `recoveryPolicy`: the run is not charged to the+ * attempt budget, so each class carries its own bound, and a person is asked+ * only once it is spent — with a gate that says what broke, not a judgment call.+ */++/**+ * Longest a Task waits on usage limits before a person is asked, measured from+ * the first limited run of the streak. A five-hour window that resets overnight+ * fits; a weekly limit days away does not, and is worth telling someone about.+ */+export const QUOTA_MAX_HOLD_MS = 26 * 60 * 60 * 1000;+/** Without a reset time the limit is retried on the offline-style backoff: 30m … 8h. */+export const QUOTA_FIRST_RETRY_DELAY_MS = 30 * 60 * 1000;+export const QUOTA_MAX_RETRY_DELAY_MS = 8 * 60 * 60 * 1000;+export const MAX_QUOTA_RETRIES = 6;+/**+ * Transient faults retry quickly and only a few times: one that survives three+ * fresh attempts across ~40 minutes is not transient any more.+ */+export const TRANSIENT_RETRY_DELAYS_MS = [2 * 60 * 1000, 10 * 60 * 1000, 30 * 60 * 1000];++export type MachineRecoveryPlan =+ /** Not a machine problem: the judgment gate (or the supervisor) owns it. */+ | { action: 'none' }+ /** Retry now through the ordinary recovery path. */+ | { action: 'retry'; failureClass: 'quota' | 'transient' }+ /** Hold the Task; nothing to do until `retryAt`. */+ | {+ action: 'wait';+ failureClass: 'quota' | 'transient';+ /** When the failure being waited out happened. */+ failedAt: Date;+ message: string;+ retryAt: Date;+ }+ /** A person has to fix the setup; `reason` says what and is stable across ticks. */+ | { action: 'gate'; reason: string };++interface RunLike {+ status: string;+ updatedAt: Date | string;+}++const hours = (ms: number) => {+ const value = ms / 3_600_000;+ return value >= 10 ? `${Math.round(value)}h` : `${Math.round(value * 10) / 10}h`;+};++/** The fix a person makes for each environment problem, appended when the error does not say it. */+const environmentFix = (problem: GoalEnvironmentProblem): string => {+ switch (problem.kind) {+ case 'workingDirectory': {+ return `Create ${problem.path} on the device the agent runs on, or point the agent at a working directory that exists there`;+ }+ case 'cli': {+ return 'Install the CLI on the device the agent runs on and make sure it is on PATH';+ }+ case 'credentials': {+ return "Update the provider credentials, plan or model in the agent's settings";+ }+ case 'device': {+ return 'Reconnect the device (desktop app or `lh connect`), or bind the agent to another online device';+ }+ case 'gateway': {+ return 'Configure the device gateway on the server, or switch the agent to a connected local device';+ }+ }+};++const trimError = (error: string) => {+ const flat = error+ .replaceAll(/\s+/g, ' ')+ .trim()+ .replace(/[.\s]+$/, '');+ return flat.length > 300 ? `${flat.slice(0, 297)}...` : flat;+};++/** What the machine gate says for a setup problem: what broke, then what to change. */+export const describeEnvironmentGate = (error: string, problem: GoalEnvironmentProblem): string =>+ `Setup problem: ${trimError(error)}. ${environmentFix(problem)}`;++const nextQuotaRetryAt = (+ failure: GoalFailureClassification,+ failures: number,+ lastFailureAt: Date,+): Date => {+ if (failure.resetAt && failure.resetAt.getTime() > lastFailureAt.getTime())+ return new Date(failure.resetAt.getTime() + QUOTA_RESET_MARGIN_MS);+ const delay = Math.min(+ QUOTA_FIRST_RETRY_DELAY_MS * 2 ** (Math.max(1, failures) - 1),+ QUOTA_MAX_RETRY_DELAY_MS,+ );+ return new Date(lastFailureAt.getTime() + delay);+};++/**+ * Decide what to do with a Task paused on `error`.+ *+ * `runs` is the Task's run history newest first. A failure that left no run+ * behind (a dispatch that never started) counts as the first of its streak,+ * dated by the Task's own last update.+ */+export const planMachineRecovery = (params: {+ error: string | null | undefined;+ now: Date;+ runs: readonly RunLike[];+ taskUpdatedAt: Date | string;+}): MachineRecoveryPlan => {+ const { error, now, runs } = params;+ if (!error) return { action: 'none' };+ const { class: failureClass, problem } = classifyGoalFailure(error);++ if (failureClass === 'environment')+ return { action: 'gate', reason: describeEnvironmentGate(error, problem!) };+ if (failureClass === 'judgment') return { action: 'none' };++ const status = failureClass === 'quota' ? QUOTA_LIMITED_RUN_STATUS : TRANSIENT_FAILED_RUN_STATUS;+ const streak = countConsecutiveRunsWithStatus(runs, status);+ const failures = Math.max(1, streak);+ const lastFailureAt = streak ? new Date(runs[0].updatedAt) : new Date(params.taskUpdatedAt);+ const firstFailureAt = streak ? new Date(runs[streak - 1].updatedAt) : lastFailureAt;+ const retries = failures - 1;+ const spentFor = hours(lastFailureAt.getTime() - firstFailureAt.getTime());++ if (failureClass === 'quota') {+ // A wall-clock reset ("resets 4:30am") is the next one after the failure.+ const failure = classifyGoalFailure(error, lastFailureAt);+ const retryAt = nextQuotaRetryAt(failure, failures, lastFailureAt);+ if (retryAt.getTime() - firstFailureAt.getTime() > QUOTA_MAX_HOLD_MS) {+ return {+ action: 'gate',+ reason:+ retries === 0+ ? `Usage limit: ${trimError(error)}. It does not reset until ${retryAt.toISOString()}, more than a day away. Switch the agent to another account or provider, or retry after the reset`+ : `Usage limit: ${trimError(error)}. Retried ${retries} time(s) over ${spentFor} and the limit still applies. Check the plan or switch the agent to another account or provider`,+ };+ }+ if (retries >= MAX_QUOTA_RETRIES) {+ return {+ action: 'gate',+ reason: `Usage limit: ${trimError(error)}. Retried ${retries} time(s) over ${spentFor} and the limit still applies. Check the plan or switch the agent to another account or provider`,+ };+ }+ if (retryAt.getTime() <= now.getTime()) return { action: 'retry', failureClass: 'quota' };+ return {+ action: 'wait',+ failedAt: lastFailureAt,+ failureClass: 'quota',+ message: `Usage limit hit; retrying at ${retryAt.toISOString()}`,+ retryAt,+ };+ }++ if (retries >= TRANSIENT_RETRY_DELAYS_MS.length) {+ return {+ action: 'gate',+ reason: `Run failed: ${trimError(error)}. Retried ${retries} time(s) over ${spentFor} and it failed the same way each time. Check the device, its network and the agent gateway`,+ };+ }+ const retryAt = new Date(lastFailureAt.getTime() + TRANSIENT_RETRY_DELAYS_MS[retries]);+ if (retryAt.getTime() <= now.getTime()) return { action: 'retry', failureClass: 'transient' };+ return {+ action: 'wait',+ failedAt: lastFailureAt,+ failureClass: 'transient',+ message: `Transient failure; retrying at ${retryAt.toISOString()}`,+ retryAt,+ };+};++/**+ * When a person last answered a gate opened for this Task node. Their Retry is+ * a fresh start: runs before it belong to the schedule they already overrode,+ * so a limit hit again afterwards is waited out again instead of gating at once.+ */+export const lastAnsweredGateAt = (+ graph: Pick<GoalGraphSnapshot, 'decisions' | 'edges'>,+ nodeId: string,+): Date | undefined => {+ const gates = new Set(+ graph.edges+ .filter((edge) => edge.sourceNodeId === nodeId && edge.kind === 'leads_to')+ .map((edge) => edge.targetNodeId),+ );+ let latest: Date | undefined;+ for (const decision of graph.decisions) {+ if (!gates.has(decision.nodeId) || decision.status !== 'resolved' || !decision.resolvedAt)+ continue;+ const at = new Date(decision.resolvedAt);+ if (!latest || at > latest) latest = at;+ }+ return latest;+};diff --git a/apps/server/src/services/goal/manager.test.ts b/apps/server/src/services/goal/manager.test.tsindex ee6e87b5962..dd60ed7a41b 100644--- a/apps/server/src/services/goal/manager.test.ts+++ b/apps/server/src/services/goal/manager.test.ts@@ -1,5 +1,9 @@// @vitest-environment node-import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import {+ GOAL_ACCEPTANCE_TASK_TITLE,+ GOAL_COORDINATOR_ACTOR_ID,+ GOAL_MANAGER_QUESTION_TITLE,+} from '@lobechat/const/goal';import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -746,6 +750,23 @@ describe('CLI main Agent planning', () => {expect(vi.mocked(AiAgentService.prototype.execAgent)).toHaveBeenCalledTimes(1);});+ it('records a turn-budget pause as the system, not the owner', async () => {+ const { id, op } = await start(1);+ await ops().recordCompletion(op.id, {+ status: 'error',+ completionReason: 'error',+ error: { message: 'transport error' },+ });+ await service().tick(id);+ await service().tick(id);++ const pause = (await service().graph(id)).events.find(+ (event) =>+ event.entityType === 'goal' && event.reason === 'Goal or main Agent turn budget exhausted',+ );+ expect(pause).toMatchObject({ actorId: GOAL_COORDINATOR_ACTOR_ID, actorType: 'system' });+ });+it('rejects a delayed claim after another turn has consumed the remaining budget', async () => {const { id, op } = await start(2);await ops().recordCompletion(op.id, { status: 'error' });@@ -1603,37 +1624,38 @@ describe('takeover ordering', () => {});});+/** A takeover-mode Goal whose only Task just spent its attempt budget. */+const stuckGoal = async (title = 'Explored research') => {+ const graph = await service().create({+ config: {+ exploration: { instruction: 'Follow the pre-registered branches', maxExperiments: 4 },+ manager: { maxTurns: 4 },+ recovery: { maxAttemptsPerTask: 1 },+ },+ createdByAgentId: agentId,+ tasks: ['Measure ranking ability on the frozen holdout'],+ title,+ });+ const created = await service().tick(graph.goal.id);+ const taskModel = new TaskModel(db, userId);+ await taskModel.update(created.taskId!, { totalTopics: 1 });+ await taskModel.updateStatus(created.taskId!, 'paused', {+ error: 'Delivery did not pass verification.',+ });+ await service().tick(graph.goal.id);+ const state = (await model().findById(graph.goal.id))!.config!.managerState!;+ const turn = await ops().findByTopicSourceMessage(+ state.topicId,+ `msg_goal_manager_${state.token}`,+ );+ return { goalId: graph.goal.id, state, taskId: created.taskId!, turn: turn! };+};+/*** Codex review round 2 on #19477. Both findings were about the takeover contract* promising more than the code would accept.*/describe('takeover submissions', () => {- const stuckGoal = async (title = 'Explored research') => {- const graph = await service().create({- config: {- exploration: { instruction: 'Follow the pre-registered branches', maxExperiments: 4 },- manager: { maxTurns: 4 },- recovery: { maxAttemptsPerTask: 1 },- },- createdByAgentId: agentId,- tasks: ['Measure ranking ability on the frozen holdout'],- title,- });- const created = await service().tick(graph.goal.id);- const taskModel = new TaskModel(db, userId);- await taskModel.update(created.taskId!, { totalTopics: 1 });- await taskModel.updateStatus(created.taskId!, 'paused', {- error: 'Delivery did not pass verification.',- });- await service().tick(graph.goal.id);- const state = (await model().findById(graph.goal.id))!.config!.managerState!;- const turn = await ops().findByTopicSourceMessage(- state.topicId,- `msg_goal_manager_${state.token}`,- );- return { goalId: graph.goal.id, state, taskId: created.taskId!, turn: turn! };- };-/*** The prompt advertises a corrective task, verification, a retry and escalation.* `submit` refused `tasks` and `verify` whenever any task node was unfinished —@@ -1731,6 +1753,155 @@ describe('takeover submissions', () => {});});+/**+ * Escalations used to carry only a reason, so the owner's gate offered retry /+ * retire while the actual decision — waive a criterion, restore a closed PR —+ * sat in the text with no button to answer it.+ */+describe('escalations that ask a real question', () => {+ const waiveAsk = {+ question: 'Waive the "in order" criterion for this delivery?',+ options: [+ {+ id: 'waive',+ label: 'Waive it',+ description: 'Accept the PRs in the order they merged',+ effect: 'retry' as const,+ },+ { id: 'keep', label: 'Keep it', effect: 'retire' as const },+ ],+ recommendedOptionId: 'waive',+ };++ it('opens a question gate instead of pausing an ordinary planning turn', async () => {+ const { id, state, op } = await start();+ await operationCaller(op.id).submitOperationPlan({+ id,+ operationId: op.id,+ token: state.token,+ plan: {+ action: 'escalate',+ reason: 'Both readings of the requirement are defensible',+ ask: {+ question: 'Should the report cover desktop only?',+ options: [+ { id: 'desktop', label: 'Desktop only' },+ { id: 'all', label: 'Desktop and mobile' },+ ],+ },+ },+ });++ const goal = (await model().findById(id))!;+ expect(goal.status).toBe('review');+ const graph = await service().graph(id);+ const node = graph.nodes.find((n) => n.title === GOAL_MANAGER_QUESTION_TITLE)!;+ expect(node).toMatchObject({+ description: 'Both readings of the requirement are defensible',+ kind: 'decision',+ });+ expect(graph.decisions).toEqual([+ expect.objectContaining({+ nodeId: node.id,+ options: [+ { id: 'desktop', label: 'Desktop only' },+ { id: 'all', label: 'Desktop and mobile' },+ ],+ question: 'Should the report cover desktop only?',+ status: 'pending',+ }),+ ]);++ // The answer is what the next turn plans from.+ await service().decide(id, graph.decisions[0].id, 'all', 'Mobile matters for this launch');+ expect((await model().findById(id))!.status).toBe('running');+ const answered = (await service().graph(id)).decisions[0];+ expect(answered).toMatchObject({+ resolution: 'Mobile matters for this launch',+ resolvedOptionId: 'all',+ status: 'resolved',+ });+ });++ it('asks a takeover question as written and carries the chosen answer into the retry', async () => {+ const { goalId, state, taskId, turn } = await stuckGoal();+ await operationCaller(turn.id).submitOperationPlan({+ id: goalId,+ operationId: turn.id,+ plan: { action: 'escalate', reason: 'The PRs merged out of order', ask: waiveAsk },+ token: state.token,+ });+ await db.update(agentOperations).set({ status: 'done' }).where(eq(agentOperations.id, turn.id));+ await service().tick(goalId);++ expect(await service().tick(goalId)).toMatchObject({ outcome: 'waiting_human' });+ const gated = await service().graph(goalId);+ expect(gated.decisions).toHaveLength(1);+ const [gate] = gated.decisions;+ expect(gate).toMatchObject({+ options: waiveAsk.options,+ question: waiveAsk.question,+ recommendedOptionId: 'waive',+ });+ expect(gated.nodes.find((n) => n.id === gate.nodeId)!.description).toContain(+ 'The PRs merged out of order',+ );++ await service().decide(goalId, gate.id, 'waive', 'Order follows merge time');+ const task = await new TaskModel(db, userId).findById(taskId);+ expect(task!.status).toBe('backlog');+ const comments = await new TaskModel(db, userId).getComments(taskId);+ expect(comments.at(-1)!.content).toContain('Chosen: Waive it');+ expect(comments.at(-1)!.content).toContain('Guidance: Order follows merge time');+ });++ // Gates are labelled by option id, so an authored "retry" that retires the+ // Task would read "Retry task" on the card.+ it('refuses answers that reuse the coordinator option ids', async () => {+ const { goalId, state, turn } = await stuckGoal();+ await expect(+ operationCaller(turn.id).submitOperationPlan({+ id: goalId,+ operationId: turn.id,+ plan: {+ action: 'escalate',+ reason: 'Needs a call',+ ask: {+ question: 'Keep this result?',+ options: [+ { id: 'retry', label: 'Keep this result', effect: 'retire' },+ { id: 'redo', label: 'Redo it', effect: 'retry' },+ ],+ },+ },+ token: state.token,+ }),+ ).rejects.toThrow('reserved');+ });++ it('refuses a takeover question whose answers leave the blocked Task undecided', async () => {+ const { goalId, state, turn } = await stuckGoal();+ await expect(+ operationCaller(turn.id).submitOperationPlan({+ id: goalId,+ operationId: turn.id,+ plan: {+ action: 'escalate',+ reason: 'Needs a judge',+ ask: {+ question: 'Which judge?',+ options: [+ { id: 'a', label: 'A' },+ { id: 'b', label: 'B' },+ ],+ },+ },+ token: state.token,+ }),+ ).rejects.toThrow('needs an effect');+ });+});+/*** Codex review round 4. The acceptance guard was written for uninvited turns* ("verification exists, stop planning more work") but sat above the inviteddiff --git a/apps/server/src/services/goal/manager.ts b/apps/server/src/services/goal/manager.tsindex 9e98a6c2e4e..0ddf05a9fe4 100644--- a/apps/server/src/services/goal/manager.ts+++ b/apps/server/src/services/goal/manager.ts@@ -1,6 +1,11 @@import { createHash, randomUUID } from 'node:crypto';-import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import {+ GOAL_ACCEPTANCE_TASK_TITLE,+ GOAL_CLARIFICATION_OPTION,+ GOAL_COORDINATOR_ACTOR_ID,+ GOAL_MANAGER_QUESTION_TITLE,+} from '@lobechat/const/goal';import { buildGoalManagerPrompt } from '@lobechat/prompts';import type {GoalGraphSnapshot,@@ -28,10 +33,11 @@ import { readDeviceDispatchRoute } from '@/server/services/aiAgent/helpers/heterimport { TopicStartReservationError } from '@/server/services/aiAgent/topicStartReservation';import { deviceGateway } from '@/server/services/deviceGateway';+import { GoalBriefService } from './goalBriefs';import { TERMINAL_GOAL_STATUSES as finishedGoalStatuses } from './goalTraceRecorder';import {classifyRunFailure,- countDeviceOfflineRuns,+ countUnchargedRuns,DEFAULT_MANAGER_MAX_TURNS,nextDeviceOfflineRetryAt,QUOTA_RESET_MARGIN_MS,@@ -42,6 +48,58 @@ import { recoveryEligibility } from './supervisor/policy';import { goalWaitSchema, GoalWaitService } from './wait';const reason = z.string().trim().min(1).max(8000);+/**+ * The question an escalation puts to the owner. A bare reason left the gate+ * asking "retry or retire?" while the decision that actually blocked the goal —+ * waive a criterion, restore a closed PR — was buried in its text with no+ * button to answer it.+ */+/**+ * Option ids the coordinator and the planner own. Their gates are labelled by+ * id on the goal page and in the inbox, so an authored answer reusing one would+ * show the coordinator's label ("Retry task") over a different consequence.+ */+const RESERVED_ASK_OPTION_IDS = new Set<string>([+ 'fail',+ 'retire',+ 'retry',+ ...Object.values(GOAL_CLARIFICATION_OPTION),+]);++const goalAskSchema = z+ .object({+ question: z.string().trim().min(1).max(2000),+ options: z+ .array(+ z+ .object({+ id: z+ .string()+ .trim()+ .regex(/^[\w-]{1,40}$/),+ label: z.string().trim().min(1).max(120),+ description: z.string().trim().max(600).optional(),+ effect: z.enum(['retry', 'retire']).optional(),+ })+ .strict(),+ )+ .min(2)+ .max(4),+ recommendedOptionId: z.string().trim().optional(),+ })+ .strict()+ .refine((ask) => new Set(ask.options.map((option) => option.id)).size === ask.options.length, {+ message: 'Option ids must be unique',+ })+ .refine((ask) => ask.options.every((option) => !RESERVED_ASK_OPTION_IDS.has(option.id)), {+ message: `Option ids ${[...RESERVED_ASK_OPTION_IDS].join(', ')} are reserved; name the answer itself (e.g. "waive")`,+ })+ .refine(+ (ask) =>+ !ask.recommendedOptionId ||+ ask.options.some((option) => option.id === ask.recommendedOptionId),+ { message: 'recommendedOptionId must name one of the options' },+ );export const goalPlanSchema = z.discriminatedUnion('action', [z.object({@@ -78,7 +136,7 @@ export const goalPlanSchema = z.discriminatedUnion('action', [failedOperationId: z.string().min(1),}).strict(),- z.object({ action: z.literal('escalate'), reason }).strict(),+ z.object({ action: z.literal('escalate'), reason, ask: goalAskSchema.optional() }).strict(),]);type GoalPlan = z.infer<typeof goalPlanSchema>;const activeStatuses = new Set(['planning', 'running']);@@ -238,7 +296,7 @@ export const problemKey = (problem: { reason: string; taskId?: string }) =>*/export const answeredProblem = (state?: GoalManagerState) =>state?.consumed && state.problem && state.submitted- ? { key: state.problem, reason: state.submitted.reason }+ ? { ask: state.submitted.ask, key: state.problem, reason: state.submitted.reason }: undefined;export class GoalManagerService {@@ -567,6 +625,11 @@ export class GoalManagerService {};private graph = (db = this.db) => new GoalGraphModel(db, this.userId, this.workspaceId);+ private coordinatorGraph = (db = this.db) =>+ new GoalGraphModel(db, this.userId, this.workspaceId, {+ id: GOAL_COORDINATOR_ACTOR_ID,+ type: 'system',+ });private reviews = async (graph: GoalGraphSnapshot, db = this.db) => {const tasks = new TaskModel(db, this.userId, this.workspaceId);@@ -646,7 +709,9 @@ export class GoalManagerService {const goal = await model.lockById(goalId);if (goal && activeStatuses.has(goal.status)) {await model.updateStatus(goalId, 'paused');- await this.graph(db).recordGoalStatus(goalId, goal.status, 'paused', message);+ // The system paused it (a spent turn budget, an unconfirmed main Agent+ // turn), so the timeline must not file it as the owner's pause.+ await this.coordinatorGraph(db).recordGoalStatus(goalId, goal.status, 'paused', message);}});return { goalId, outcome: 'no_progress', message };@@ -923,7 +988,7 @@ export class GoalManagerService {runs[0].operationId,): undefined;- return !recoveryEligibility(graph, failed, op, false, countDeviceOfflineRuns(runs)).eligible;+ return !recoveryEligibility(graph, failed, op, false, countUnchargedRuns(runs)).eligible;};private startTurn = async (@@ -1366,7 +1431,7 @@ export class GoalManagerService {if (!task ||runs[0]?.operationId !== plan.failedOperationId ||- !recoveryEligibility(graph, task, failure, false, countDeviceOfflineRuns(runs)).eligible+ !recoveryEligibility(graph, task, failure, false, countUnchargedRuns(runs)).eligible)throw new TRPCError({code: 'CONFLICT',@@ -1381,6 +1446,44 @@ export class GoalManagerService {)))throw new TRPCError({ code: 'CONFLICT', message: 'Task changed before retry' });+ } else if (plan.action === 'escalate' && state.problem && plan.ask) {+ // A takeover question is answered on the failed Task's gate, so every+ // answer has to say what happens to that Task — an answer that leaves it+ // failed would only reopen the same gate on the next tick.+ if (plan.ask.options.some((option) => !option.effect))+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message:+ 'Every option of a takeover question needs an effect (retry or retire) for the blocked Task',+ });+ } else if (plan.action === 'escalate' && !state.problem && plan.ask) {+ // A question with answers is asked, not parked: it opens a gate the+ // owner can answer from anywhere, and the answer wakes the next turn.+ const node = await authored.createNode(goalId, {+ description: plan.reason,+ kind: 'decision',+ status: 'waiting',+ title: GOAL_MANAGER_QUESTION_TITLE,+ });+ if (!node) throw new TRPCError({ code: 'NOT_FOUND', message: 'Goal not found' });+ const problemNode = graph.nodes.find((n) => n.kind === 'problem');+ if (problemNode) await authored.createEdge(goalId, problemNode.id, node.id, 'leads_to');+ const decision = await authored.createDecision(goalId, node.id, {+ authority: 'user',+ options: plan.ask.options,+ question: plan.ask.question,+ recommendedOptionId: plan.ask.recommendedOptionId,+ requestedUserId: this.userId,+ });+ await model.updateStatus(goalId, 'review');+ await authored.recordGoalStatus(goalId, goal.status, 'review', plan.reason);+ if (decision)+ await new GoalBriefService(db, this.userId, this.workspaceId).openDecision(goal, {+ decisionId: decision.id,+ options: decision.options,+ question: decision.question,+ recommendedOptionId: decision.recommendedOptionId,+ });} else if (plan.action === 'escalate' && !state.problem) {// Only an ORDINARY planning turn pauses the Goal here. A takeover turn has// a gate waiting behind it for this exact problem, and the coordinator@@ -1396,6 +1499,7 @@ export class GoalManagerService {action: plan.action,reason: plan.reason,...(plan.action === 'retry' ? { taskId: plan.taskId } : {}),+ ...(plan.action === 'escalate' && plan.ask ? { ask: plan.ask } : {}),},readyForAcceptance: plan.action === 'verify',replanReason: undefined,diff --git a/apps/server/src/services/goal/recoveryPolicy.test.ts b/apps/server/src/services/goal/recoveryPolicy.test.tsindex 5a7fd768283..ae3643171ae 100644--- a/apps/server/src/services/goal/recoveryPolicy.test.ts+++ b/apps/server/src/services/goal/recoveryPolicy.test.ts@@ -5,6 +5,7 @@ import {classifyRunFailure,countChargedTaskAttempts,countConsecutiveDeviceOfflineRuns,+ countUnchargedRuns,DEFAULT_MANAGER_MAX_TURNS,managerTurnsSpent,MIN_OPERATION_LEASE_TIMEOUT_MS,@@ -124,3 +125,32 @@ describe('classifyRunFailure', () => {expect(classifyRunFailure(error, text).kind).toBe(kind);});});++describe('machine-failure run accounting', () => {+ it('marks a run that hit a usage limit or a transient fault as uncharged', () => {+ expect(+ resolveFailedRunStatus("You've hit your session limit · resets 4:30am (Asia/Shanghai)"),+ ).toBe('quota_limited');+ expect(+ resolveFailedRunStatus(+ "Server discarded the agent's output (operation-not-running): this run is no longer the topic's active operation, so nothing it produced was saved",+ ),+ ).toBe('transient_failed');+ expect(resolveFailedRunStatus('Working directory does not exist: /Users/user/x')).toBe(+ 'failed',+ );+ });++ it('charges none of the machine-failure runs to the attempt budget', () => {+ const runs = [+ { status: 'quota_limited' },+ { status: 'transient_failed' },+ { status: 'device_offline' },+ { status: 'failed' },+ { status: 'completed' },+ ];+ expect(countChargedTaskAttempts({ totalTopics: runs.length }, countUnchargedRuns(runs))).toBe(+ 2,+ );+ });+});diff --git a/apps/server/src/services/goal/recoveryPolicy.ts b/apps/server/src/services/goal/recoveryPolicy.tsindex 5b319b63eb2..a1933030cb7 100644--- a/apps/server/src/services/goal/recoveryPolicy.ts+++ b/apps/server/src/services/goal/recoveryPolicy.ts@@ -1,8 +1,14 @@-import { DEVICE_OFFLINE_RUN_STATUS } from '@lobechat/const/goal';+import {+ DEVICE_OFFLINE_RUN_STATUS,+ QUOTA_LIMITED_RUN_STATUS,+ TRANSIENT_FAILED_RUN_STATUS,+} from '@lobechat/const/goal';import type { GoalItem, TaskItem } from '@lobechat/types';import { HETERO_DISPATCH_ERROR_HEADLINES } from '@/server/services/aiAgent/helpers/heteroErrors';+import { classifyGoalFailure } from './failureClass';+/*** Attempts a Task gets before the coordinator opens a decision gate, when the* goal does not set its own.@@ -124,13 +130,44 @@ export const countConsecutiveDeviceOfflineRuns = (runs: readonly { status: strin};/**- * Attempts charged to a Task's budget: every run it produced except the ones- * its device lost. Those retry on the offline schedule above instead.+ * Runs that ended on a machine problem nothing judged: the device was gone, a+ * usage limit was hit, or a transport fault lost the run. Each retries on its+ * own bounded schedule instead of spending the attempt budget.+ */+const UNCHARGED_RUN_STATUSES = new Set<string>([+ DEVICE_OFFLINE_RUN_STATUS,+ QUOTA_LIMITED_RUN_STATUS,+ TRANSIENT_FAILED_RUN_STATUS,+]);++export const isUnchargedRun = (run: { status: string }): boolean =>+ UNCHARGED_RUN_STATUSES.has(run.status);++/** Runs not charged to the Task's attempt budget (see `UNCHARGED_RUN_STATUSES`). */+export const countUnchargedRuns = (runs: readonly { status: string }[]): number =>+ runs.filter(isUnchargedRun).length;++/**+ * Consecutive runs that ended with `status`, `runs` newest first. Like the+ * offline count, the streak restarts once any other run ends, so a usage limit+ * hit once a week is not held to last week's retries.+ */+export const countConsecutiveRunsWithStatus = (+ runs: readonly { status: string }[],+ status: string,+): number => {+ const firstOther = runs.findIndex((run) => run.status !== status);+ return firstOther === -1 ? runs.length : firstOther;+};++/**+ * Attempts charged to a Task's budget: every run it produced except the+ * uncharged ones (`countUnchargedRuns`). Those retry on their own schedules.*/export const countChargedTaskAttempts = (task: Pick<TaskItem, 'totalTopics'>,- deviceOfflineRuns: number,-): number => Math.max(0, (task.totalTopics ?? 0) - deviceOfflineRuns);+ unchargedRuns: number,+): number => Math.max(0, (task.totalTopics ?? 0) - unchargedRuns);/*** Dispatch failures that only say the device is not reachable right now. A@@ -157,11 +194,16 @@ export const isDeviceUnavailableFailure = (error?: string | null): boolean =>/*** The `task_topics.status` a run that errored ends with. Every writer of a failed* run goes through this, so the dispatch result and a lifecycle hook delivered- * later agree on an offline run instead of the later one turning it back into a- * charged failure.+ * later agree on an uncharged run (offline device, usage limit, transport fault)+ * instead of the later one turning it back into a charged failure.*/-export const resolveFailedRunStatus = (error?: string | null): string =>- isDeviceUnavailableFailure(error) ? DEVICE_OFFLINE_RUN_STATUS : 'failed';+export const resolveFailedRunStatus = (error?: string | null): string => {+ if (isDeviceUnavailableFailure(error)) return DEVICE_OFFLINE_RUN_STATUS;+ const failure = classifyGoalFailure(error);+ if (failure.class === 'quota') return QUOTA_LIMITED_RUN_STATUS;+ if (failure.class === 'transient') return TRANSIENT_FAILED_RUN_STATUS;+ return 'failed';+};/*** What a failed run's error says about retrying it.diff --git a/apps/server/src/services/goal/supervisor/index.ts b/apps/server/src/services/goal/supervisor/index.tsindex 3852b3aedd7..b432bb2c1ff 100644--- a/apps/server/src/services/goal/supervisor/index.ts+++ b/apps/server/src/services/goal/supervisor/index.ts@@ -21,7 +21,7 @@ import type { LobeChatDatabase } from '@/database/type';import { AiAgentService } from '@/server/services/aiAgent';import { resolveGoalModelConfig } from '../modelConfig';-import { countDeviceOfflineRuns } from '../recoveryPolicy';+import { countUnchargedRuns } from '../recoveryPolicy';import { scheduleGoalAdvance } from '../scheduler';import { claimGoalTask } from '../taskClaim';import {@@ -165,7 +165,7 @@ export class GoalSupervisorService {task,failedOperation,statusAuthoredByActor(await taskModel.getActivities(task.id, 20), task.status),- countDeviceOfflineRuns(runs),+ countUnchargedRuns(runs),);if (eligibility.eligible && (await this.budgetBlocked(graph))) {eligibility = {@@ -341,7 +341,7 @@ export class GoalSupervisorService {await new TaskModel(tx, this.userId, this.workspaceId).getActivities(task.id, 20),currentTask.status,),- countDeviceOfflineRuns(currentRuns),+ countUnchargedRuns(currentRuns),).eligible ||(await new GoalSupervisorService(tx, this.userId, this.workspaceId).budgetBlocked(currentGraph,diff --git a/apps/server/src/services/goal/supervisor/policy.test.ts b/apps/server/src/services/goal/supervisor/policy.test.tsindex 5acd46a2dbf..9a24ecf52d2 100644--- a/apps/server/src/services/goal/supervisor/policy.test.ts+++ b/apps/server/src/services/goal/supervisor/policy.test.ts@@ -106,6 +106,19 @@ describe('supervisor recovery authority', () => {).toBe(true);});+ it('recovers the transient faults that used to fall outside the policy', () => {+ // Every real incident the policy escalated was one of these, and a fresh attempt+ // got past each of them when a person pressed Retry.+ for (const error of [+ "Server discarded the agent's output (operation-not-running): this run is no longer the topic's active operation, so nothing it produced was saved",+ 'Failed to persist tool_result for message msg_8ggMzr8jCOsJL51nwA',+ '{"error":"TIMEOUT","success":false}',+ ])+ expect(+ recoveryEligibility(graph, { ...task, error, status: 'paused' }, settled).eligible,+ ).toBe(true);+ });+it('keeps a dispatch failure a retry cannot fix, or whose outcome is unknown, with a person', () => {for (const error of ['DEVICE_GATEWAY_UNAUTHORIZED',diff --git a/apps/server/src/services/goal/supervisor/policy.ts b/apps/server/src/services/goal/supervisor/policy.tsindex 65987d8178c..1bbf60eaf4c 100644--- a/apps/server/src/services/goal/supervisor/policy.ts+++ b/apps/server/src/services/goal/supervisor/policy.ts@@ -9,6 +9,7 @@ import { isAgentOperationInFlight } from '@lobechat/types';import type { AgentOperationItem } from '@/database/schemas/agentOperations';import { HETERO_DISPATCH_ERROR_HEADLINES } from '@/server/services/aiAgent/helpers/heteroErrors';+import { classifyGoalFailure } from '../failureClass';import {classifyRunFailure,countChargedTaskAttempts,@@ -97,8 +98,8 @@ export const recoveryEligibility = (operation?: AgentOperationItem,/** Whether the Task's current status was written by a person or an agent tool. */actorAuthoredStatus = false,- /** Runs the Task's device lost; they are not charged to its attempt budget. */- deviceOfflineRuns = 0,+ /** Runs lost to a machine problem; they are not charged to its attempt budget. */+ unchargedRuns = 0,): { eligible: boolean; reason: string } => {if (!graph.goal.config?.supervision?.enabled && !graph.goal.config?.manager)return { eligible: false, reason: 'Supervision is disabled' };@@ -126,7 +127,7 @@ export const recoveryEligibility = (if (actorAuthoredStatus) {return { eligible: false, reason: 'Someone set this status themselves' };}- if (countChargedTaskAttempts(task, deviceOfflineRuns) >= resolveTaskAttemptBudget(graph.goal)) {+ if (countChargedTaskAttempts(task, unchargedRuns) >= resolveTaskAttemptBudget(graph.goal)) {return { eligible: false, reason: 'Task attempt budget exhausted' };}const error = `${operation?.error?.type ?? ''} ${operation?.error?.message ?? ''} ${task.error ?? ''}`;@@ -147,7 +148,16 @@ export const recoveryEligibility = (// an actor can author — a Task marked failed through the API, a settled run someone// reopened — arrives looking exactly like a dropped dispatch. Recognising the// failures instead keeps an authored decision with the person who made it.- if (!isRetryableDispatchFailure(error) && failure.kind !== 'transient') {+ //+ // The transient class is part of that allowlist: every real incident this policy+ // escalated was a run the server discarded (`operation-not-running`), a tool+ // result that did not persist, or a gateway timeout — failures a fresh attempt+ // got past each time a person pressed Retry.+ if (+ !isRetryableDispatchFailure(error) &&+ failure.kind !== 'transient' &&+ classifyGoalFailure(error).class !== 'transient'+ ) {return {eligible: false,reason: 'Failure is outside the recognised transport recovery policy',diff --git a/apps/server/src/services/goal/taskRecoveryCoordinator.ts b/apps/server/src/services/goal/taskRecoveryCoordinator.tsindex 456b0fce6f0..68cc42b514e 100644--- a/apps/server/src/services/goal/taskRecoveryCoordinator.ts+++ b/apps/server/src/services/goal/taskRecoveryCoordinator.ts@@ -10,7 +10,7 @@ import { TaskRunnerService } from '@/server/services/taskRunner';import {countChargedTaskAttempts,- countDeviceOfflineRuns,+ countUnchargedRuns,isDeviceUnavailableFailure,resolveTaskAttemptBudget,resolveTaskMaxSteps,@@ -68,12 +68,13 @@ export class TaskRecoveryCoordinator {task: TaskItem;}): Promise<TaskRecoveryResult> => {const { goal, task } = params;- // A run its device lost was never judged, so it does not spend the budget;- // the coordinator's offline schedule bounds those retries instead.+ // A run lost to a machine problem was never judged, so it does not spend the+ // budget; the coordinator's offline / quota / transient schedules bound those+ // retries instead.const runs = await new TaskTopicModel(this.db, this.userId, this.workspaceId).findByTaskId(task.id,);- const attempts = countChargedTaskAttempts(task, countDeviceOfflineRuns(runs));+ const attempts = countChargedTaskAttempts(task, countUnchargedRuns(runs));const attemptBudget = resolveTaskAttemptBudget(goal);if (attempts >= attemptBudget) return { outcome: 'exhausted-rounds' };diff --git a/apps/server/src/services/taskLifecycle/index.ts b/apps/server/src/services/taskLifecycle/index.tsindex 165aca9f453..318c7ab3849 100644--- a/apps/server/src/services/taskLifecycle/index.ts+++ b/apps/server/src/services/taskLifecycle/index.ts@@ -397,19 +397,28 @@ export class TaskLifecycleService {// user regardless of what happens to the scheduling state below. The topic// id rides the structured `topicId` field (it also powers the card's// "View run" shortcut), never the headline.- await this.briefModel.create({- actions: errorActions,- agentId: currentTask?.assigneeAgentId || undefined,- // Persist the structured cause for observability / future remedy mapping.- metadata: errorCode ? { error: { code: errorCode } } : undefined,- priority: 'urgent',- summary,- taskId,- title: tHome('inbox.error.title'),- topicId,- trigger: 'task',- type: 'error',- });+ // A Goal Task's failed run is the coordinator's to recover: it retries,+ // reroutes or opens a decision gate, and that gate is the brief the+ // person gets. An urgent error card per failed run asked them to act on+ // something the goal was already handling — the same reason Goal rounds+ // never synthesize result briefs above. Only runs the coordinator+ // dispatched count: a manual rerun of a Task kept under a paused or+ // finished goal has nobody recovering it, so its failure still surfaces.+ const coordinatedByGoal = params.runTrigger === 'goal';+ if (!coordinatedByGoal)+ await this.briefModel.create({+ actions: errorActions,+ agentId: currentTask?.assigneeAgentId || undefined,+ // Persist the structured cause for observability / future remedy mapping.+ metadata: errorCode ? { error: { code: errorCode } } : undefined,+ priority: 'urgent',+ summary,+ taskId,+ title: tHome('inbox.error.title'),+ topicId,+ trigger: 'task',+ type: 'error',+ });const runTrigger = params.runTrigger ?? 'manual';const isAutomationTick = runTrigger === 'schedule' || runTrigger === 'heartbeat';diff --git a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts b/apps/server/src/services/taskLifecycle/onTopicComplete.test.tsindex 43b3541269f..76c1754040b 100644--- a/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts+++ b/apps/server/src/services/taskLifecycle/onTopicComplete.test.ts@@ -681,6 +681,47 @@ describe('TaskLifecycleService.onTopicComplete', () => {);});+ // A Goal Task's failed run is the coordinator's to recover, and the gate it+ // opens is the brief the person gets. An urgent error card per failed run+ // asked them to act on something the goal was already handling.+ it('leaves a Goal Task failure to the coordinator instead of an error brief', async () => {+ const task = baseTask({ automationMode: null });+ findById.mockResolvedValue(task);++ await service.onTopicComplete({+ errorMessage: 'boom',+ operationId: 'op-1',+ reason: 'error',+ runTrigger: 'goal',+ taskId: 'task-1',+ taskIdentifier: 'TASK-1',+ topicId: 'topic-1',+ });++ expect(createBrief).not.toHaveBeenCalledWith(expect.objectContaining({ type: 'error' }));+ });++ // Only the coordinator's own runs are recovered by it: a manual rerun of a+ // Task kept under a paused or finished goal has nobody watching it.+ it('still sends the error brief for a manual rerun of a Goal Task', async () => {+ const task = baseTask({ automationMode: null });+ findById.mockResolvedValue(task);++ await service.onTopicComplete({+ errorMessage: 'boom',+ operationId: 'op-1',+ reason: 'error',+ runTrigger: 'manual',+ taskId: 'task-1',+ taskIdentifier: 'TASK-1',+ topicId: 'topic-1',+ });++ expect(createBrief).toHaveBeenCalledWith(+ expect.objectContaining({ priority: 'urgent', type: 'error' }),+ );+ });+it('error brief keeps internal ids out of the user-facing copy', async () => {const task = baseTask({ automationMode: 'schedule' });findById.mockResolvedValue(task);diff --git a/apps/server/src/services/taskRunner/buildTaskPrompt.ts b/apps/server/src/services/taskRunner/buildTaskPrompt.tsindex d2dabd171f6..6189313fce9 100644--- a/apps/server/src/services/taskRunner/buildTaskPrompt.ts+++ b/apps/server/src/services/taskRunner/buildTaskPrompt.ts@@ -15,7 +15,7 @@ import { extractFileIdsFromEditorData } from '@/server/services/file/extractFileimport { resolveAttachmentMetadata } from '@/server/services/file/resolveAttachments';import {countChargedTaskAttempts,- countDeviceOfflineRuns,+ countUnchargedRuns,resolveTaskAttemptBudget,} from '@/server/services/goal/recoveryPolicy';import { resolveTaskAcceptance } from '@/server/services/verify/taskAcceptance';@@ -39,14 +39,15 @@ const resolveGoalLoopContext = async (if (!goal || !task.totalTopics) return undefined;const budget = resolveTaskAttemptBudget(goal);- // Runs its device lost are not rounds the budget counts, so the agent is not- // told it is on a later round than the coordinator thinks.- const offlineRuns = countDeviceOfflineRuns(+ // Runs lost to a machine problem (offline device, usage limit, transport fault)+ // are not rounds the budget counts, so the agent is not told it is on a later+ // round than the coordinator thinks.+ const unchargedRuns = countUnchargedRuns(await deps.taskTopicModel.findByTaskId(task.id).catch(() => []),);const context: TaskRunPromptGoalLoop = {maxRounds: Number.isFinite(budget) ? budget : null,- round: countChargedTaskAttempts(task, offlineRuns) + 1,+ round: countChargedTaskAttempts(task, unchargedRuns) + 1,};try {diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 5df61e7ef17..1a16b4c29d7 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -510,7 +510,7 @@"goalEmpty.step1.title": "Set the outcome and the bar","goalEmpty.step2.desc": "Each round is one full agent run; its output, time and cost all hang off this goal.","goalEmpty.step2.title": "The agent runs a round on its own",- "goalEmpty.step3.desc": "Every check is judged one by one. All passed means achieved; anything needing your call stops at pending acceptance.",+ "goalEmpty.step3.desc": "Every check is judged one by one. All passed means achieved; anything needing your call stops and asks you.","goalEmpty.step3.title": "Acceptance runs every round","goalEmpty.title": "Chase goals without limits","goalExperiment.acceptance": "View verification",@@ -565,7 +565,7 @@"goalList.status.error": "Needs attention","goalList.status.paused": "Paused","goalList.status.planning": "Planning",- "goalList.status.review": "Pending acceptance",+ "goalList.status.review": "Needs your decision","goalList.status.running": "Pursuing","goalList.status.verifying": "Verifying","goalList.status.waiting": "Waiting",@@ -577,15 +577,15 @@"goalPage.description": "Track what this agent is pursuing and how close each goal is to acceptance.","goalPage.filter.achieved": "Completed","goalPage.filter.all": "All",- "goalPage.filter.review": "Needs review",+ "goalPage.filter.review": "Needs you","goalPage.filter.running": "In progress","goalPage.filteredEmptyDescription": "Switch to All to see every goal.","goalPage.filteredEmptyTitle": "No goals in this view","goalPage.listTitle": "Goal list","goalPage.loadMore": "Load more","goalPage.loadingProgress": "Loading acceptance progress…",- "goalPage.metrics.delivered": "Delivered",- "goalPage.metrics.pursuing": "Open",+ "goalPage.metrics.delivered": "Needs you",+ "goalPage.metrics.pursuing": "Others","goalPage.metrics.total": "Total goals","goalPage.title": "Overview","goalPage.view.card": "Cards",@@ -648,6 +648,28 @@"goalProcess.clarify.skip": "Use the agent’s assumptions","goalProcess.clarify.submit": "Start with these answers","goalProcess.clarify.title": "Clarify the goal before work starts",+ "goalProcess.decision.asks.agentQuestion": "needs your review",+ "goalProcess.decision.asks.goalAcceptance": "needs your review on the goal acceptance",+ "goalProcess.decision.asks.judgment": "needs your review on a stuck task",+ "goalProcess.decision.asks.machine": "needs you to sort it out",+ "goalProcess.decision.attempts_one": "{{count}} attempt",+ "goalProcess.decision.attempts_other": "{{count}} attempts",+ "goalProcess.decision.context.decision": "Your call",+ "goalProcess.decision.context.task": "Task",+ "goalProcess.decision.effect.abandonAcceptance": "Stop acceptance and end the goal without a verdict.",+ "goalProcess.decision.effect.fail": "End the goal and record it as failed.",+ "goalProcess.decision.effect.fixedRetry": "Run the task again once the setup is fixed.",+ "goalProcess.decision.effect.retire": "Drop this task. The goal moves on without it.",+ "goalProcess.decision.effect.retry": "Send the task back for another attempt. Your note is written into its instructions.",+ "goalProcess.decision.effect.retryAcceptance": "Run the goal-level acceptance again.",+ "goalProcess.decision.submit": "Decide",+ "goalProcess.decision.summary.agentQuestion": "While working on the goal, the main Agent hit a call only you can make. It lays out the options and its recommendation below.",+ "goalProcess.decision.summary.goalAcceptance": "The goal-level acceptance did not pass. Decide whether to run it again, abandon it, or record the goal as failed.",+ "goalProcess.decision.summary.judgment": "It used up its automatic retries without passing acceptance. Decide whether it gets another attempt or is dropped.",+ "goalProcess.decision.summary.machine": "It could not run because of the run environment, not the work itself. Fix the environment, then retry.",+ "goalProcess.decision.summary.thisTask": "this task",+ "goalProcess.decision.system": "Run environment",+ "goalProcess.decision.viewRun": "Open task","goalProcess.deliverables.empty": "Nothing delivered yet. Documents, generated files and linked resources a task persists show up here — anything left only on a local path does not.","goalProcess.deliverables.from": "From “{{title}}”","goalProcess.deliverables.title": "Deliverables",@@ -677,17 +699,29 @@"goalProcess.gate.notePlaceholder": "Optional — goes into the next attempt instructions","goalProcess.gate.option.assume": "Go with the assumption","goalProcess.gate.option.fail": "Fail goal",+ "goalProcess.gate.option.fixedRetry": "I fixed it — retry","goalProcess.gate.option.retire": "Retire work","goalProcess.gate.option.retry": "Retry work","goalProcess.gate.reason.attemptBudgetExhausted": "The attempt budget for this work is used up","goalProcess.gate.reason.costBudgetExhausted": "The goal cost budget is used up",+ "goalProcess.gate.reason.deviceStayedOffline": "The device this task runs on stayed offline through every automatic retry","goalProcess.gate.reason.goalAcceptanceFailed": "Goal-level acceptance did not pass",+ "goalProcess.gate.reason.quotaFarReset": "The usage limit ({{error}}) does not reset until {{at}}, more than a day away. Switch the agent to another account or provider, or retry after the reset.",+ "goalProcess.gate.reason.quotaRetriesSpent": "Still over the usage limit ({{error}}) after {{count}} automatic retries over {{duration}}. Check the plan, or switch the agent to another account or provider.","goalProcess.gate.reason.recoveryFailed": "Automatic recovery could not start the next attempt","goalProcess.gate.reason.runError": "The run stopped with an error ({{code}})",+ "goalProcess.gate.reason.setupCli": "The run could not start ({{error}}). Install the CLI on the device the agent runs on and make sure it is on PATH.",+ "goalProcess.gate.reason.setupCredentials": "The provider refused the run ({{error}}). Update the credentials, plan or model in the agent settings.",+ "goalProcess.gate.reason.setupDevice": "The device is unavailable ({{error}}). Reconnect it, or bind the agent to another online device.",+ "goalProcess.gate.reason.setupGateway": "The device gateway is not set up ({{error}}). Configure it on the server, or switch the agent to a connected local device.",+ "goalProcess.gate.reason.setupWorkingDirectory": "The working directory {{path}} does not exist on the device the agent runs on. Create it there, or point the agent at a directory that exists.",+ "goalProcess.gate.reason.transientRetriesSpent": "The run failed the same way {{count}} times over {{duration}} ({{error}}). Check the device, its network and the agent gateway.","goalProcess.gate.reason.verifyFailed": "Task {{id}} did not pass verification","goalProcess.gate.reason.verifyInternalError": "Verification could not run (internal error); this delivery was not evaluated","goalProcess.gate.recommended": "recommended",+ "goalProcess.gate.title.agentQuestion": "Answer the main Agent's question","goalProcess.gate.title.clarifyGoal": "Clarify the goal before work starts",+ "goalProcess.gate.title.fixSetup": "Fix the setup, then retry","goalProcess.gate.title.goalAcceptance": "Decide the goal acceptance outcome","goalProcess.gate.title.recoverTask": "Decide what happens to the failed task","goalProcess.graph.bridgeHops_one": "via {{count}} step not shown",@@ -939,6 +973,16 @@"goalProcess.result.unfinished.unmetCriteria": "Unmet criteria","goalProcess.resume": "Resume","goalProcess.running.elapsed": "Running {{duration}}",+ "goalProcess.signOff.accept": "Sign off",+ "goalProcess.signOff.acceptEffect": "Close the goal as delivered.",+ "goalProcess.signOff.accepted": "Signed off",+ "goalProcess.signOff.description": "Goal-level acceptance passed. Your sign-off closes the goal.",+ "goalProcess.signOff.islandSubtitle": "is done and waiting for your sign-off",+ "goalProcess.signOff.notePlaceholder": "What should change? The Agent reworks the delivery with this.",+ "goalProcess.signOff.question": "Do you accept what this goal delivered?",+ "goalProcess.signOff.requestChanges": "Request changes",+ "goalProcess.signOff.requestChangesEffect": "Send it back to the Agent. Say what to change in the notes.",+ "goalProcess.signOff.sentBack": "Sent back for changes","goalProcess.stale.description": "No heartbeat for {{duration}}. The next advance marks this attempt lost and starts a fresh one — it does not count as a failure.","goalProcess.summary.done": "Done · {{count}} attempts","goalProcess.summary.gateOpen": "Waiting for your decision",@@ -968,7 +1012,7 @@"goalTask.status.paused": "Paused","goalTask.status.planning": "Planning","goalTask.status.repairing": "Repairing",- "goalTask.status.review": "Pending acceptance",+ "goalTask.status.review": "Needs your decision","goalTask.status.running": "Executing","goalTask.status.verifying": "Verifying","goalTask.status.waiting": "Waiting",diff --git a/locales/en-US/home.json b/locales/en-US/home.jsonindex f7295794a73..d2aab478f9f 100644--- a/locales/en-US/home.json+++ b/locales/en-US/home.json@@ -4,13 +4,19 @@"agentSelection.noSelected": "No agents selected","agentSelection.search": "No matching agents found","brief.action.acknowledge": "Acknowledge",+ "brief.action.answer": "Answer","brief.action.approve": "Approve","brief.action.confirm": "Confirm","brief.action.confirmDone": "Confirm complete",+ "brief.action.fail": "Fail goal","brief.action.feedback": "Feedback","brief.action.ignore": "Ignore",+ "brief.action.openGoal": "Open goal",+ "brief.action.requestChanges": "Request changes",+ "brief.action.retire": "Retire task","brief.action.retry": "Retry","brief.action.review": "Go to acceptance",+ "brief.action.signOff": "Sign off","brief.action.upgrade": "Upgrade plan","brief.actionFailed": "That didn't go through. Please try again.","brief.addFeedback": "Share feedback",@@ -37,6 +43,11 @@"brief.editResult": "Edit","brief.expandAll": "Show more","brief.feedbackSent": "Feedback shared",+ "brief.goal.clarify.title": "Goal \"{{goal}}\" has questions before it starts",+ "brief.goal.decision.title": "Goal \"{{goal}}\" needs your decision",+ "brief.goal.recommended": "Recommended: {{option}}",+ "brief.goal.signOff.summary": "Goal-level acceptance passed. Sign it off to close the goal, or request changes to send it back.",+ "brief.goal.signOff.title": "Goal \"{{goal}}\" is done. Sign it off","brief.resolved": "Marked as resolved","brief.title": "Brief","brief.viewAllTasks": "View all tasks",@@ -111,7 +122,7 @@"homePromoBanner.label": "{{model}} is now available","inbox.author.scheduled": "Scheduled","inbox.error.title": "Run failed",- "inbox.goals.review": "Pending acceptance",+ "inbox.goals.review": "Needs your decision","inbox.goals.running": "In progress","inbox.goals.showAll": "Show all {{count}}","inbox.goals.title": "Goals",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex ac5be50efd9..c3f426f4cf3 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -510,7 +510,7 @@"goalEmpty.step1.title": "定下结果与验收标准","goalEmpty.step2.desc": "每一轮是一次完整的 Agent 运行,产出、耗时和花费都挂在这个目标下。","goalEmpty.step2.title": "Agent 自主跑一轮",- "goalEmpty.step3.desc": "逐条判定验收检查项。全部通过即「已达成」;需要你拍板的会停在「待验收」。",+ "goalEmpty.step3.desc": "逐条判定验收检查项。全部通过即「已达成」;需要你拍板的会停下来问你。","goalEmpty.step3.title": "每轮自动验收","goalEmpty.title": "追逐目标,永无止境","goalExperiment.acceptance": "查看验收",@@ -565,7 +565,7 @@"goalList.status.error": "需要处理","goalList.status.paused": "已暂停","goalList.status.planning": "规划中",- "goalList.status.review": "待验收",+ "goalList.status.review": "等你决定","goalList.status.running": "追逐中","goalList.status.verifying": "验证中","goalList.status.waiting": "等待中",@@ -577,15 +577,15 @@"goalPage.description": "掌握 Agent 正在追逐什么,以及每个目标距离验收还有多远。","goalPage.filter.achieved": "已完成","goalPage.filter.all": "全部",- "goalPage.filter.review": "待审阅",+ "goalPage.filter.review": "等你处理","goalPage.filter.running": "进行中","goalPage.filteredEmptyDescription": "切换到“全部”可查看所有目标。","goalPage.filteredEmptyTitle": "该筛选下暂无目标","goalPage.listTitle": "目标列表","goalPage.loadMore": "加载更多","goalPage.loadingProgress": "正在加载验收进度…",- "goalPage.metrics.delivered": "已交付",- "goalPage.metrics.pursuing": "待处理",+ "goalPage.metrics.delivered": "等你处理",+ "goalPage.metrics.pursuing": "其余","goalPage.metrics.total": "目标总数","goalPage.title": "概览","goalPage.view.card": "卡片",@@ -648,6 +648,28 @@"goalProcess.clarify.skip": "都按 Agent 的假设来","goalProcess.clarify.submit": "按这些回答开工","goalProcess.clarify.title": "开工前先确认目标",+ "goalProcess.decision.asks.agentQuestion": "需要你的审阅",+ "goalProcess.decision.asks.goalAcceptance": "需要你审阅目标验收",+ "goalProcess.decision.asks.judgment": "需要你审阅卡住的任务",+ "goalProcess.decision.asks.machine": "需要你处理一下",+ "goalProcess.decision.attempts_one": "{{count}} 次尝试",+ "goalProcess.decision.attempts_other": "{{count}} 次尝试",+ "goalProcess.decision.context.decision": "需要你决定",+ "goalProcess.decision.context.task": "任务",+ "goalProcess.decision.effect.abandonAcceptance": "停止验收,目标结束但不下结论",+ "goalProcess.decision.effect.fail": "结束目标,记为未达成",+ "goalProcess.decision.effect.fixedRetry": "确认环境修好后重新执行这项任务",+ "goalProcess.decision.effect.retire": "放弃这项任务,目标在没有它的情况下继续推进",+ "goalProcess.decision.effect.retry": "把任务退回重做,补充说明会写进下一次执行的指令",+ "goalProcess.decision.effect.retryAcceptance": "重新跑一次目标验收",+ "goalProcess.decision.submit": "确定",+ "goalProcess.decision.summary.agentQuestion": "主 Agent 在推进目标时遇到一个只有你能拍板的问题,下面是它给出的选项和推荐。",+ "goalProcess.decision.summary.goalAcceptance": "目标的整体验收没有通过,需要你决定重新验收、放弃验收,还是判定目标失败。",+ "goalProcess.decision.summary.judgment": "自动重试已经用完,仍没有通过验收,需要你决定是再试一次还是放弃。",+ "goalProcess.decision.summary.machine": "因为运行环境的问题没能执行,不是任务本身的问题;把环境修好后重试即可。",+ "goalProcess.decision.summary.thisTask": "这项任务",+ "goalProcess.decision.system": "运行环境",+ "goalProcess.decision.viewRun": "查看任务","goalProcess.deliverables.empty": "还没有交付物。任务写入产品的文档、生成的文件和关联资源会出现在这里——只留在本地路径上的产物不会。","goalProcess.deliverables.from": "来自「{{title}}」","goalProcess.deliverables.title": "交付物",@@ -677,17 +699,29 @@"goalProcess.gate.notePlaceholder": "可选,会写进下一次尝试的指令","goalProcess.gate.option.assume": "按 Agent 的假设来","goalProcess.gate.option.fail": "判定目标失败",+ "goalProcess.gate.option.fixedRetry": "已修好,重试","goalProcess.gate.option.retire": "放弃这项任务","goalProcess.gate.option.retry": "重试这项任务","goalProcess.gate.reason.attemptBudgetExhausted": "这项任务的尝试次数已用完","goalProcess.gate.reason.costBudgetExhausted": "目标的成本预算已用完",+ "goalProcess.gate.reason.deviceStayedOffline": "任务所在的设备在所有自动重试期间一直离线","goalProcess.gate.reason.goalAcceptanceFailed": "目标整体验收未通过",+ "goalProcess.gate.reason.quotaFarReset": "用量额度({{error}})要到 {{at}} 才恢复,超过一天。可以把 Agent 换到别的账号或服务商,或等额度恢复后再重试。",+ "goalProcess.gate.reason.quotaRetriesSpent": "自动重试 {{count}} 次、历时 {{duration}},仍然超出用量额度({{error}})。请检查套餐,或把 Agent 换到别的账号或服务商。","goalProcess.gate.reason.recoveryFailed": "自动恢复未能启动下一次尝试","goalProcess.gate.reason.runError": "任务运行出错({{code}})",+ "goalProcess.gate.reason.setupCli": "运行没能启动({{error}})。请在 Agent 所在的设备上安装对应 CLI,并确认它在 PATH 里。",+ "goalProcess.gate.reason.setupCredentials": "服务商拒绝了这次运行({{error}})。请在 Agent 设置里更新凭证、套餐或模型。",+ "goalProcess.gate.reason.setupDevice": "设备不可用({{error}})。请重新连接设备,或把 Agent 绑定到另一台在线设备。",+ "goalProcess.gate.reason.setupGateway": "设备网关没有配置({{error}})。请在服务端配置网关,或把 Agent 切到已连接的本地设备。",+ "goalProcess.gate.reason.setupWorkingDirectory": "工作目录 {{path}} 在 Agent 所在的设备上不存在。请在那台设备上创建它,或把 Agent 的工作目录改成一个存在的路径。",+ "goalProcess.gate.reason.transientRetriesSpent": "运行在 {{duration}} 内以同样的方式失败了 {{count}} 次({{error}})。请检查设备、网络和 Agent 网关。","goalProcess.gate.reason.verifyFailed": "任务 {{id}} 未通过验证","goalProcess.gate.reason.verifyInternalError": "验证未能运行(内部错误),这次交付没有被评估","goalProcess.gate.recommended": "推荐",+ "goalProcess.gate.title.agentQuestion": "回答主 Agent 的问题","goalProcess.gate.title.clarifyGoal": "开工前先确认目标",+ "goalProcess.gate.title.fixSetup": "修好运行环境后重试","goalProcess.gate.title.goalAcceptance": "决定目标验收的去向","goalProcess.gate.title.recoverTask": "决定失败任务的去向","goalProcess.graph.bridgeHops_one": "中间隔 {{count}} 步未显示",@@ -939,6 +973,16 @@"goalProcess.result.unfinished.unmetCriteria": "未达成的标准","goalProcess.resume": "继续","goalProcess.running.elapsed": "已运行 {{duration}}",+ "goalProcess.signOff.accept": "签收",+ "goalProcess.signOff.acceptEffect": "目标按已交付结束",+ "goalProcess.signOff.accepted": "已签收",+ "goalProcess.signOff.description": "目标验收已通过,你签收后目标正式结束。",+ "goalProcess.signOff.islandSubtitle": "已完成,等你签收",+ "goalProcess.signOff.notePlaceholder": "要改什么?Agent 会按这里的说明返工",+ "goalProcess.signOff.question": "这个目标的交付你认可吗?",+ "goalProcess.signOff.requestChanges": "提出修改",+ "goalProcess.signOff.requestChangesEffect": "退回给 Agent 重做,在补充说明里写要改什么",+ "goalProcess.signOff.sentBack": "已退回修改","goalProcess.stale.description": "已 {{duration}} 没有心跳。下一次推进会把这次尝试标为失联并重开一次,不计失败次数。","goalProcess.summary.done": "完成 · {{count}} 次尝试","goalProcess.summary.gateOpen": "等你决定",@@ -968,7 +1012,7 @@"goalTask.status.paused": "已暂停","goalTask.status.planning": "规划中","goalTask.status.repairing": "修复中",- "goalTask.status.review": "待验收",+ "goalTask.status.review": "等你决定","goalTask.status.running": "执行中","goalTask.status.verifying": "验证中","goalTask.status.waiting": "等待中",diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.jsonindex 13bd8049304..7eff31e65a6 100644--- a/locales/zh-CN/home.json+++ b/locales/zh-CN/home.json@@ -4,13 +4,19 @@"agentSelection.noSelected": "还未选择助理","agentSelection.search": "未找到匹配的助理","brief.action.acknowledge": "确认",+ "brief.action.answer": "去回答","brief.action.approve": "批准","brief.action.confirm": "已阅","brief.action.confirmDone": "确认完成",+ "brief.action.fail": "判定失败","brief.action.feedback": "反馈","brief.action.ignore": "忽略",+ "brief.action.openGoal": "查看目标",+ "brief.action.requestChanges": "提出修改",+ "brief.action.retire": "放弃任务","brief.action.retry": "重试","brief.action.review": "去验收",+ "brief.action.signOff": "签收","brief.action.upgrade": "升级方案","brief.actionFailed": "操作没有成功,请再试一次。","brief.addFeedback": "分享反馈",@@ -37,6 +43,11 @@"brief.editResult": "编辑","brief.expandAll": "展开全部","brief.feedbackSent": "反馈已提交",+ "brief.goal.clarify.title": "目标「{{goal}}」开始前有问题要问你",+ "brief.goal.decision.title": "目标「{{goal}}」需要你决定",+ "brief.goal.recommended": "推荐:{{option}}",+ "brief.goal.signOff.summary": "目标验收已通过。签收后目标正式结束;不满意可以提出修改,退回重做。",+ "brief.goal.signOff.title": "目标「{{goal}}」已完成,等你签收","brief.resolved": "已标记为已解决","brief.title": "简报","brief.viewAllTasks": "查看全部任务",@@ -111,7 +122,7 @@"homePromoBanner.label": "{{model}} 现已上线","inbox.author.scheduled": "定时触发","inbox.error.title": "运行失败",- "inbox.goals.review": "待验收",+ "inbox.goals.review": "等你决定","inbox.goals.running": "进行中","inbox.goals.showAll": "查看全部 {{count}} 个","inbox.goals.title": "目标",diff --git a/packages/const/src/goal.ts b/packages/const/src/goal.tsindex ec84e57edf2..b5d2e6195c0 100644--- a/packages/const/src/goal.ts+++ b/packages/const/src/goal.ts@@ -57,6 +57,29 @@ export const GOAL_ACCEPTANCE_TASK_TITLE = 'Complete full Goal acceptance';*/export const GOAL_CLARIFICATION_TITLE = 'Clarify the goal';+/**+ * Fixed title of the decision node the coordinator opens when a machine problem+ * needs a person: the setup is broken (a missing working directory, a CLI that is+ * not installed, an unregistered device) or the automatic retries for a usage+ * limit or a transport fault are spent. Nothing about the work is in question, so+ * clients tell it apart from a judgment gate by this title, the same way as the+ * clarification gate.+ */+export const GOAL_MACHINE_GATE_TITLE = 'Fix the setup, then retry';++/**+ * Fixed title of the decision node the main Agent opens when an ordinary+ * planning turn escalates a question with its own answers. Matched by clients+ * for localized copy, like the clarification title.+ */+export const GOAL_MANAGER_QUESTION_TITLE = 'Answer the main Agent';++/**+ * `briefs.trigger` of every brief a goal raises — its decision gates, its+ * sign-off and its progress reports. `metadata.goal` says which one it is.+ */+export const GOAL_BRIEF_TRIGGER = 'goal';+/** Option ids every clarification decision carries besides the planner's own choices. */export const GOAL_CLARIFICATION_OPTION = {/** Answer in the free-text note; the note is the answer. */@@ -88,6 +111,20 @@ export const ABANDONED_OPERATION_ERROR_PREFIX = 'Operation abandoned:';* run to the Task's attempt budget and retries it on its own offline schedule.*/export const DEVICE_OFFLINE_RUN_STATUS = 'device_offline';+/**+ * `task_topics.status` of a run that ended on a provider or CLI usage limit+ * ("You've hit your session limit · resets 4:30am"). The limit resets on its own+ * and nothing judged the work, so the run is not charged to the attempt budget;+ * the coordinator holds the Task until the reset and retries it.+ */+export const QUOTA_LIMITED_RUN_STATUS = 'quota_limited';+/**+ * `task_topics.status` of a run lost to a transport or runtime fault a retry+ * plausibly fixes (a timeout, an output the server discarded, a write that did+ * not persist). Not charged to the attempt budget; retried on a short bounded+ * schedule before a person is asked.+ */+export const TRANSIENT_FAILED_RUN_STATUS = 'transient_failed';/** The verifier ran and judged the delivery short of the criteria. */export const VERIFICATION_FAILED_ERROR = 'Delivery did not pass verification.';/** The verifier itself could not run, so the delivery was never evaluated. */diff --git a/packages/database/src/models/brief.ts b/packages/database/src/models/brief.tsindex 694937e1c31..4d09d835f57 100644--- a/packages/database/src/models/brief.ts+++ b/packages/database/src/models/brief.ts@@ -38,7 +38,7 @@ export class BriefModel {// share content rows), which would leak each member's briefs to everyone else// in the workspace. Brief ownership therefore always requires `user_id` to// match, in both personal and workspace mode.- private ownership = (): SQL =>+ ownership = (): SQL =>this.workspaceId? (and(eq(briefs.userId, this.userId), eq(briefs.workspaceId, this.workspaceId)) as SQL): (and(eq(briefs.userId, this.userId), isNull(briefs.workspaceId)) as SQL);diff --git a/packages/database/src/models/goal.ts b/packages/database/src/models/goal.tsindex 2c55f319afe..226ba40b0c4 100644--- a/packages/database/src/models/goal.ts+++ b/packages/database/src/models/goal.ts@@ -7,11 +7,12 @@ import type {GoalSupervisionState,GoalUnderstanding,} from '@lobechat/types';-import { and, desc, eq, inArray, notInArray, sql } from 'drizzle-orm';+import { and, desc, eq, inArray, isNull, ne, notInArray, or, sql } from 'drizzle-orm';+import { alias } from 'drizzle-orm/pg-core';import type { GoalItem, NewGoal } from '../schemas/goal';import { goals } from '../schemas/goal';-import { goalNodeDecisions, goalNodes } from '../schemas/goalGraph';+import { goalEdges, goalNodeDecisions, goalNodes } from '../schemas/goalGraph';import { tasks, taskTopics } from '../schemas/task';import { topics } from '../schemas/topic';import type { LobeChatDatabase } from '../type';@@ -359,6 +360,57 @@ export class GoalModel {// their order stable across reads so "question 1" stays question 1..orderBy(goalNodeDecisions.createdAt, goalNodeDecisions.id);+ /**+ * Every gate waiting on the person across their goals, except clarification+ * rounds (asked as one form through `listPendingClarifications`) — what the+ * approval island asks wherever the person is. Each row names the Task the+ * gate was opened for, so the question can say what it is about.+ */+ listPendingDecisions = async (): Promise<PendingGoalDecisionRow[]> => {+ const source = alias(goalNodes, 'gate_source');+ return this.db+ .select({+ agentId: goals.agentId,+ createdAt: goalNodeDecisions.createdAt,+ decisionId: goalNodeDecisions.id,+ description: goalNodes.description,+ goalId: goals.id,+ goalTitle: goals.title,+ nodeId: goalNodes.id,+ nodeTitle: goalNodes.title,+ options: goalNodeDecisions.options,+ question: goalNodeDecisions.question,+ recommendedOptionId: goalNodeDecisions.recommendedOptionId,+ sourceTaskId: source.taskId,+ sourceTitle: source.title,+ })+ .from(goalNodeDecisions)+ .innerJoin(goalNodes, eq(goalNodeDecisions.nodeId, goalNodes.id))+ .innerJoin(goals, eq(goalNodes.goalId, goals.id))+ .leftJoin(+ goalEdges,+ and(eq(goalEdges.targetNodeId, goalNodes.id), eq(goalEdges.kind, 'leads_to')),+ )+ .leftJoin(source, and(eq(source.id, goalEdges.sourceNodeId), eq(source.kind, 'task')))+ .where(+ and(+ this.ownership(),+ notInArray(goals.status, ['paused', 'achieved', 'failed', 'canceled']),+ eq(goalNodeDecisions.status, 'pending'),+ eq(goalNodeDecisions.authority, 'user'),+ // In a workspace every member can see the goal, but a gate is asked+ // of one person. Rows from before the requester was recorded fall+ // back to the goal's creator.+ or(+ eq(goalNodeDecisions.requestedUserId, this.userId),+ and(isNull(goalNodeDecisions.requestedUserId), eq(goals.userId, this.userId)),+ ),+ ne(goalNodes.title, GOAL_CLARIFICATION_TITLE),+ ),+ )+ .orderBy(goalNodeDecisions.createdAt, goalNodeDecisions.id);+ };+delete = async (id: string) => {return this.db.delete(goals).where(and(eq(goals.id, id), this.ownership()));};@@ -585,6 +637,24 @@ export interface GoalListItem {totalRunDuration: number;}+export interface PendingGoalDecisionRow {+ agentId: string | null;+ createdAt: Date;+ decisionId: string;+ /** What the gate stands on: the coordinator's reason, the main Agent's diagnosis. */+ description: string | null;+ goalId: string;+ goalTitle: string;+ nodeId: string;+ nodeTitle: string;+ options: GoalDecisionOption[] | null;+ question: string;+ recommendedOptionId: string | null;+ /** The Task the gate was opened for; null for a goal-level question. */+ sourceTaskId: string | null;+ sourceTitle: string | null;+}+export interface PendingGoalClarificationRow {agentId: string | null;decisionId: string;diff --git a/packages/database/src/models/goalGraph.ts b/packages/database/src/models/goalGraph.tsindex 84b39b33161..4f63c5bd2f8 100644--- a/packages/database/src/models/goalGraph.ts+++ b/packages/database/src/models/goalGraph.ts@@ -37,7 +37,7 @@ import {goalNodes,goalNodeWorkVersions,} from '../schemas/goalGraph';-import { tasks } from '../schemas/task';+import { briefs, tasks } from '../schemas/task';import { works, workVersions } from '../schemas/work';import type { LobeChatDatabase, Transaction } from '../type';import { notTrashed } from '../utils/softDelete';@@ -77,6 +77,27 @@ interface CreateDecisionInput {}/** Persistence boundary for an owned Goal Graph and its append-only audit trail. */+/**+ * A goal gate is asked in two places — the goal itself and the brief that+ * carries it to the inbox. Whichever answers, the other must stop asking, so+ * every write that settles a decision settles its brief in the same transaction.+ */+const settleDecisionBriefs = async (+ tx: Transaction,+ decisionId: string,+ action: string,+ comment?: string,+) =>+ tx+ .update(briefs)+ .set({ resolvedAction: action, resolvedAt: new Date(), resolvedComment: comment ?? null })+ .where(+ and(+ isNull(briefs.resolvedAt),+ sql`${briefs.metadata} -> 'goal' ->> 'decisionId' = ${decisionId}`,+ ),+ );+export class GoalGraphModel {/*** `actor` is who the audit trail records for the transitions made through this@@ -825,6 +846,7 @@ export class GoalGraphModel {eventType: 'resolved',reason: resolution,});+ await settleDecisionBriefs(tx, decision.id, optionId, resolution);return decision;});@@ -868,6 +890,7 @@ export class GoalGraphModel {eventType: 'retired',reason,});+ await settleDecisionBriefs(tx, decision.id, 'canceled', reason);return decision;});}diff --git a/packages/database/src/models/taskTopic.ts b/packages/database/src/models/taskTopic.tsindex c7e7f0af686..21d8e823c79 100644--- a/packages/database/src/models/taskTopic.ts+++ b/packages/database/src/models/taskTopic.ts@@ -1,4 +1,8 @@-import { DEVICE_OFFLINE_RUN_STATUS } from '@lobechat/const/goal';+import {+ DEVICE_OFFLINE_RUN_STATUS,+ QUOTA_LIMITED_RUN_STATUS,+ TRANSIENT_FAILED_RUN_STATUS,+} from '@lobechat/const/goal';import type { BriefDecision, TaskTopicHandoff } from '@lobechat/types';import { and, count, desc, eq, gte, inArray, sql } from 'drizzle-orm';@@ -13,7 +17,9 @@ export const TERMINAL_TOPIC_STATUSES = new Set(['completed',DEVICE_OFFLINE_RUN_STATUS,'failed',+ QUOTA_LIMITED_RUN_STATUS,'timeout',+ TRANSIENT_FAILED_RUN_STATUS,]);export class TaskTopicModel {diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex c6e4c1ec567..bb2754464cb 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -2002,7 +2002,7 @@ export default {'Each round is one full agent run; its output, time and cost all hang off this goal.','goalEmpty.step2.title': 'The agent runs a round on its own','goalEmpty.step3.desc':- 'Every check is judged one by one. All passed means achieved; anything needing your call stops at pending acceptance.',+ 'Every check is judged one by one. All passed means achieved; anything needing your call stops and asks you.','goalEmpty.step3.title': 'Acceptance runs every round','goalEmpty.title': 'Chase goals without limits','goalList.acceptanceProgress': '{{passed}}/{{total}} passed',@@ -2022,7 +2022,7 @@ export default {'goalList.status.error': 'Needs attention','goalList.status.paused': 'Paused','goalList.status.planning': 'Planning',- 'goalList.status.review': 'Pending acceptance',+ 'goalList.status.review': 'Needs your decision','goalList.status.running': 'Pursuing','goalList.status.verifying': 'Verifying','goalList.status.waiting': 'Waiting',@@ -2036,7 +2036,7 @@ export default {'goalTask.status.paused': 'Paused','goalTask.status.planning': 'Planning','goalTask.status.repairing': 'Repairing',- 'goalTask.status.review': 'Pending acceptance',+ 'goalTask.status.review': 'Needs your decision','goalTask.status.running': 'Executing','goalTask.status.verifying': 'Verifying','goalTask.status.waiting': 'Waiting',@@ -2204,6 +2204,7 @@ export default {'goalProcess.gate.decisionPointLabel': 'What needs your decision','goalProcess.gate.title.recoverTask': 'Decide what happens to the failed task','goalProcess.gate.title.goalAcceptance': 'Decide the goal acceptance outcome',+ 'goalProcess.gate.title.fixSetup': 'Fix the setup, then retry','goalProcess.clarify.title': 'Clarify the goal before work starts','goalProcess.clarify.description':'Answer these once and the agent plans with them. Skip to let it proceed on its own assumptions.',@@ -2219,14 +2220,74 @@ export default {'goalProcess.gate.reason.attemptBudgetExhausted': 'The attempt budget for this work is used up','goalProcess.gate.reason.costBudgetExhausted': 'The goal cost budget is used up','goalProcess.gate.reason.recoveryFailed': 'Automatic recovery could not start the next attempt',+ 'goalProcess.gate.reason.deviceStayedOffline':+ 'The device this task runs on stayed offline through every automatic retry',+ 'goalProcess.gate.reason.setupWorkingDirectory':+ 'The working directory {{path}} does not exist on the device the agent runs on. Create it there, or point the agent at a directory that exists.',+ 'goalProcess.gate.reason.setupCli':+ 'The run could not start ({{error}}). Install the CLI on the device the agent runs on and make sure it is on PATH.',+ 'goalProcess.gate.reason.setupCredentials':+ 'The provider refused the run ({{error}}). Update the credentials, plan or model in the agent settings.',+ 'goalProcess.gate.reason.setupDevice':+ 'The device is unavailable ({{error}}). Reconnect it, or bind the agent to another online device.',+ 'goalProcess.gate.reason.setupGateway':+ 'The device gateway is not set up ({{error}}). Configure it on the server, or switch the agent to a connected local device.',+ 'goalProcess.gate.reason.quotaFarReset':+ 'The usage limit ({{error}}) does not reset until {{at}}, more than a day away. Switch the agent to another account or provider, or retry after the reset.',+ 'goalProcess.gate.reason.quotaRetriesSpent':+ 'Still over the usage limit ({{error}}) after {{count}} automatic retries over {{duration}}. Check the plan, or switch the agent to another account or provider.',+ 'goalProcess.gate.reason.transientRetriesSpent':+ 'The run failed the same way {{count}} times over {{duration}} ({{error}}). Check the device, its network and the agent gateway.','goalProcess.gate.reason.runError': 'The run stopped with an error ({{code}})','goalProcess.gate.recommended': 'recommended','goalProcess.gate.noteLabel': 'Extra guidance','goalProcess.gate.notePlaceholder': 'Optional — goes into the next attempt instructions','goalProcess.gate.option.retry': 'Retry work',+ 'goalProcess.gate.option.fixedRetry': 'I fixed it — retry','goalProcess.gate.option.retire': 'Retire work','goalProcess.gate.option.fail': 'Fail goal','goalProcess.gate.option.assume': 'Go with the assumption',+ 'goalProcess.decision.effect.fixedRetry': 'Run the task again once the setup is fixed.',+ 'goalProcess.decision.asks.judgment': 'needs your review on a stuck task',+ 'goalProcess.decision.asks.goalAcceptance': 'needs your review on the goal acceptance',+ 'goalProcess.decision.asks.agentQuestion': 'needs your review',+ 'goalProcess.decision.asks.machine': 'needs you to sort it out',+ 'goalProcess.decision.system': 'Run environment',+ 'goalProcess.decision.summary.judgment':+ 'It used up its automatic retries without passing acceptance. Decide whether it gets another attempt or is dropped.',+ 'goalProcess.decision.summary.machine':+ 'It could not run because of the run environment, not the work itself. Fix the environment, then retry.',+ 'goalProcess.decision.summary.goalAcceptance':+ 'The goal-level acceptance did not pass. Decide whether to run it again, abandon it, or record the goal as failed.',+ 'goalProcess.decision.summary.agentQuestion':+ 'While working on the goal, the main Agent hit a call only you can make. It lays out the options and its recommendation below.',+ 'goalProcess.decision.summary.thisTask': 'this task',+ 'goalProcess.decision.context.task': 'Task',+ 'goalProcess.decision.context.decision': 'Your call',+ 'goalProcess.decision.submit': 'Decide',+ 'goalProcess.decision.viewRun': 'Open task',+ 'goalProcess.decision.attempts_one': '{{count}} attempt',+ 'goalProcess.decision.attempts_other': '{{count}} attempts',+ 'goalProcess.decision.effect.retry':+ 'Send the task back for another attempt. Your note is written into its instructions.',+ 'goalProcess.decision.effect.retire': 'Drop this task. The goal moves on without it.',+ 'goalProcess.decision.effect.fail': 'End the goal and record it as failed.',+ 'goalProcess.decision.effect.retryAcceptance': 'Run the goal-level acceptance again.',+ 'goalProcess.decision.effect.abandonAcceptance':+ 'Stop acceptance and end the goal without a verdict.',+ 'goalProcess.signOff.islandSubtitle': 'is done and waiting for your sign-off',+ 'goalProcess.signOff.question': 'Do you accept what this goal delivered?',+ 'goalProcess.signOff.description': 'Goal-level acceptance passed. Your sign-off closes the goal.',+ 'goalProcess.signOff.accept': 'Sign off',+ 'goalProcess.signOff.acceptEffect': 'Close the goal as delivered.',+ 'goalProcess.signOff.requestChanges': 'Request changes',+ 'goalProcess.signOff.requestChangesEffect':+ 'Send it back to the Agent. Say what to change in the notes.',+ 'goalProcess.signOff.notePlaceholder':+ 'What should change? The Agent reworks the delivery with this.',+ 'goalProcess.signOff.accepted': 'Signed off',+ 'goalProcess.signOff.sentBack': 'Sent back for changes',+ 'goalProcess.gate.title.agentQuestion': "Answer the main Agent's question",'goalProcess.attempts.title': 'Previous attempts','goalProcess.attempts.nth': 'Attempt {{index}}','goalProcess.attempts.passed': 'Passed',@@ -2511,13 +2572,13 @@ export default {'goalPage.filteredEmptyTitle': 'No goals in this view','goalPage.filter.achieved': 'Completed','goalPage.filter.all': 'All',- 'goalPage.filter.review': 'Needs review',+ 'goalPage.filter.review': 'Needs you','goalPage.filter.running': 'In progress','goalPage.loadingProgress': 'Loading acceptance progress…','goalPage.listTitle': 'Goal list','goalPage.loadMore': 'Load more',- 'goalPage.metrics.delivered': 'Delivered',- 'goalPage.metrics.pursuing': 'Open',+ 'goalPage.metrics.delivered': 'Needs you',+ 'goalPage.metrics.pursuing': 'Others','goalPage.metrics.total': 'Total goals','goalPage.title': 'Overview','goalPage.view.card': 'Cards',diff --git a/packages/locales/src/default/home.ts b/packages/locales/src/default/home.tsindex 53df5c97e90..65bfd919f45 100644--- a/packages/locales/src/default/home.ts+++ b/packages/locales/src/default/home.ts@@ -13,6 +13,18 @@ export default {'brief.action.review': 'Go to acceptance','brief.action.retry': 'Retry','brief.action.upgrade': 'Upgrade plan',+ 'brief.action.retire': 'Retire task',+ 'brief.action.fail': 'Fail goal',+ 'brief.action.signOff': 'Sign off',+ 'brief.action.requestChanges': 'Request changes',+ 'brief.action.openGoal': 'Open goal',+ 'brief.action.answer': 'Answer',+ 'brief.goal.decision.title': 'Goal "{{goal}}" needs your decision',+ 'brief.goal.clarify.title': 'Goal "{{goal}}" has questions before it starts',+ 'brief.goal.signOff.title': 'Goal "{{goal}}" is done. Sign it off',+ 'brief.goal.signOff.summary':+ 'Goal-level acceptance passed. Sign it off to close the goal, or request changes to send it back.',+ 'brief.goal.recommended': 'Recommended: {{option}}','brief.actionFailed': "That didn't go through. Please try again.",'brief.agentSignal.selfReview.applied.heading': 'Updated','brief.agentSignal.selfReview.applied.summary': '{{count}} dream update was applied.',@@ -115,7 +127,7 @@ export default {'Task mode does not support attachments or selected context yet. Remove them or switch to Agent mode; your draft has been kept.','inbox.author.scheduled': 'Scheduled','inbox.error.title': 'Run failed',- 'inbox.goals.review': 'Pending acceptance',+ 'inbox.goals.review': 'Needs your decision','inbox.goals.running': 'In progress','inbox.goals.showAll': 'Show all {{count}}','inbox.goals.title': 'Goals',diff --git a/packages/prompts/src/chains/goalManager.test.ts b/packages/prompts/src/chains/goalManager.test.tsindex 0244e52840c..ad70cddf016 100644--- a/packages/prompts/src/chains/goalManager.test.ts+++ b/packages/prompts/src/chains/goalManager.test.ts@@ -28,7 +28,7 @@ describe('buildGoalManagerPrompt', () => {'keeps supervision language tied to the goal rather than the English control prompt: %s',(requirement) => {const prompt = buildGoalManagerPrompt({ ...base, requirement });- expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v7');+ expect(GOAL_MANAGER_PROMPT_VERSION).toBe('v8');expect(cdataOf(prompt, 'requirement')).toBe(requirement);expect(prompt).toContain('Use the language of the Goal requirement');expect(prompt).toContain(@@ -59,6 +59,20 @@ describe('buildGoalManagerPrompt', () => {expect(prompt).toContain('escalate with the specific question');});+ /**+ * Regression: escalations only carried a reason, so the owner's gate offered+ * retry / retire while the real decision (waive a criterion, restore a PR)+ * sat in the text with no way to answer it.+ */+ it('asks escalations to carry the decision with concrete answers', () => {+ const prompt = buildGoalManagerPrompt({+ ...base,+ problem: 'Goal-level acceptance did not pass',+ });+ expect(prompt).toContain('"ask":{"question"');+ expect(prompt).toContain('every option needs an effect');+ });+/*** Regression: without dependsOn every planned task hung directly off the* problem node, so a four-round Goal rendered as one flat row.@@ -106,7 +120,7 @@ describe('buildGoalManagerPrompt', () => {});expect(prompt.split('\n')[0]).toBe(- '<goalTurn goal="goal_1" maxTurns="12" trigger="settled" turn="3" version="v7">',+ '<goalTurn goal="goal_1" maxTurns="12" trigger="settled" turn="3" version="v8">',);expect(prompt.endsWith('</goalTurn>')).toBe(true);// CommonMark ends an HTML block at a blank line; the client needs one block.diff --git a/packages/prompts/src/chains/goalManager.ts b/packages/prompts/src/chains/goalManager.tsindex 257d0088b60..c6a41b20827 100644--- a/packages/prompts/src/chains/goalManager.ts+++ b/packages/prompts/src/chains/goalManager.ts@@ -10,8 +10,10 @@ import { GOAL_TURN_TAG } from '@lobechat/const';* turn ended, and only the review feedback new since then, with the repeating* contract in `<instruction>` — so the client renders it as a card instead of a* wall of identical text every turn.+ * v8 lets an escalation carry an `ask` — the owner's question with concrete+ * answers (and, on a takeover, what each answer does to the blocked Task).*/-export const GOAL_MANAGER_PROMPT_VERSION = 'v7';+export const GOAL_MANAGER_PROMPT_VERSION = 'v8';export interface GoalManagerFeedbackNote {/** `user`, or `agent <id>` for an agent-written comment. */@@ -162,7 +164,8 @@ const contract = (input: GoalManagerPromptInput) =>'{"action":"wait","reason":"why evidence must arrive later","until":"future UTC ISO instant","event":{"type":"external.result","key":"correlated job ID"}}','{"action":"verify","reason":"why the existing evidence warrants independent Goal verification"}','{"action":"retry","taskId":"failed Task ID","failedOperationId":"latest confirmed failure ID","reason":"diagnosis and checkpoint-aware recovery instruction"}',- '{"action":"escalate","reason":"concrete blocker requiring human input"}',+ '{"action":"escalate","reason":"what you found and why only the owner can unblock it","ask":{"question":"the one decision the owner has to make, in the Goal language","options":[{"id":"waive","label":"short answer","description":"what happens if they choose it","effect":"retry"},{"id":"keep","label":"short answer","description":"what happens if they choose it","effect":"retire"}],"recommendedOptionId":"waive"}}',+ 'When you escalate, ask the actual decision with 2-4 concrete answers in "ask" instead of burying it in reason: the owner sees the question with your answers as buttons, your reason as the evidence, and your recommendation marked. When you are taking over a blocked Task, every option needs an effect: "retry" sends the Task back with the chosen answer as guidance, "retire" drops it. On an ordinary planning turn options need no effect; the owner\'s answer appears as a resolved decision in lh goal show on your next turn, and you plan from it. Name each option id after the answer itself (e.g. "waive"); retry, retire, fail, assume and answer are reserved for the coordinator and will be refused.',].join('\n');export const buildGoalManagerPrompt = (input: GoalManagerPromptInput) => {diff --git a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsxindex 68563024f74..570882c9e0e 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx+++ b/packages/shared-tool-ui/src/AskUserQuestion/AskUserQuestionView.tsx@@ -260,7 +260,7 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {event.preventDefault();handleSubmit();} else if (event.key === 'Escape') {- if (submitting) return;+ if (submitting || !labels.skip) return;event.preventDefault();handleSkip();}@@ -299,10 +299,14 @@ export const AskUserQuestionView = memo<AskUserQuestionViewProps>((props) => {</Text>)}<Flexbox horizontal gap={8}>- <Button disabled={submitting} icon={<Icon icon={X} />} onClick={handleSkip}>- {labels.skip}- <Hotkey compact keys={KeyMapEnum.Esc} variant="borderless" />- </Button>+ {/* A host whose question has no "not now" answer (a decision gate)+ passes no skip label, and the form offers no way around it. */}+ {labels.skip && (+ <Button disabled={submitting} icon={<Icon icon={X} />} onClick={handleSkip}>+ {labels.skip}+ <Hotkey compact keys={KeyMapEnum.Esc} variant="borderless" />+ </Button>+ )}<Buttondisabled={isSubmitDisabled}icon={<Icon icon={Send} />}diff --git a/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsxindex 4a1ab3fc931..e3fb99f05f4 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx+++ b/packages/shared-tool-ui/src/AskUserQuestion/QuestionPanel.tsx@@ -15,8 +15,10 @@ const styles = createStaticStyles(({ css, cssVar }) => ({customRow: css`margin-block-start: 2px;- /* Align the chip under the option number chips (OptionCard padding-inline). */- padding-inline: 12px;+ /* Align the chip under the option number chips (OptionCard padding-inline);+ the input itself runs to the option cards' right edge, flush with the+ submit button below. */+ padding-inline-start: 12px;`,// Mirrors OptionCard's `optionIndex` chip so the free-text row's number reads// identically to the numbered options above it.diff --git a/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts b/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.tsindex 7b06e31ed2a..ff519734756 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/normalize.test.ts@@ -156,4 +156,21 @@ describe('normalizeAskUserQuestions', () => {}),).toEqual([{ description: 'Decides the tone', header: 'Q1', options: [], question: 'Who?' }]);});++ it('keeps an explicit recommended flag from a host-built option', () => {+ const [question] = normalizeAskUserQuestions({+ questions: [+ {+ header: '',+ options: [+ { id: 'retry', label: 'Retry', recommended: true },+ { id: 'retire', label: 'Retire' },+ ],+ question: 'What next?',+ },+ ],+ });+ expect(question.options[0]).toMatchObject({ id: 'retry', label: 'Retry', recommended: true });+ expect(question.options[1].recommended).toBeUndefined();+ });});diff --git a/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts b/packages/shared-tool-ui/src/AskUserQuestion/normalize.tsindex 564aba360ae..89247bdcd3b 100644--- a/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts+++ b/packages/shared-tool-ui/src/AskUserQuestion/normalize.ts@@ -37,8 +37,11 @@ const normalizeOption = (value: unknown): AskUserQuestionOption | undefined => {const strippedLabel = stripRecommendedSuffix(rawLabel);// Only treat the suffix as a marker when something remains — a label that IS// "(Recommended)" stays verbatim rather than collapsing to an empty option.- const recommended = strippedLabel.length > 0 && strippedLabel !== rawLabel;- const label = recommended ? strippedLabel : rawLabel;+ const suffixed = strippedLabel.length > 0 && strippedLabel !== rawLabel;+ const label = suffixed ? strippedLabel : rawLabel;+ // Hosts that ask their own questions (a goal gate) know their pick and say+ // so directly; only tool calls need the label convention.+ const recommended = suffixed || option?.recommended === true;const description = pickString(option?.description);const id = pickString(option?.id);diff --git a/packages/types/src/brief/index.ts b/packages/types/src/brief/index.tsindex 3c0644c0f1d..40c4261f8eb 100644--- a/packages/types/src/brief/index.ts+++ b/packages/types/src/brief/index.ts@@ -65,12 +65,30 @@ export interface BriefAgentSignalMetadata {nightlySelfReview?: unknown;}+/**+ * Goal-owned Brief metadata: what a goal brief stands for, so answering it from+ * the inbox acts on the goal and the goal settles it when answered elsewhere.+ */+export interface BriefGoalMetadata {+ /** Present on a decision brief — the gate it mirrors. */+ decisionId?: string;+ goalId: string;+ goalTitle: string;+ /** What the brief is for. */+ kind: 'decision' | 'signOff';+ /** The action the goal advises — set apart among the brief's buttons. */+ recommendedAction?: string;+ /** Present on a sign-off brief — the Goal-level acceptance to sign. */+ signOffAcceptanceId?: string;+}+/** Freeform Brief metadata namespaced by feature owner. */export interface BriefMetadata {/** Other feature namespaces remain possible without schema churn. */[key: string]: unknown;/** Agent Signal extension metadata. */agentSignal?: BriefAgentSignalMetadata;+ goal?: BriefGoalMetadata;/*** `llm_generation_tracing` row id of the generation that produced this brief's* title/summary. Set for LLM-synthesized briefs so the user's resolve actiondiff --git a/packages/types/src/goal.ts b/packages/types/src/goal.tsindex 140186db95a..808fbee0985 100644--- a/packages/types/src/goal.ts+++ b/packages/types/src/goal.ts@@ -247,6 +247,13 @@ export interface GoalManagerWait {};}+/** A question the main Agent escalates to the owner, with the answers it proposes. */+export interface GoalManagerAsk {+ options: GoalDecisionOption[];+ question: string;+ recommendedOptionId?: string;+}+/** Server-owned dispatch receipt, retained across backend restarts. */export interface GoalManagerState {/**@@ -321,6 +328,12 @@ export interface GoalManagerState {startedAt: string;submitted?: {action: 'tasks' | 'verify' | 'retry' | 'escalate' | 'wait';+ /**+ * The question an `escalate` puts to the owner, with the answers it offers.+ * Without it the gate could only ask "retry or retire?" while the real+ * question sat unanswerable in the reason text.+ */+ ask?: GoalManagerAsk;reason: string;taskId?: string;};@@ -476,8 +489,18 @@ export type GoalDecisionAuthority = 'agent' | 'user' | 'project_role';export type GoalDecisionStatus = 'pending' | 'resolved' | 'canceled';+/**+ * What answering with an option does to the Task the gate was opened for.+ * Coordinator options carry it implicitly through their fixed ids+ * (`retry` / `retire` / `fail`); options the main Agent writes for its own+ * question name it, so its wording never has to match a reserved id.+ */+export type GoalDecisionOptionEffect = 'retry' | 'retire';+export interface GoalDecisionOption {+ /** The consequence of choosing this option, in the words the person reads. */description?: string;+ effect?: GoalDecisionOptionEffect;id: string;label: string;}diff --git a/packages/utils/src/goalCopy.test.ts b/packages/utils/src/goalCopy.test.tsnew file mode 100644index 00000000000..4ef531d15a0--- /dev/null+++ b/packages/utils/src/goalCopy.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest';++import { coordinatorGateReason, coordinatorReasonCopy } from './goalCopy';++/**+ * The machine gate's question is English data written on the server; without a+ * template it reached a Chinese reader verbatim on the goal page, the island+ * and the inbox brief.+ */+describe('machine gate reasons', () => {+ const reasonOf = (question: string) => coordinatorReasonCopy(coordinatorGateReason(question));++ it('names the missing working directory', () => {+ expect(+ reasonOf(+ 'Setup problem: Working directory does not exist: /Users/user/lobehub. Create /Users/user/lobehub on the device the agent runs on, or point the agent at a working directory that exists there. Fix it, then retry or retire this task node?',+ ),+ ).toEqual({+ key: 'goalProcess.gate.reason.setupWorkingDirectory',+ params: { path: '/Users/user/lobehub' },+ });+ });++ it('carries every figure of a spent retry schedule', () => {+ expect(+ reasonOf(+ "Usage limit: You've hit your session limit. Retried 6 time(s) over 26h and the limit still applies. Check the plan or switch the agent to another account or provider. Fix it, then retry or retire this task node?",+ ),+ ).toEqual({+ key: 'goalProcess.gate.reason.quotaRetriesSpent',+ params: { count: '6', duration: '26h', error: "You've hit your session limit" },+ });+ });++ it('still reads the single-parameter templates', () => {+ expect(reasonOf('Task T-3 did not pass verification. Retry or retire this task node?')).toEqual(+ { key: 'goalProcess.gate.reason.verifyFailed', params: { id: 'T-3' } },+ );+ });+});diff --git a/packages/utils/src/goalCopy.ts b/packages/utils/src/goalCopy.tsnew file mode 100644index 00000000000..b62ceaeebd5--- /dev/null+++ b/packages/utils/src/goalCopy.ts@@ -0,0 +1,136 @@+/**+ * The goal coordinator authors its gate/attempt strings in English on the+ * server (`GoalService.openFailureDecision` and the verify settle reasons).+ * The reason templates are a stable, finite vocabulary, so every surface that+ * shows them — the goal page, the approval island and the inbox brief the+ * server writes — recognizes them and swaps in the reader's language through+ * the `chat` namespace; anything not recognized renders verbatim.+ */++export interface LocalizedCopyRef {+ key: string;+ params?: Record<string, string>;+}++/** Strip the coordinator question template down to its dynamic reason half. */+const QUESTION_TAILS = [+ /\.?\s*Retry or retire this task node\?$/,+ /\.?\s*Fix it, then retry or retire this task node\?$/,+ /\.?\s*Retry Goal acceptance or fail this Goal\?$/,+ /\.?\s*Retry Goal acceptance, abandon it, or fail this Goal\?$/,+];++export const coordinatorGateReason = (question?: string | null): string | undefined => {+ if (!question) return undefined;+ for (const tail of QUESTION_TAILS) {+ if (tail.test(question)) {+ const reason = question.replace(tail, '').trim();+ return reason || undefined;+ }+ }+ return question;+};++/** Known coordinator reason templates → chat-ns locale refs. */+const REASON_PATTERNS: Array<{+ key: string;+ param?: string;+ /** Names for several capture groups, in order; `param` names just the first. */+ params?: string[];+ pattern: RegExp;+}> = [+ // Machine gates (see `machineRecovery.ts`): what broke, then what to change.+ {+ key: 'goalProcess.gate.reason.setupWorkingDirectory',+ params: ['path'],+ pattern: /^Setup problem: Working directory does not exist: (.+?)\. Create \1 on the device/,+ },+ {+ key: 'goalProcess.gate.reason.setupCli',+ params: ['error'],+ pattern: /^Setup problem: (.+?)\. Install the CLI on the device/,+ },+ {+ key: 'goalProcess.gate.reason.setupCredentials',+ params: ['error'],+ pattern: /^Setup problem: (.+?)\. Update the provider credentials/,+ },+ {+ key: 'goalProcess.gate.reason.setupDevice',+ params: ['error'],+ pattern: /^Setup problem: (.+?)\. Reconnect the device/,+ },+ {+ key: 'goalProcess.gate.reason.setupGateway',+ params: ['error'],+ pattern: /^Setup problem: (.+?)\. Configure the device gateway/,+ },+ {+ key: 'goalProcess.gate.reason.quotaFarReset',+ params: ['error', 'at'],+ pattern: /^Usage limit: (.+?)\. It does not reset until (\S+), more than a day away/,+ },+ {+ key: 'goalProcess.gate.reason.quotaRetriesSpent',+ params: ['error', 'count', 'duration'],+ pattern: /^Usage limit: (.+?)\. Retried (\d+) time\(s\) over (.+?) and the limit still applies/,+ },+ {+ key: 'goalProcess.gate.reason.transientRetriesSpent',+ params: ['error', 'count', 'duration'],+ pattern: /^Run failed: (.+?)\. Retried (\d+) time\(s\) over (.+?) and it failed the same way/,+ },+ {+ key: 'goalProcess.gate.reason.verifyInternalError',+ pattern: /^Verification could not run \(internal error\); the delivery was not evaluated\.?$/,+ },+ {+ key: 'goalProcess.gate.reason.verifyFailed',+ param: 'id',+ pattern: /^Task (\S+) did not pass verification$/,+ },+ {+ key: 'goalProcess.gate.reason.goalAcceptanceFailed',+ pattern: /^Goal-level acceptance did not pass$/,+ },+ {+ key: 'goalProcess.gate.reason.attemptBudgetExhausted',+ pattern: /^Task attempt budget was exhausted( after an operation was abandoned)?$/,+ },+ {+ key: 'goalProcess.gate.reason.costBudgetExhausted',+ pattern: /^Goal cost budget was exhausted( after an operation was abandoned)?$/,+ },+ {+ key: 'goalProcess.gate.reason.deviceStayedOffline',+ pattern: /^Task device stayed offline$/,+ },+ {+ key: 'goalProcess.gate.reason.recoveryFailed',+ pattern:+ /^Automatic recovery could not (start the next attempt|restart an abandoned operation)$/,+ },+ {+ // A run that failed outright leaves its runtime error type as the reason+ // (e.g. `InvalidProviderAPIKey`). The code stays visible for support; the+ // sentence around it is the user's language.+ key: 'goalProcess.gate.reason.runError',+ param: 'code',+ pattern: /^([A-Z][a-z0-9]+[A-Z][A-Za-z0-9]*)$/,+ },+];++export const coordinatorReasonCopy = (reason?: string | null): LocalizedCopyRef | undefined => {+ if (!reason) return undefined;+ const trimmed = reason.trim();+ for (const { key, param, params, pattern } of REASON_PATTERNS) {+ const match = pattern.exec(trimmed);+ if (!match) continue;+ const names = params ?? (param ? [param] : []);+ const values = Object.fromEntries(+ names.flatMap((name, index) => (match[index + 1] ? [[name, match[index + 1]]] : [])),+ );+ return { key, ...(names.length > 0 ? { params: values } : {}) };+ }+ return undefined;+};diff --git a/src/features/AgentGoals/GoalDecision/index.tsx b/src/features/AgentGoals/GoalDecision/index.tsxnew file mode 100644index 00000000000..4e0efec594f--- /dev/null+++ b/src/features/AgentGoals/GoalDecision/index.tsx@@ -0,0 +1,356 @@+'use client';++import type { GoalDecisionOption } from '@lobechat/types';+import { Center, Flexbox, Icon } from '@lobehub/ui';+import { Avatar, Text } from '@lobehub/ui/base-ui';+import { createStaticStyles, cssVar } from 'antd-style';+import { MonitorCog } from 'lucide-react';+import { type ReactNode, useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useAgentDisplayMeta } from '@/features/AgentTasks/shared/useAgentDisplayMeta';+import ClarificationQuestions, {+ type ClarificationAnswer,+} from '@/features/ClarificationQuestions';++import {+ coordinatorGateReason,+ coordinatorReasonCopy,+ gateOptionLabelKey,+} from '../ProcessControl/coordinatorCopy';+import {+ type GoalGateCategory,+ type GoalGateDecision,+ toGateAnswer,+ toGateQuestion,+} from './mapping';++export { type GoalGateCategory, goalGateCategory, type GoalGateDecision } from './mapping';++type GateCategory = Exclude<GoalGateCategory, 'clarify'>;++interface GoalDecisionAskerProps {+ /** The agent the goal answers to — the one asking, unless the system is. */+ agentId?: string | null;+ category: GateCategory;+ /** Trailing context on the asker line, e.g. which goal (the island). */+ extra?: ReactNode;+ size?: number;+ /** Overrides what the asker wants, for a host asking something other than a gate. */+ subtitle?: string;+}++/**+ * Who is asking. A gate is the goal's agent turning to its owner, so it leads+ * with that agent the way an AskUserQuestion card leads with the agent that+ * called it; a machine gate has no one behind it but the system, and says so+ * with its own mark instead of borrowing the agent's face.+ */+export const GoalDecisionAsker = ({+ agentId,+ category,+ extra,+ size = 28,+ subtitle,+}: GoalDecisionAskerProps) => {+ const { t } = useTranslation('chat');+ const meta = useAgentDisplayMeta(agentId);+ const machine = category === 'machine';++ return (+ <Flexbox horizontal align={'center'} gap={10} style={{ minWidth: 0 }}>+ {machine ? (+ // The run environment's glyph on a light approval-blue tile, in the+ // avatar's place: the system asks, not an agent.+ <Center+ flex={'none'}+ style={{+ background: cssVar.colorInfoBg,+ borderRadius: cssVar.borderRadius,+ color: cssVar.colorInfo,+ height: size,+ width: size,+ }}+ >+ <Icon icon={MonitorCog} size={size * 0.58} />+ </Center>+ ) : (+ <Avatar+ avatar={meta?.avatar}+ background={meta?.backgroundColor}+ shape={'circle'}+ size={size}+ style={{ flex: 'none' }}+ title={meta?.title}+ />+ )}+ <Flexbox horizontal align={'baseline'} gap={10} style={{ minWidth: 0 }}>+ {/* The asker's name, then what it wants, in the same voice: one line,+ set apart by space rather than by a dimmer grey. */}+ <Text ellipsis style={{ flex: 'none', maxWidth: 240 }} weight={500}>+ {machine ? t('goalProcess.decision.system') : meta?.title}+ </Text>+ <Text ellipsis>{subtitle ?? t(`goalProcess.decision.asks.${category}` as const)}</Text>+ {extra}+ </Flexbox>+ </Flexbox>+ );+};++/** The coordinator's own answers, in the reader's words, and what each one does. */+export const useGateOptionCopy = () => {+ const { t } = useTranslation('chat');+ return useMemo(+ () => ({+ describe: (option: GoalDecisionOption, category: GoalGateCategory) => {+ const terminalAcceptance = category === 'goalAcceptance';+ switch (option.id) {+ case 'retry': {+ if (category === 'machine') return t('goalProcess.decision.effect.fixedRetry');+ return terminalAcceptance+ ? t('goalProcess.decision.effect.retryAcceptance')+ : t('goalProcess.decision.effect.retry');+ }+ case 'retire': {+ return terminalAcceptance+ ? t('goalProcess.decision.effect.abandonAcceptance')+ : t('goalProcess.decision.effect.retire');+ }+ case 'fail': {+ return t('goalProcess.decision.effect.fail');+ }+ default: {+ return undefined;+ }+ }+ },+ label: (option: GoalDecisionOption, category: GoalGateCategory) => {+ const key = gateOptionLabelKey(option, category === 'machine' ? 'fixSetup' : undefined);+ return key ? t(key as any) : option.label;+ },+ }),+ [t],+ );+};++const contextStyles = createStaticStyles(({ css, cssVar }) => ({+ block: css`+ display: grid;+ grid-template-columns: max-content 1fr;+ gap: 8px 16px;++ padding-block: 12px;+ padding-inline: 14px;+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorFillQuaternary};+ `,+ description: css`+ overflow: hidden;+ display: -webkit-box;+ -webkit-box-orient: vertical;+ -webkit-line-clamp: 2;++ margin-block-start: 2px;++ font-size: 12px;+ color: ${cssVar.colorTextSecondary};+ `,+ label: css`+ font-size: 13px;+ line-height: 22px;+ color: ${cssVar.colorTextSecondary};+ `,+ title: css`+ cursor: pointer;+ font-weight: 500;++ &:hover {+ color: ${cssVar.colorPrimary};+ }+ `,+}));++/**+ * What the owner needs before reading the question: the Task that stopped —+ * its name and what it was asked to do — and, in one line, what they are+ * being asked to decide.+ */+const GateContext = ({+ summary,+ task,+}: {+ summary?: string;+ task?: { description?: string | null; onOpen?: () => void; title: string };+}) => {+ const { t } = useTranslation('chat');+ return (+ <div className={contextStyles.block}>+ {task && (+ <>+ <span className={contextStyles.label}>{t('goalProcess.decision.context.task')}</span>+ <div style={{ lineHeight: '22px', minWidth: 0 }}>+ <span className={contextStyles.title} onClick={task.onOpen}>+ {task.title}+ </span>+ {task.description && (+ <div className={contextStyles.description}>{task.description}</div>+ )}+ </div>+ </>+ )}+ {summary && (+ <>+ <span className={contextStyles.label}>{t('goalProcess.decision.context.decision')}</span>+ <span style={{ lineHeight: '22px' }}>{summary}</span>+ </>+ )}+ </div>+ );+};++/**+ * The one-sentence account a gate opens with: what stopped, and why it is the+ * owner's call. Built from the category and the Task it is about.+ */+export const useGateSummary = () => {+ const { t } = useTranslation('chat');+ return (category: GateCategory, taskTitle?: string | null) =>+ t(`goalProcess.decision.summary.${category}` as const, {+ task: taskTitle || t('goalProcess.decision.summary.thisTask'),+ });+};++export interface GoalDecisionCaseProps {+ /** Portal the submit footer into a host-owned footer (the island pins it). */+ actionsPortalTarget?: HTMLElement | null;+ /** The agent the goal answers to; it is the one asking. */+ agentId?: string | null;+ /**+ * What the gate stands on beyond its question — the main Agent's diagnosis,+ * the coordinator's reason when the question is the Agent's own.+ */+ basis?: string | null;+ /** Read-only: the case is shown, the answer form is not. */+ canAnswer?: boolean;+ category: GateCategory;+ decision: GoalGateDecision;+ /** Proof the owner may want before answering: attempts, acceptance, the run. */+ evidence?: ReactNode;+ /**+ * Quiet links on the answer row's leading edge (open the task, its+ * attempts), across from the submit button — the way a brief carries its+ * "View run" — instead of a row of their own above the question.+ */+ footer?: ReactNode;+ /** The host already says who is asking (the island's own header). */+ hideAsker?: boolean;+ onDecide: (optionId: string, resolution?: string) => Promise<unknown>;+ /** What the gate is about — the Task it stopped, linked to its run. */+ subject?: ReactNode;+ /**+ * What the owner is being asked to decide, in one sentence: which work+ * stopped and why it came to them. Leads the case beside the Task it is+ * about; the question alone read as a riddle.+ */+ summary?: string;+ /** The Task the gate stopped: its title and what it was asked to do. */+ task?: { description?: string | null; onOpen?: () => void; title: string };+}++/**+ * One gate, asked the way the product asks every question of its own: the+ * AskUserQuestion form, with the answers' consequences written out and the+ * advised one marked. What kind of question it is leads, so a system+ * problem never reads like a judgment call; the evidence sits between the+ * question's framing and its answers.+ *+ * Shared by the goal page, the approval island and the result page, so a+ * gate reads and answers the same wherever it is met.+ */+const GoalDecisionCase = ({+ actionsPortalTarget,+ agentId,+ hideAsker,+ basis,+ canAnswer = true,+ category,+ decision,+ evidence,+ footer,+ onDecide,+ subject,+ summary,+ task,+}: GoalDecisionCaseProps) => {+ const { t } = useTranslation('chat');+ const optionCopy = useGateOptionCopy();++ // The coordinator's English reason renders in the reader's language when+ // recognized; an Agent's question is already in the goal's language.+ const rawReason = coordinatorGateReason(decision.question) ?? decision.question;+ const reasonCopy = coordinatorReasonCopy(rawReason);+ const questionText = reasonCopy ? t(reasonCopy.key as any, reasonCopy.params) : rawReason;+ const basisText = basis && basis.trim() !== rawReason.trim() ? basis.trim() : undefined;++ const questions = useMemo(+ () => [+ toGateQuestion(decision, {+ basis: basisText,+ describe: (option) => optionCopy.describe(option, category),+ label: (option) => optionCopy.label(option, category),+ question: questionText,+ }),+ ],+ [basisText, category, decision, optionCopy, questionText],+ );++ const handleSubmit = useCallback(+ async (answers: ClarificationAnswer[]) => {+ const answer = toGateAnswer(decision, answers);+ if (!answer) return;+ await onDecide(answer.optionId, answer.resolution?.trim() || undefined);+ },+ [decision, onDecide],+ );++ // With links to lay beside it, the card owns the submit row: links on the+ // left, the form's submit portalled in on the right.+ const [ownFooter, setOwnFooter] = useState<HTMLDivElement | null>(null);+ const ownsFooter = !!footer && !actionsPortalTarget;++ return (+ <Flexbox gap={12}>+ {!hideAsker && <GoalDecisionAsker agentId={agentId} category={category} />}+ {(task || summary) && <GateContext summary={summary} task={task} />}+ {subject}+ {canAnswer ? (+ <ClarificationQuestions+ actionsPortalTarget={ownsFooter ? ownFooter : actionsPortalTarget}+ draftKey={`goal-gate:${decision.id}`}+ key={decision.id}+ questions={questions}+ submitLabel={t('goalProcess.decision.submit')}+ supplementPlaceholder={t('goalProcess.gate.notePlaceholder')}+ onSubmit={handleSubmit}+ />+ ) : (+ <Flexbox gap={4}>+ <Text weight={500}>{questionText}</Text>+ {basisText && <Text type={'secondary'}>{basisText}</Text>}+ </Flexbox>+ )}+ {(ownsFooter || (!canAnswer && footer)) && (+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ <Flexbox horizontal align={'center'} gap={4} style={{ flex: 'none' }}>+ {footer}+ </Flexbox>+ {canAnswer && <div ref={setOwnFooter} style={{ flex: 1, minWidth: 0 }} />}+ </Flexbox>+ )}+ {evidence}+ </Flexbox>+ );+};++export default GoalDecisionCase;diff --git a/src/features/AgentGoals/GoalDecision/mapping.test.ts b/src/features/AgentGoals/GoalDecision/mapping.test.tsnew file mode 100644index 00000000000..b310ca05743--- /dev/null+++ b/src/features/AgentGoals/GoalDecision/mapping.test.ts@@ -0,0 +1,119 @@+import {+ GOAL_CLARIFICATION_TITLE,+ GOAL_MACHINE_GATE_TITLE,+ GOAL_MANAGER_QUESTION_TITLE,+} from '@lobechat/const/goal';+import { describe, expect, it } from 'vitest';++import { goalGateCategory, toGateAnswer, toGateQuestion } from './mapping';++const recover = [+ { id: 'retry', label: 'Retry task' },+ { id: 'retire', label: 'Retire task' },+];++describe('goalGateCategory', () => {+ it('tells a system problem apart from a judgment call', () => {+ expect(goalGateCategory({ nodeTitle: GOAL_MACHINE_GATE_TITLE, options: recover })).toBe(+ 'machine',+ );+ expect(+ goalGateCategory({ nodeTitle: 'Choose how to recover failed task', options: recover }),+ ).toBe('judgment');+ });++ it('recognizes the goal acceptance and clarification gates', () => {+ expect(goalGateCategory({ options: [...recover, { id: 'fail', label: 'Fail goal' }] })).toBe(+ 'goalAcceptance',+ );+ expect(goalGateCategory({ nodeTitle: GOAL_CLARIFICATION_TITLE })).toBe('clarify');+ });++ it("reads the main Agent's own answers as its question, on either gate", () => {+ expect(goalGateCategory({ nodeTitle: GOAL_MANAGER_QUESTION_TITLE, options: [] })).toBe(+ 'agentQuestion',+ );+ // A takeover question rides the failed Task's gate under the coordinator title.+ expect(+ goalGateCategory({+ nodeTitle: 'Choose how to recover failed task',+ options: [+ { effect: 'retry', id: 'waive', label: 'Waive it' },+ { effect: 'retire', id: 'keep', label: 'Keep it' },+ ],+ }),+ ).toBe('agentQuestion');+ });+});++describe('toGateQuestion', () => {+ it('writes each answer with what it does and marks the advised one', () => {+ const question = toGateQuestion(+ { id: 'd1', options: recover, question: 'Q', recommendedOptionId: 'retry' },+ {+ basis: 'Main Agent: the fixture is stale',+ describe: (option) => (option.id === 'retry' ? 'Send it back' : undefined),+ label: (option) => option.label.toUpperCase(),+ question: 'The attempt budget is used up',+ },+ );++ expect(question).toEqual({+ description: 'Main Agent: the fixture is stale',+ header: '',+ id: 'd1',+ options: [+ { description: 'Send it back', id: 'retry', label: 'RETRY TASK', recommended: true },+ { id: 'retire', label: 'RETIRE TASK' },+ ],+ question: 'The attempt budget is used up',+ });+ });++ it("keeps an Agent's own consequence over the generic one", () => {+ const question = toGateQuestion(+ {+ id: 'd2',+ options: [{ description: 'PR order follows merge time', id: 'waive', label: 'Waive' }],+ question: 'Waive?',+ },+ { describe: () => 'generic', label: (o) => o.label, question: 'Waive?' },+ );+ expect(question.options[0].description).toBe('PR order follows merge time');+ });+});++describe('toGateAnswer', () => {+ const decision = { id: 'd1', options: recover, question: 'Q', recommendedOptionId: 'retire' };++ it('passes a picked option and its note through', () => {+ expect(+ toGateAnswer(decision, [+ { note: 'use staging', optionId: 'retire', questionId: 'd1', type: 'option' },+ ]),+ ).toEqual({ optionId: 'retire', resolution: 'use staging' });+ });++ it('turns written-out guidance into a retry that carries it', () => {+ expect(+ toGateAnswer(decision, [{ questionId: 'd1', text: 'Try the v2 API', type: 'text' }]),+ ).toEqual({ optionId: 'retry', resolution: 'Try the v2 API' });+ });++ it('falls back to the advised answer when nothing retries', () => {+ expect(+ toGateAnswer(+ {+ id: 'd2',+ options: [+ { id: 'desktop', label: 'Desktop' },+ { id: 'all', label: 'All' },+ ],+ question: 'Scope?',+ recommendedOptionId: 'all',+ },+ [{ questionId: 'd2', text: 'Both, desktop first', type: 'text' }],+ ),+ ).toEqual({ optionId: 'all', resolution: 'Both, desktop first' });+ });+});diff --git a/src/features/AgentGoals/GoalDecision/mapping.ts b/src/features/AgentGoals/GoalDecision/mapping.tsnew file mode 100644index 00000000000..2f000a2876c--- /dev/null+++ b/src/features/AgentGoals/GoalDecision/mapping.ts@@ -0,0 +1,104 @@+import {+ GOAL_CLARIFICATION_OPTION,+ GOAL_CLARIFICATION_TITLE,+ GOAL_MACHINE_GATE_TITLE,+ GOAL_MANAGER_QUESTION_TITLE,+} from '@lobechat/const/goal';+import type { GoalDecisionOption } from '@lobechat/types';++import type {+ ClarificationAnswer,+ ClarificationQuestion,+} from '@/features/ClarificationQuestions/answers';++/**+ * What kind of thing a gate asks, which decides how it is framed:+ * - `machine` — the setup is broken or the automatic retries are spent; the+ * owner fixes something, nothing about the work is in question+ * - `judgment` — the coordinator stopped on a failure only the owner can weigh+ * - `goalAcceptance` — the goal's own acceptance ended unmet+ * - `agentQuestion` — the main Agent asked a concrete question with its own answers+ * - `clarify` — a clarification round, asked as its own form+ */+export type GoalGateCategory =+ 'agentQuestion' | 'clarify' | 'goalAcceptance' | 'judgment' | 'machine';++/** The ids the coordinator writes on its own gates; anything else is an Agent's answer. */+const COORDINATOR_OPTION_IDS = new Set(['fail', 'retire', 'retry']);++export const goalGateCategory = (gate: {+ nodeTitle?: string | null;+ options?: GoalDecisionOption[] | null;+}): GoalGateCategory => {+ if (gate.nodeTitle === GOAL_CLARIFICATION_TITLE) return 'clarify';+ if (gate.nodeTitle === GOAL_MANAGER_QUESTION_TITLE) return 'agentQuestion';+ if (gate.nodeTitle === GOAL_MACHINE_GATE_TITLE) return 'machine';+ const options = gate.options ?? [];+ // A takeover question rides the failed Task's gate, so its title is the+ // coordinator's; its answers are what give it away.+ if (options.some((option) => !COORDINATOR_OPTION_IDS.has(option.id))) return 'agentQuestion';+ if (options.some((option) => option.id === 'fail')) return 'goalAcceptance';+ return 'judgment';+};++export interface GoalGateDecision {+ id: string;+ options?: GoalDecisionOption[] | null;+ question: string;+ recommendedOptionId?: string | null;+}++/**+ * One gate as one AskUserQuestion question: the question in the reader's+ * words, the evidence it stands on underneath, and each answer with what it+ * does. The coordinator's own answers get their consequence from `describe`;+ * an Agent's answers carry their own.+ */+export const toGateQuestion = (+ decision: GoalGateDecision,+ copy: {+ basis?: string | null;+ describe: (option: GoalDecisionOption) => string | undefined;+ label: (option: GoalDecisionOption) => string;+ question: string;+ },+): ClarificationQuestion => ({+ ...(copy.basis ? { description: copy.basis } : {}),+ header: '',+ id: decision.id,+ options: (decision.options ?? [])+ .filter((option) => option.id !== GOAL_CLARIFICATION_OPTION.answer)+ .map((option) => {+ const description = option.description ?? copy.describe(option);+ return {+ ...(description ? { description } : {}),+ id: option.id,+ label: copy.label(option),+ ...(option.id === decision.recommendedOptionId ? { recommended: true } : {}),+ };+ }),+ question: copy.question,+});++/**+ * Which option a written-out answer stands for. A gate has no "other" answer+ * of its own, so words with no pick go with the option that carries guidance+ * forward — an explicit free answer, then whatever retries, then the advised+ * one — and become its note.+ */+const optionForWrittenAnswer = (options: GoalDecisionOption[], recommended?: string | null) =>+ options.find((option) => option.id === GOAL_CLARIFICATION_OPTION.answer) ??+ options.find((option) => option.effect === 'retry' || option.id === 'retry') ??+ options.find((option) => option.id === recommended) ??+ options[0];++export const toGateAnswer = (+ decision: GoalGateDecision,+ answers: ClarificationAnswer[],+): { optionId: string; resolution?: string } | undefined => {+ const answer = answers.find((item) => item.questionId === decision.id) ?? answers[0];+ if (!answer) return undefined;+ if (answer.type === 'option') return { optionId: answer.optionId, resolution: answer.note };+ const option = optionForWrittenAnswer(decision.options ?? [], decision.recommendedOptionId);+ return option ? { optionId: option.id, resolution: answer.text } : undefined;+};diff --git a/src/features/AgentGoals/ProcessControl/Frontier.tsx b/src/features/AgentGoals/ProcessControl/Frontier.tsxindex 16270a836b7..b26dea98b4c 100644--- a/src/features/AgentGoals/ProcessControl/Frontier.tsx+++ b/src/features/AgentGoals/ProcessControl/Frontier.tsx@@ -1,10 +1,10 @@'use client';-import type { AcceptanceStatus, GoalDecisionOption } from '@lobechat/types';-import { Block, Flexbox, Icon, Tooltip } from '@lobehub/ui';-import { Button, Divider, Tag, Text, TextArea } from '@lobehub/ui/base-ui';+import type { AcceptanceStatus } from '@lobechat/types';+import { Block, Flexbox, Icon } from '@lobehub/ui';+import { Button, Divider, Tag, Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';-import { ChevronDown, ChevronRight, Plus } from 'lucide-react';+import { ChevronDown, ChevronRight, History, ListTodo, Plus } from 'lucide-react';import { Fragment, memo, useState } from 'react';import { useTranslation } from 'react-i18next';@@ -15,6 +15,11 @@ import { useActivityTime } from '@/hooks/useActivityTime';import { useChatStore } from '@/store/chat';import GoalClarification, { type PendingGoalClarification } from '../GoalClarification';+import GoalDecisionCase, {+ type GoalGateCategory,+ goalGateCategory,+ useGateSummary,+} from '../GoalDecision';import AssigneeProfileAvatar from './AssigneeProfileAvatar';import {coordinatorGateReason,@@ -66,6 +71,16 @@ const styles = createStaticStyles(({ css }) => ({padding-block: 8px 14px;padding-inline: 26px 12px;`,+ // A gate is an intent card: lifted off the list so it reads as the one thing+ // asking for the owner, not another row.+ decisionCard: css`+ padding: 16px;+ border: 1px solid ${cssVar.colorBorderSecondary};+ border-radius: ${cssVar.borderRadiusLG};++ background: ${cssVar.colorBgElevated};+ box-shadow: ${cssVar.boxShadowTertiary};+ `,deps: css`font-family: ${cssVar.fontFamilyCode};font-size: 12px;@@ -112,7 +127,7 @@ const styles = createStaticStyles(({ css }) => ({export interface FrontierActions {addTask: (title: string, description?: string) => Promise<void>;- decide: (decisionId: string, optionId: string, resolution?: string) => void;+ decide: (decisionId: string, optionId: string, resolution?: string) => Promise<unknown>;}interface FrontierProps {@@ -124,27 +139,6 @@ interface FrontierProps {planning?: boolean;}-/** Server option ids are stable; their labels are English strings from the coordinator. */-export const useGateOptionLabel = () => {- const { t } = useTranslation('chat');- return (option: GoalDecisionOption) => {- switch (option.id) {- case 'fail': {- return t('goalProcess.gate.option.fail');- }- case 'retire': {- return t('goalProcess.gate.option.retire');- }- case 'retry': {- return t('goalProcess.gate.option.retry');- }- default: {- return option.label;- }- }- };-};-const RowGlyph = memo<{ kind: FrontierItem['kind']; view: GoalNodeView }>(({ kind, view }) => {switch (kind) {case 'done': {@@ -331,18 +325,125 @@ const AcceptanceChip = memo<{ view: GoalNodeView }>(({ view }) => {AcceptanceChip.displayName = 'GoalAcceptanceChip';-const FrontierRow = memo<{+/**+ * What a gate's answer should be weighed against: the Task it stopped, one+ * click from its run and its acceptance, and what each attempt did. Folded to+ * one line until opened — the question leads, the proof is on demand.+ */+/**+ * The way into what a gate stands on, as quiet links on its answer row: open+ * the Task's run, and fold its attempts open beneath the card.+ */+const GateLinks = memo<{+ ledgerOpen: boolean;+ onOpen: () => void;+ onToggleLedger: () => void;+ subject: GoalNodeView;+}>(({ ledgerOpen, onOpen, onToggleLedger, subject }) => {+ const { t } = useTranslation('chat');+ const attempts = subject.attempts.length;+ const quiet = { color: cssVar.colorTextSecondary };++ return (+ <>+ <Button icon={ListTodo} size={'small'} style={quiet} type={'text'} onClick={onOpen}>+ {t('goalProcess.decision.viewRun')}+ </Button>+ {attempts > 0 && (+ <Button+ icon={ledgerOpen ? ChevronDown : History}+ size={'small'}+ style={quiet}+ type={'text'}+ onClick={onToggleLedger}+ >+ {t('goalProcess.decision.attempts', { count: attempts })}+ </Button>+ )}+ <AcceptanceChip view={subject} />+ </>+ );+});++GateLinks.displayName = 'GoalGateLinks';++/**+ * A gate the owner answers, as one card of its own above the task list: who is+ * asking, what about, the question and its answers. Lifted out of the list —+ * a decision is the one thing on the page waiting for the reader, not another+ * row in it.+ */+const GateCard = memo<{actions: FrontierActions;canEdit: boolean;+ category: Exclude<GoalGateCategory, 'clarify'>;+ goalAgentId?: string | null;+ numbers: Map<string, number>;+ onSelect: (nodeId: string) => void;+ subject?: GoalNodeView;+ view: GoalNodeView;+}>(({ actions, canEdit, category, goalAgentId, numbers, onSelect, subject, view }) => {+ const { t } = useTranslation('chat');+ const gateSummary = useGateSummary();+ const [ledgerOpen, setLedgerOpen] = useState(false);+ const taskSubject = subject?.node.kind === 'task' ? subject : undefined;+ const subjectTitle =+ subject?.node.kind === 'task'+ ? (() => {+ const key = coordinatorNodeTitleKey(subject);+ return key ? t(key as any) : subject.node.title;+ })()+ : undefined;+ return (+ <div className={styles.decisionCard} data-goal-gate={view.decision!.id}>+ <GoalDecisionCase+ agentId={goalAgentId}+ basis={view.node.description}+ canAnswer={canEdit}+ category={category}+ decision={view.decision!}+ evidence={taskSubject && ledgerOpen ? <AttemptLedger view={taskSubject} /> : undefined}+ summary={gateSummary(category, subjectTitle)}+ footer={+ // A goal-level question (the main Agent asking about the goal itself)+ // stopped no Task, so there is no run to open.+ taskSubject ? (+ <GateLinks+ ledgerOpen={ledgerOpen}+ subject={taskSubject}+ onOpen={() => onSelect(taskSubject.node.id)}+ onToggleLedger={() => setLedgerOpen(!ledgerOpen)}+ />+ ) : undefined+ }+ task={+ taskSubject && subjectTitle+ ? {+ description: taskSubject.node.description,+ onOpen: () => onSelect(taskSubject.node.id),+ title:+ numbers.get(taskSubject.node.id) !== undefined+ ? `#${numbers.get(taskSubject.node.id)} ${subjectTitle}`+ : subjectTitle,+ }+ : undefined+ }+ onDecide={(optionId, resolution) => actions.decide(view.decision!.id, optionId, resolution)}+ />+ </div>+ );+});++GateCard.displayName = 'GoalGateCard';++const FrontierRow = memo<{item: FrontierItem;numbers: Map<string, number>;onSelect: (nodeId: string) => void;/** A gate's ledger is the ledger of the Task it was opened for. */subject?: GoalNodeView;-}>(({ actions, canEdit, item, numbers, onSelect, subject }) => {+}>(({ item, numbers, onSelect, subject }) => {const { t } = useTranslation('chat');- const optionLabel = useGateOptionLabel();- const [note, setNote] = useState('');const { view } = item;const { node } = view;const deps = view.dependsOn.map((id) => numbers.get(id)).filter(Boolean);@@ -380,8 +481,6 @@ const FrontierRow = memo<{}: null;- const stop = (event: React.MouseEvent) => event.stopPropagation();-return (<Blockclickable@@ -425,9 +524,6 @@ const FrontierRow = memo<{// out.<Flexbox className={styles.body} gap={14}>{item.kind === 'gate' && view.decision && (- // State the problem itself, in the user's language when the- // coordinator's vocabulary is recognized — the buttons below- // already carry the choices, so no extra framing sentence.<Text fontSize={13} weight={500}>{gateReasonText ?? view.decision.question}</Text>@@ -441,39 +537,6 @@ const FrontierRow = memo<{)}{item.kind === 'stale' && <StaleBody view={view} />}<AttemptLedger view={subject ?? view} />- {item.kind === 'gate' && canEdit && (- // A click here is aimed at the note field or a decision button —- // never at "open this node".- <Flexbox gap={14} onClick={stop}>- <Flexbox gap={4}>- <span className={styles.label}>{t('goalProcess.gate.noteLabel')}</span>- <TextArea- autoSize={{ maxRows: 3, minRows: 1 }}- placeholder={t('goalProcess.gate.notePlaceholder')}- value={note}- onChange={(event) => setNote(event.target.value)}- />- </Flexbox>- {/* Actions close the card: read the situation, add guidance, then decide. */}- <Flexbox horizontal gap={8}>- {view.decision?.options?.map((option) => (- <Tooltip key={option.id} title={option.description}>- <Button- type={- option.id === view.decision?.recommendedOptionId ? 'primary' : 'default'- }- onClick={(event) => {- stop(event);- actions.decide(view.decision!.id, option.id, note.trim() || undefined);- }}- >- {optionLabel(option)}- </Button>- </Tooltip>- ))}- </Flexbox>- </Flexbox>- )}</Flexbox>)}</Block>@@ -514,7 +577,18 @@ const Frontier = memo<FrontierProps>(({ actions, canEdit, graph, onSelect, plann(item) => item.kind === 'gate' && viewGateKind(item.view) === 'clarifyGoal',): [];- const rows = graph.frontier.filter((item) => !clarifyItems.includes(item));+ // Every other gate is its own decision card above the list.+ const gateCards = graph.frontier.flatMap((item) => {+ if (item.kind !== 'gate' || !item.view.decision) return [];+ const category = goalGateCategory({+ nodeTitle: item.view.node.title,+ options: item.view.decision.options,+ });+ return category === 'clarify' ? [] : [{ category, item }];+ });+ const rows = graph.frontier.filter(+ (item) => !clarifyItems.includes(item) && !gateCards.some((gate) => gate.item === item),+ );const pendingClarifications: PendingGoalClarification[] = clarifyItems.map(({ view }) => ({decisionId: view.decision!.id,description: view.node.description,@@ -541,88 +615,106 @@ const Frontier = memo<FrontierProps>(({ actions, canEdit, graph, onSelect, plann{canEdit && <AddTaskButton onAdd={actions.addTask} />}</Flexbox>- <div className={styles.list}>- <Block gap={0} padding={2} variant={'borderless'}>- {graph.frontier.length === 0 &&- (planning ? (- <Flexbox horizontal align={'center'} gap={10} padding={12}>- <RunningGlyph size={16} />+ {gateCards.map(({ category, item }) => (+ <GateCard+ actions={actions}+ canEdit={canEdit}+ category={category}+ goalAgentId={graph.goal.agentId}+ key={item.key}+ numbers={numbers}++ subject={item.view.gateSubjectId ? graph.byId[item.view.gateSubjectId] : undefined}+ view={item.view}+ onSelect={onSelect}+ />+ ))}++ {(rows.length > 0 ||+ pendingClarifications.length > 0 ||+ graph.blocked.length > 0 ||+ graph.frontier.length === 0) && (+ <div className={styles.list}>+ <Block gap={0} padding={2} variant={'borderless'}>+ {graph.frontier.length === 0 &&+ (planning ? (+ <Flexbox horizontal align={'center'} gap={10} padding={12}>+ <RunningGlyph size={16} />+ <Flexbox gap={2}>+ <Text weight={500}>{t('goalProcess.planning.title')}</Text>+ <Text fontSize={12} type={'secondary'}>+ {t('goalProcess.planning.description')}+ </Text>+ </Flexbox>+ </Flexbox>+ ) : (+ <Flexbox gap={2} padding={12}>+ <Text weight={500}>+ {achieved+ ? t('goalProcess.frontier.achievedTitle')+ : t('goalProcess.frontier.emptyTitle')}+ </Text>+ <Text fontSize={12} type={'secondary'}>+ {achieved+ ? t('goalProcess.frontier.achievedDescription')+ : t('goalProcess.frontier.emptyDescription')}+ </Text>+ </Flexbox>+ ))}+ {pendingClarifications.length > 0 && (+ // Filled so the one thing blocking the goal stands apart from the+ // task rows around it.+ <Block gap={12} padding={12} variant={'filled'}><Flexbox gap={2}>- <Text weight={500}>{t('goalProcess.planning.title')}</Text>+ <Text weight={500}>{t('goalProcess.clarify.title')}</Text><Text fontSize={12} type={'secondary'}>- {t('goalProcess.planning.description')}+ {t('goalProcess.clarify.description')}</Text></Flexbox>- </Flexbox>- ) : (- <Flexbox gap={2} padding={12}>- <Text weight={500}>- {achieved- ? t('goalProcess.frontier.achievedTitle')- : t('goalProcess.frontier.emptyTitle')}- </Text>- <Text fontSize={12} type={'secondary'}>- {achieved- ? t('goalProcess.frontier.achievedDescription')- : t('goalProcess.frontier.emptyDescription')}- </Text>- </Flexbox>- ))}- {pendingClarifications.length > 0 && (- // Filled so the one thing blocking the goal stands apart from the- // task rows around it.- <Block gap={12} padding={12} variant={'filled'}>- <Flexbox gap={2}>- <Text weight={500}>{t('goalProcess.clarify.title')}</Text>- <Text fontSize={12} type={'secondary'}>- {t('goalProcess.clarify.description')}- </Text>- </Flexbox>- <GoalClarification goalId={graph.goal.id} pending={pendingClarifications} />- </Block>- )}- {rows.map((item, index) => (- <Fragment key={item.key}>- {(index > 0 || pendingClarifications.length > 0) && (- <Divider dashed style={{ margin: 0 }} />- )}- <FrontierRow- actions={actions}- canEdit={canEdit}- item={item}- numbers={numbers}- subject={item.view.gateSubjectId ? graph.byId[item.view.gateSubjectId] : undefined}- onSelect={onSelect}- />- </Fragment>- ))}- </Block>- {graph.blocked.length > 0 && (- <>- <Divider dashed style={{ margin: 0 }} />- <div className={styles.blockedHead} onClick={() => setShowBlocked(!showBlocked)}>- <Icon icon={showBlocked ? ChevronDown : ChevronRight} size={12} />- <span>{t('goalProcess.frontier.blocked', { count: graph.blocked.length })}</span>- </div>- {showBlocked && (- <Block gap={0} padding={2} variant={'borderless'}>- {graph.blocked.map((view, index) => (- <Fragment key={view.node.id}>- {index > 0 && <Divider dashed style={{ margin: 0 }} />}- <FrontierRow- actions={actions}- canEdit={canEdit}- item={{ key: view.node.id, kind: 'ready', rank: 3, view }}- numbers={numbers}- onSelect={onSelect}- />- </Fragment>- ))}+ <GoalClarification goalId={graph.goal.id} pending={pendingClarifications} /></Block>)}- </>- )}- </div>+ {rows.map((item, index) => (+ <Fragment key={item.key}>+ {(index > 0 || pendingClarifications.length > 0) && (+ <Divider dashed style={{ margin: 0 }} />+ )}+ <FrontierRow+ item={item}+ numbers={numbers}+ subject={+ item.view.gateSubjectId ? graph.byId[item.view.gateSubjectId] : undefined+ }+ onSelect={onSelect}+ />+ </Fragment>+ ))}+ </Block>+ {graph.blocked.length > 0 && (+ <>+ <Divider dashed style={{ margin: 0 }} />+ <div className={styles.blockedHead} onClick={() => setShowBlocked(!showBlocked)}>+ <Icon icon={showBlocked ? ChevronDown : ChevronRight} size={12} />+ <span>{t('goalProcess.frontier.blocked', { count: graph.blocked.length })}</span>+ </div>+ {showBlocked && (+ <Block gap={0} padding={2} variant={'borderless'}>+ {graph.blocked.map((view, index) => (+ <Fragment key={view.node.id}>+ {index > 0 && <Divider dashed style={{ margin: 0 }} />}+ <FrontierRow+ item={{ key: view.node.id, kind: 'ready', rank: 3, view }}+ numbers={numbers}+ onSelect={onSelect}+ />+ </Fragment>+ ))}+ </Block>+ )}+ </>+ )}+ </div>+ )}</Flexbox>);});diff --git a/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx b/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsxindex fd6d0349e2b..6d802a997da 100644--- a/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx+++ b/src/features/AgentGoals/ProcessControl/GoalResultHeader.tsx@@ -1,18 +1,16 @@'use client';import type { GoalGraphDecision } from '@lobechat/types';-import { Flexbox, Tooltip } from '@lobehub/ui';-import { Button, Spin, Text, TextArea, toast } from '@lobehub/ui/base-ui';+import { Flexbox } from '@lobehub/ui';+import { Spin, Text, toast } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar } from 'antd-style';-import { useState } from 'react';import { useTranslation } from 'react-i18next';import { usePermission } from '@/hooks/usePermission';import { useGoalStore } from '@/store/goal';import { shinyTextStyles } from '@/styles';-import { coordinatorGateReason, coordinatorReasonCopy } from './coordinatorCopy';-import { useGateOptionLabel } from './Frontier';+import GoalDecisionCase from '../GoalDecision';import type { GoalGraphView } from './goalGraphViewModel';import {deriveGoalResultStatus,@@ -40,6 +38,7 @@ const styles = createStaticStyles(({ css }) => ({}));interface DecisionStripProps {+ agentId?: string | null;decision: GoalGraphDecision;goalId: string;onDecided: () => Promise<unknown>;@@ -48,68 +47,35 @@ interface DecisionStripProps {/*** The Goal-level acceptance ended unmet and the coordinator opened a gate on* it. The owner decides here, beside the criteria that failed, instead of- * hunting for the gate on the 执行过程 tab — same options, same endpoint.+ * hunting for the gate on the 执行过程 tab — the same case the goal page and+ * the island ask, on the same endpoint.*/-const DecisionStrip = ({ decision, goalId, onDecided }: DecisionStripProps) => {+const DecisionStrip = ({ agentId, decision, goalId, onDecided }: DecisionStripProps) => {const { t } = useTranslation('chat');const decideGoal = useGoalStore((s) => s.decideGoal);const { allowed: canEdit } = usePermission('create_content');- const optionLabel = useGateOptionLabel();- const [note, setNote] = useState('');- const [deciding, setDeciding] = useState<string>();- const rawReason = coordinatorGateReason(decision.question);- const reasonCopy = coordinatorReasonCopy(rawReason);- const reason = reasonCopy ? t(reasonCopy.key as any, reasonCopy.params) : rawReason;-- const decide = async (optionId: string) => {- setDeciding(optionId);+ const decide = async (optionId: string, resolution?: string) => {try {- await decideGoal(goalId, {- decisionId: decision.id,- optionId,- resolution: note.trim() || undefined,- });+ await decideGoal(goalId, { decisionId: decision.id, optionId, resolution });await onDecided();} catch (error) {console.error('[goal:result-decision]', error);toast.error(t('goalProcess.result.gate.error'));- } finally {- setDeciding(undefined);+ // Rethrow so the form keeps the draft and can be sent again.+ throw error;}};return (- <Flexbox className={styles.strip} data-goal-result-gate={decision.id} gap={12}>- <Flexbox gap={4}>- {reason && <Text weight={500}>{reason}</Text>}- <Text type={'secondary'}>{t('goalProcess.result.gate.prompt')}</Text>- </Flexbox>- {canEdit && (- <>- <TextArea- autoSize={{ maxRows: 3, minRows: 1 }}- placeholder={t('goalProcess.gate.notePlaceholder')}- value={note}- onChange={(event) => setNote(event.target.value)}- />- <Flexbox horizontal gap={8} wrap={'wrap'}>- {decision.options?.map((option) => (- <Tooltip key={option.id} title={option.description}>- <Button- danger={option.id === 'fail'}- disabled={!!deciding && deciding !== option.id}- loading={deciding === option.id}- type={option.id === decision.recommendedOptionId ? 'primary' : 'default'}- onClick={() => decide(option.id)}- >- {optionLabel(option)}- </Button>- </Tooltip>- ))}- </Flexbox>- </>- )}+ <Flexbox className={styles.strip} data-goal-result-gate={decision.id}>+ <GoalDecisionCase+ agentId={agentId}+ canAnswer={canEdit}+ category={'goalAcceptance'}+ decision={decision}+ onDecide={decide}+ /></Flexbox>);};@@ -163,6 +129,7 @@ const GoalResultHeader = ({ data, graph }: GoalResultHeaderProps) => {)}{status === 'awaitingDecision' && gate?.kind === 'pending' && (<DecisionStrip+ agentId={goal.agentId}decision={gate.decision}goalId={goal.id}onDecided={data.mutateAcceptance}diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.tsindex 5a433888949..c1b295159b5 100644--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.test.ts@@ -1,9 +1,11 @@+import { GOAL_MACHINE_GATE_TITLE } from '@lobechat/const/goal';import { describe, expect, it } from 'vitest';import {coordinatorGateKind,coordinatorGateReason,coordinatorReasonCopy,+ gateOptionLabelKey,} from './coordinatorCopy';const decision = (ids: string[]) => ({ options: ids.map((id) => ({ id, label: id })) }) as any;@@ -113,3 +115,31 @@ describe('coordinatorReasonCopy', () => {expect(coordinatorReasonCopy(undefined)).toBeUndefined();});});++describe('machine gate copy', () => {+ it('reads the machine gate off its title and gives its Retry the "fixed it" label', () => {+ expect(coordinatorGateKind(decision(['retry', 'retire']), GOAL_MACHINE_GATE_TITLE)).toBe(+ 'fixSetup',+ );+ expect(gateOptionLabelKey({ id: 'retry' }, 'fixSetup')).toBe(+ 'goalProcess.gate.option.fixedRetry',+ );+ expect(gateOptionLabelKey({ id: 'retry' }, 'recoverTask')).toBe(+ 'goalProcess.gate.option.retry',+ );+ expect(gateOptionLabelKey({ id: 'option-1' })).toBeUndefined();+ });++ it('strips the machine gate question down to what broke', () => {+ expect(+ coordinatorGateReason(+ 'Setup problem: Working directory does not exist: /tmp/x. Create /tmp/x on the device the agent runs on, or point the agent at a working directory that exists there. Fix it, then retry or retire this task node?',+ ),+ ).toBe(+ 'Setup problem: Working directory does not exist: /tmp/x. Create /tmp/x on the device the agent runs on, or point the agent at a working directory that exists there',+ );+ expect(coordinatorReasonCopy('Task device stayed offline')).toEqual({+ key: 'goalProcess.gate.reason.deviceStayedOffline',+ });+ });+});diff --git a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts b/src/features/AgentGoals/ProcessControl/coordinatorCopy.tsindex affa45309d5..774fd7545f7 100644--- a/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts+++ b/src/features/AgentGoals/ProcessControl/coordinatorCopy.ts@@ -1,5 +1,15 @@-import { GOAL_ACCEPTANCE_TASK_TITLE, GOAL_CLARIFICATION_OPTION } from '@lobechat/const/goal';-import type { GoalGraphDecision } from '@lobechat/types';+import {+ GOAL_ACCEPTANCE_TASK_TITLE,+ GOAL_CLARIFICATION_OPTION,+ GOAL_MACHINE_GATE_TITLE,+ GOAL_MANAGER_QUESTION_TITLE,+} from '@lobechat/const/goal';+import type { GoalDecisionOption, GoalGraphDecision } from '@lobechat/types';+import {+ coordinatorGateReason,+ coordinatorReasonCopy,+ type LocalizedCopyRef,+} from '@lobechat/utils/goalCopy';import type { GoalNodeView } from './goalGraphViewModel';@@ -11,24 +21,23 @@ import type { GoalNodeView } from './goalGraphViewModel';* not recognize renders verbatim.*/-export type CoordinatorGateKind = 'clarifyGoal' | 'goalAcceptance' | 'recoverTask';--export interface LocalizedCopyRef {- key: string;- params?: Record<string, string>;-}+export type CoordinatorGateKind =+ 'agentQuestion' | 'clarifyGoal' | 'fixSetup' | 'goalAcceptance' | 'recoverTask';const idsOf = (decision?: GoalGraphDecision | null): Set<string> =>new Set((decision?.options ?? []).map((option) => option.id));export const coordinatorGateKind = (decision?: GoalGraphDecision | null,+ /** The gate node's title; the machine gate shares its options with `recoverTask`. */+ nodeTitle?: string | null,): CoordinatorGateKind | undefined => {const ids = idsOf(decision);// `fail` only ever appears on the terminal acceptance gate, which may also// offer `retire` — check it first.if (ids.has('retry') && ids.has('fail')) return 'goalAcceptance';- if (ids.has('retry') && ids.has('retire')) return 'recoverTask';+ if (ids.has('retry') && ids.has('retire'))+ return nodeTitle === GOAL_MACHINE_GATE_TITLE ? 'fixSetup' : 'recoverTask';if (ids.has(GOAL_CLARIFICATION_OPTION.assume) && ids.has(GOAL_CLARIFICATION_OPTION.answer))return 'clarifyGoal';return undefined;@@ -36,10 +45,37 @@ export const coordinatorGateKind = (/** The gate a node view carries — pending first, else the last human-resolved one. */export const viewGateKind = (view: GoalNodeView): CoordinatorGateKind | undefined =>- coordinatorGateKind(view.decision ?? view.humanTouches.at(-1));+ coordinatorGateKind(view.decision ?? view.humanTouches.at(-1), view.node.title);export const gateTitleKey = (kind: CoordinatorGateKind): string => `goalProcess.gate.title.${kind}`;+/**+ * Locale key for a coordinator gate option, or undefined for a planner-authored+ * option that keeps its stored label. The machine gate's Retry says the person+ * fixed something first.+ */+export const gateOptionLabelKey = (+ option: Pick<GoalDecisionOption, 'id'>,+ kind?: CoordinatorGateKind,+): string | undefined => {+ switch (option.id) {+ case 'fail': {+ return 'goalProcess.gate.option.fail';+ }+ case 'retire': {+ return 'goalProcess.gate.option.retire';+ }+ case 'retry': {+ return kind === 'fixSetup'+ ? 'goalProcess.gate.option.fixedRetry'+ : 'goalProcess.gate.option.retry';+ }+ default: {+ return undefined;+ }+ }+};+/** The coordinator's terminal Task that accepts the whole Goal (matched by its fixed title). */export const isGoalAcceptanceTask = (view: GoalNodeView): boolean =>view.node.kind === 'task' && view.node.title === GOAL_ACCEPTANCE_TASK_TITLE;@@ -51,6 +87,8 @@ export const isGoalAcceptanceTask = (view: GoalNodeView): boolean =>export const coordinatorNodeTitleKey = (view: GoalNodeView): string | undefined => {const { node } = view;if (isGoalAcceptanceTask(view)) return 'goalProcess.node.terminalAcceptance';+ if (node.kind === 'decision' && node.title === GOAL_MANAGER_QUESTION_TITLE)+ return gateTitleKey('agentQuestion');if (node.kind === 'decision') {const kind = viewGateKind(view);if (kind) return gateTitleKey(kind);@@ -58,72 +96,4 @@ export const coordinatorNodeTitleKey = (view: GoalNodeView): string | undefinedreturn undefined;};-/** Strip the coordinator question template down to its dynamic reason half. */-const QUESTION_TAILS = [- /\.?\s*Retry or retire this task node\?$/,- /\.?\s*Retry Goal acceptance or fail this Goal\?$/,- /\.?\s*Retry Goal acceptance, abandon it, or fail this Goal\?$/,-];--export const coordinatorGateReason = (question?: string | null): string | undefined => {- if (!question) return undefined;- for (const tail of QUESTION_TAILS) {- if (tail.test(question)) {- const reason = question.replace(tail, '').trim();- return reason || undefined;- }- }- return question;-};--/** Known coordinator reason templates → chat-ns locale refs. */-const REASON_PATTERNS: Array<{- key: string;- param?: string;- pattern: RegExp;-}> = [- {- key: 'goalProcess.gate.reason.verifyInternalError',- pattern: /^Verification could not run \(internal error\); the delivery was not evaluated\.?$/,- },- {- key: 'goalProcess.gate.reason.verifyFailed',- param: 'id',- pattern: /^Task (\S+) did not pass verification$/,- },- {- key: 'goalProcess.gate.reason.goalAcceptanceFailed',- pattern: /^Goal-level acceptance did not pass$/,- },- {- key: 'goalProcess.gate.reason.attemptBudgetExhausted',- pattern: /^Task attempt budget was exhausted( after an operation was abandoned)?$/,- },- {- key: 'goalProcess.gate.reason.costBudgetExhausted',- pattern: /^Goal cost budget was exhausted( after an operation was abandoned)?$/,- },- {- key: 'goalProcess.gate.reason.recoveryFailed',- pattern:- /^Automatic recovery could not (start the next attempt|restart an abandoned operation)$/,- },- {- // A run that failed outright leaves its runtime error type as the reason- // (e.g. `InvalidProviderAPIKey`). The code stays visible for support; the- // sentence around it is the user's language.- key: 'goalProcess.gate.reason.runError',- param: 'code',- pattern: /^([A-Z][a-z0-9]+[A-Z][A-Za-z0-9]*)$/,- },-];--export const coordinatorReasonCopy = (reason?: string | null): LocalizedCopyRef | undefined => {- if (!reason) return undefined;- const trimmed = reason.trim();- for (const { key, param, pattern } of REASON_PATTERNS) {- const match = pattern.exec(trimmed);- if (match) return { key, ...(param && match[1] ? { params: { [param]: match[1] } } : {}) };- }- return undefined;-};+export { coordinatorGateReason, coordinatorReasonCopy, type LocalizedCopyRef };diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.tsindex 59c0a4d5a27..ed7c94badfc 100644--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.test.ts@@ -1,4 +1,8 @@-import { GOAL_ACCEPTANCE_TASK_TITLE } from '@lobechat/const/goal';+import {+ GOAL_ACCEPTANCE_TASK_TITLE,+ GOAL_CLARIFICATION_TITLE,+ GOAL_MACHINE_GATE_TITLE,+} from '@lobechat/const/goal';import type {GoalGraphDecision,GoalGraphEdge,@@ -344,6 +348,28 @@ describe('buildGoalGraphView', () => {expect(view.byId.w1.startedAt).toBeUndefined();});+ it('tells machine gates apart from judgment and clarification gates by their title', () => {+ const view = buildGoalGraphView(+ snapshot({+ nodes: [+ node('m', { kind: 'decision', status: 'waiting', title: GOAL_MACHINE_GATE_TITLE }),+ node('c', { kind: 'decision', status: 'waiting', title: GOAL_CLARIFICATION_TITLE }),+ node('j', {+ kind: 'decision',+ status: 'waiting',+ title: 'Choose how to recover failed task',+ }),+ node('t'),+ ],+ }),+ NOW,+ );+ expect(view.byId.m.decisionCategory).toBe('machine');+ expect(view.byId.c.decisionCategory).toBe('clarification');+ expect(view.byId.j.decisionCategory).toBe('judgment');+ expect(view.byId.t.decisionCategory).toBeUndefined();+ });+it('surfaces a pending gate and hides the waiting task it was opened for', () => {const decision: GoalGraphDecision = {authority: 'user',diff --git a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.tsindex 44a70d4c9e4..03d3659282a 100644--- a/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts+++ b/src/features/AgentGoals/ProcessControl/goalGraphViewModel.ts@@ -1,3 +1,4 @@+import { GOAL_CLARIFICATION_TITLE, GOAL_MACHINE_GATE_TITLE } from '@lobechat/const/goal';import type {GoalGraphDecision,GoalGraphEdge,@@ -84,6 +85,28 @@ export interface GoalArtifactView {workVersionId: string;}+/**+ * What a decision node asks of the person.+ *+ * - `machine` — the setup is broken or the automatic retries ran out; fix it and retry.+ * - `clarification` — the planner needs an answer before it can plan.+ * - `judgment` — a call about the work itself.+ */+export type GoalDecisionCategory = 'clarification' | 'judgment' | 'machine';++/**+ * Read off the coordinator's fixed node titles, the same contract the server+ * uses to recognise its clarification gate.+ */+export const decisionCategoryOf = (+ node: Pick<GoalGraphNode, 'kind' | 'title'>,+): GoalDecisionCategory | undefined => {+ if (node.kind !== 'decision') return undefined;+ if (node.title === GOAL_MACHINE_GATE_TITLE) return 'machine';+ if (node.title === GOAL_CLARIFICATION_TITLE) return 'clarification';+ return 'judgment';+};+export interface GoalNodeView {/** This task's own verification, when it has been dispatched. */acceptance?: GoalNodeAcceptance;@@ -104,6 +127,8 @@ export interface GoalNodeView {closedReason?: string;/** Pending user decision opened on this node. */decision?: GoalGraphDecision;+ /** Decision nodes only: what the decision asks of the person. */+ decisionCategory?: GoalDecisionCategory;dependsOn: string[];/** Findings produced by this Task. */findings: GoalGraphNode[];@@ -456,6 +481,7 @@ export const buildGoalGraphView = (.map((id) => nodeById.get(id)).filter((dep): dep is GoalGraphNode => !!dep && !TERMINAL_NODE_STATUSES.has(dep.status)),decision: nodeDecisions.find((d) => d.status === 'pending'),+ ...(node.kind === 'decision' ? { decisionCategory: decisionCategoryOf(node) } : {}),dependsOn: dependsOn.get(node.id) ?? [],findings:node.kind === 'experiment'diff --git a/src/features/AgentGoals/ProcessControl/useGoalProcessActions.ts b/src/features/AgentGoals/ProcessControl/useGoalProcessActions.tsindex b49ae878a51..49aee77b568 100644--- a/src/features/AgentGoals/ProcessControl/useGoalProcessActions.ts+++ b/src/features/AgentGoals/ProcessControl/useGoalProcessActions.ts@@ -54,7 +54,7 @@ export const useFrontierActions = (goalId: string): FrontierActions => {await refreshGoalGraph(goalId);},decide: (decisionId, optionId, resolution) =>- void decideGoal(goalId, { decisionId, optionId, resolution }),+ decideGoal(goalId, { decisionId, optionId, resolution }),}),[decideGoal, goalId, refreshGoalGraph],);diff --git a/src/features/AgentTasks/AgentTaskDetail/TopicStatusIcon.tsx b/src/features/AgentTasks/AgentTaskDetail/TopicStatusIcon.tsxindex e2c2d4bdd2c..f6ab8eb8eb2 100644--- a/src/features/AgentTasks/AgentTaskDetail/TopicStatusIcon.tsx+++ b/src/features/AgentTasks/AgentTaskDetail/TopicStatusIcon.tsx@@ -6,7 +6,15 @@ import { memo } from 'react';import { EXECUTION_STATUS_VISUALS, type ExecutionStatusVisual } from '@/components/ExecutionStatus';type TopicRunStatus =- 'canceled' | 'completed' | 'device_offline' | 'failed' | 'pending' | 'running' | 'timeout';+ | 'canceled'+ | 'completed'+ | 'device_offline'+ | 'failed'+ | 'pending'+ | 'quota_limited'+ | 'running'+ | 'timeout'+ | 'transient_failed';const STATIC_META: Record<Exclude<TopicRunStatus, 'running'>, ExecutionStatusVisual> = {canceled: EXECUTION_STATUS_VISUALS.canceled,@@ -16,7 +24,10 @@ const STATIC_META: Record<Exclude<TopicRunStatus, 'running'>, ExecutionStatusVisfailed: EXECUTION_STATUS_VISUALS.failed,// Not-yet-started run: same glyph as a backlog task.pending: EXECUTION_STATUS_VISUALS.backlog,+ // A usage limit or a transport fault: retried on a schedule, not failed.+ quota_limited: { color: cssVar.colorWarning, icon: CircleAlert },timeout: { color: cssVar.colorWarning, icon: CircleAlert },+ transient_failed: { color: cssVar.colorWarning, icon: CircleAlert },};const RunningIcon = memo<{ size: number }>(({ size }) => {diff --git a/src/features/ClarificationQuestions/answers.ts b/src/features/ClarificationQuestions/answers.tsindex 5021ff4bf77..8e8a1d261df 100644--- a/src/features/ClarificationQuestions/answers.ts+++ b/src/features/ClarificationQuestions/answers.ts@@ -17,8 +17,11 @@ export interface ClarificationQuestion {header: string;/** Host-owned identity, echoed back on the answer. */id: string;- /** Option ids are submitted as-is, so a host never maps labels back. */- options: { description?: string; id: string; label: string }[];+ /**+ * Option ids are submitted as-is, so a host never maps labels back. A host+ * that advises one answer marks it, and the form badges it.+ */+ options: { description?: string; id: string; label: string; recommended?: boolean }[];question: string;}diff --git a/src/features/ClarificationQuestions/index.tsx b/src/features/ClarificationQuestions/index.tsxindex 914f5487872..8b2a95983c4 100644--- a/src/features/ClarificationQuestions/index.tsx+++ b/src/features/ClarificationQuestions/index.tsx@@ -41,8 +41,12 @@ export interface ClarificationQuestionsProps {draftKey?: string;/** Mirror the answers the draft would submit, for hosts that own the result. */onAnswersChange?: (answers: ClarificationAnswer[]) => void;- /** What "skip" means is the host's call: proceed on assumptions, or without answers. */- onSkip: () => Promise<void> | void;+ /**+ * What "skip" means is the host's call: proceed on assumptions, or without+ * answers. A question that must be answered passes none and the form offers+ * no skip at all.+ */+ onSkip?: () => Promise<void> | void;onSubmit: (answers: ClarificationAnswer[]) => Promise<void> | void;questions: ClarificationQuestion[];/** Defaults to `true`; pass `false` when every question is optional. */@@ -50,6 +54,8 @@ export interface ClarificationQuestionsProps {/** Host wording for the two footer buttons, when "Submit" / "Skip" undersell them. */skipLabel?: string;submitLabel?: string;+ /** Host wording for the notes box, when its notes go somewhere specific. */+ supplementPlaceholder?: string;}/**@@ -73,9 +79,14 @@ const ClarificationQuestions = memo<ClarificationQuestionsProps>(requireAllAnswered,skipLabel,submitLabel,+ supplementPlaceholder,}) => {const { t } = useTranslation('tool');- const labels = useAskUserLabels({ skip: skipLabel, submit: submitLabel });+ const labels = useAskUserLabels({+ skip: onSkip ? skipLabel : '',+ submit: submitLabel,+ supplementPlaceholder,+ });const userId = useUserStore(userProfileSelectors.userId);const storageKey = accountDraftKey(userId, draftKey);const [draft, setDraft] = useState<AskUserDraft | undefined>(() =>@@ -99,8 +110,10 @@ const ClarificationQuestions = memo<ClarificationQuestionsProps>(async (action) => {setFailed(false);try {- if (action.type === 'skip') await onSkip();- else if (action.type === 'submit')+ if (action.type === 'skip') {+ if (!onSkip) return;+ await onSkip();+ } else if (action.type === 'submit')await onSubmit(toClarificationAnswers(questions, action.payload ?? {}));// Sent: nothing left to restore. A failed send keeps the draft.if (storageKey) clearClarificationDraft(storageKey);diff --git a/src/features/ClarificationQuestions/useAskUserLabels.ts b/src/features/ClarificationQuestions/useAskUserLabels.tsindex 19fe057c252..8edcadea04f 100644--- a/src/features/ClarificationQuestions/useAskUserLabels.ts+++ b/src/features/ClarificationQuestions/useAskUserLabels.ts@@ -9,8 +9,10 @@ import { useTranslation } from 'react-i18next';* shows raw keys, so the form waits the moment it takes to load.*/export const useAskUserLabels = (overrides: {+ /** An empty string drops the skip button: the question has no "not now". */skip?: string;submit?: string;+ supplementPlaceholder?: string;}): AskUserQuestionLabels | undefined => {const { t, ready } = useTranslation('tool');if (ready === false) return undefined;@@ -25,7 +27,8 @@ export const useAskUserLabels = (overrides: {skip: overrides.skip ?? t('askUserQuestion.skip'),submit: overrides.submit ?? t('askUserQuestion.submit'),supplementEnter: t('askUserQuestion.supplement.enter'),- supplementPlaceholder: t('askUserQuestion.supplement.placeholder'),+ supplementPlaceholder:+ overrides.supplementPlaceholder ?? t('askUserQuestion.supplement.placeholder'),timeExpired: '',timeExpiredNoAnswer: '',timeRemaining: () => '',diff --git a/src/features/Conversation/Markdown/plugins/GoalTurn/parseGoalTurn.test.ts b/src/features/Conversation/Markdown/plugins/GoalTurn/parseGoalTurn.test.tsindex abc42f7f3e5..0a467d4196b 100644--- a/src/features/Conversation/Markdown/plugins/GoalTurn/parseGoalTurn.test.ts+++ b/src/features/Conversation/Markdown/plugins/GoalTurn/parseGoalTurn.test.ts@@ -1,4 +1,4 @@-import { buildGoalManagerPrompt } from '@lobechat/prompts';+import { buildGoalManagerPrompt, GOAL_MANAGER_PROMPT_VERSION } from '@lobechat/prompts';import remarkParse from 'remark-parse';import { unified } from 'unified';import { describe, expect, it } from 'vitest';@@ -56,7 +56,7 @@ describe('goalTurn block', () => {maxTurns: '12',trigger: 'settled',turn: '3',- version: 'v7',+ version: GOAL_MANAGER_PROMPT_VERSION,});const parsed = parseGoalTurn(found[0].data.hChildren[0].value);diff --git a/src/features/DailyBrief/BriefActionLink.tsx b/src/features/DailyBrief/BriefActionLink.tsxindex 91becbcebce..ea689528edf 100644--- a/src/features/DailyBrief/BriefActionLink.tsx+++ b/src/features/DailyBrief/BriefActionLink.tsx@@ -3,6 +3,8 @@import { isDesktop } from '@lobechat/const';import { RENDERER_HANDLED_LINK_ATTR } from '@lobechat/desktop-bridge';import { Button } from '@lobehub/ui/base-ui';+import { cssVar } from 'antd-style';+import type { LucideIcon } from 'lucide-react';import type { MouseEvent, ReactNode } from 'react';import { memo, useCallback } from 'react';@@ -18,10 +20,17 @@ interface BriefActionLinkProps {agentId?: string | null;children: ReactNode;className?: string;+ /** Leading glyph, for the quiet navigation variant. */+ icon?: LucideIcon;/** Renders the filled primary variant used for a card's leading action. */primary?: boolean;taskId?: string | null;url?: string;+ /**+ * `quiet`: a small secondary text button, the same as the card's "View run"+ * shortcut — for a link that navigates beside the answers rather than being one.+ */+ variant?: 'quiet';}/**@@ -40,7 +49,7 @@ interface BriefActionLinkProps {* click is already claimed.*/export const BriefActionLink = memo<BriefActionLinkProps>(- ({ agentId, children, className, primary, taskId, url }) => {+ ({ agentId, children, className, icon, primary, taskId, url, variant }) => {const navigate = useWorkspaceAwareNavigate();const workspaces = useWorkspaces();const openAcceptance = useChatStore((s) => s.openAcceptance);@@ -97,6 +106,22 @@ export const BriefActionLink = memo<BriefActionLinkProps>(],);+ if (variant === 'quiet')+ return (+ <Button+ {...(isRendererHandled ? { [RENDERER_HANDLED_LINK_ATTR]: 'true' } : {})}+ className={className}+ href={url}+ icon={icon}+ size={'small'}+ style={{ color: cssVar.colorTextSecondary }}+ type={'text'}+ onClick={handleClick}+ >+ {children}+ </Button>+ );+return (<Button{...(isRendererHandled ? { [RENDERER_HANDLED_LINK_ATTR]: 'true' } : {})}diff --git a/src/features/DailyBrief/BriefCardActions.tsx b/src/features/DailyBrief/BriefCardActions.tsxindex 944543ce793..39f0e035331 100644--- a/src/features/DailyBrief/BriefCardActions.tsx+++ b/src/features/DailyBrief/BriefCardActions.tsx@@ -2,7 +2,7 @@ import { type BriefAction, DEFAULT_BRIEF_ACTIONS, type TaskStatus } from '@lobecimport { Flexbox, Icon, Tooltip } from '@lobehub/ui';import { Button, Text, toast } from '@lobehub/ui/base-ui';import { cssVar } from 'antd-style';-import { Check, SquarePen, Workflow } from 'lucide-react';+import { Check, SquarePen, Target, Workflow } from 'lucide-react';import { lazy, memo, Suspense, useCallback, useState } from 'react';import { useTranslation } from 'react-i18next';import { shallow } from 'zustand/shallow';@@ -26,10 +26,18 @@ export interface BriefCardActionsProps {agentId?: string | null;briefId: string;briefType: string;+ /**+ * The brief's labels are already written in the reader's language for this+ * brief (a goal gate's own answers), so they are shown as given instead of+ * the generic copy for the same action key.+ */+ labelsLocalized?: boolean;/** Hook invoked after a comment is successfully posted. */onAfterAddComment?: () => void | Promise<void>;/** Hook invoked after the brief is successfully resolved. */onAfterResolve?: () => void | Promise<void>;+ /** The advised answer, drawn filled among the brief's text buttons. */+ recommendedActionKey?: string;resolvedAction?: string | null;taskId?: string | null;/** Parent task's runtime status — `scheduled` flips the result action to a plain "Confirm" since approving must NOT terminate a task parked between automated runs. */@@ -55,7 +63,9 @@ const BriefCardActions = memo<BriefCardActionsProps>(agentId,briefId,briefType,+ labelsLocalized,onAfterAddComment,+ recommendedActionKey,onAfterResolve,resolvedAction,taskId,@@ -133,13 +143,31 @@ const BriefCardActions = memo<BriefCardActionsProps>(const getActionLabel = useCallback((action: BriefAction) => {if (isResult && action.key === 'approve') return t(resultLabelKey);+ if (labelsLocalized && action.label) return action.label;const i18nKey = `brief.action.${action.key}`;const translated = t(i18nKey, { defaultValue: '' });return !translated || translated === i18nKey ? action.label : translated;},- [isResult, resultLabelKey, t],+ [isResult, labelsLocalized, resultLabelKey, t],);+ /**+ * A goal brief's answers are quiet text buttons, the advised one a filled+ * button — marked without a primary's weight; other briefs keep their+ * round outlined buttons.+ */+ const answerButtonProps = (key: string) =>+ labelsLocalized+ ? key === recommendedActionKey+ ? { className: undefined, shape: 'round' as const, type: 'fill' as const }+ : {+ className: undefined,+ shape: undefined,+ style: { color: cssVar.colorTextSecondary },+ type: 'text' as const,+ }+ : { shape: 'round' as const, type: 'default' as const };+/*** Run a brief mutation and report a rejection to the user, returning whether* it landed.@@ -250,12 +278,21 @@ const BriefCardActions = memo<BriefCardActionsProps>(}const commentActions = actions.find((a) => a.type === 'comment');- const primaryActions = actions.find((a) => a.type !== 'comment');+ const primaryActions = actions.find(+ (a) => a.type !== 'comment' && !(labelsLocalized && a.type === 'link'),+ );+ // A brief that writes its own answers keeps its navigation link apart from+ // them, at the leading edge in the same quiet form as "View run", so "open+ // the goal" sits in one place across every goal brief instead of wherever+ // it fell among the answers.+ const leadingLinks = labelsLocalized ? actions.filter((a) => a.type === 'link') : [];const otherActions = actions- .filter((a) => a.type !== 'comment')+ .filter((a) => a.type !== 'comment' && !leadingLinks.includes(a)).slice(1).reverse();- const showEditButton = !!taskId && (isResult || !!commentActions);+ // A comment action off a task (a goal's "request changes") still needs its+ // input box; on a task the same button doubles as free-form feedback.+ const showEditButton = !!commentActions || (!!taskId && isResult);const editTooltip = isResult? t('brief.editResult'): commentActions@@ -264,20 +301,55 @@ const BriefCardActions = memo<BriefCardActionsProps>(return (<Flexbox horizontal align={'center'} gap={8} justify={'space-between'} wrap={'wrap'}>- {viewRunButton ?? <span />}+ {viewRunButton ??+ (leadingLinks.length > 0 ? (+ <Flexbox horizontal align={'center'} gap={4}>+ {leadingLinks.map((action) => (+ <BriefActionLink+ agentId={agentId}+ icon={Target}+ key={action.key}+ taskId={taskId}+ url={action.url}+ variant={'quiet'}+ >+ {getActionLabel(action)}+ </BriefActionLink>+ ))}+ </Flexbox>+ ) : (+ <span />+ ))}<Flexbox horizontal align={'center'} gap={8}>- {showEditButton && (- <Tooltip title={editTooltip}>- <Button- className={'brief-comment-btn'}- icon={SquarePen}- shape={'round'}- style={{- color: cssVar.colorTextSecondary,- }}- onClick={() => setCommentMode({ type: 'feedback' })}- />- </Tooltip>+ {labelsLocalized && commentActions ? (+ // A brief that names its own answers ("Request changes") says so+ // in words: an icon alone hid the only way to send a goal back.+ <Button+ {...answerButtonProps(commentActions.key)}+ onClick={() => setCommentMode({ key: commentActions.key, type: 'comment' })}+ >+ {getActionLabel(commentActions)}+ </Button>+ ) : (+ showEditButton && (+ <Tooltip title={editTooltip}>+ <Button+ className={'brief-comment-btn'}+ icon={SquarePen}+ shape={'round'}+ style={{+ color: cssVar.colorTextSecondary,+ }}+ onClick={() =>+ setCommentMode(+ !taskId && commentActions+ ? { key: commentActions.key, type: 'comment' }+ : { type: 'feedback' },+ )+ }+ />+ </Tooltip>+ ))}{otherActions.map((action) => {if (action.type === 'link') {@@ -299,7 +371,7 @@ const BriefCardActions = memo<BriefCardActionsProps>(className={styles.actionBtn}disabled={loadingKey === action.key}key={action.key}- shape={'round'}+ {...answerButtonProps(action.key)}onClick={() => handleResolve(action.key)}>{getActionLabel(action)}@@ -334,7 +406,7 @@ const BriefCardActions = memo<BriefCardActionsProps>(<ButtonclassName={styles.actionBtnPrimary}disabled={loadingKey === primaryActions.key}- shape={'round'}+ {...answerButtonProps(primaryActions.key)}onClick={() => handleResolve(primaryActions.key)}>{getActionLabel(primaryActions)}diff --git a/src/features/GlobalApprovalNotification/GoalDecisionCard.tsx b/src/features/GlobalApprovalNotification/GoalDecisionCard.tsxnew file mode 100644index 00000000000..7b9ec422c9a--- /dev/null+++ b/src/features/GlobalApprovalNotification/GoalDecisionCard.tsx@@ -0,0 +1,185 @@+'use client';++import { ActionIcon, toast } from '@lobehub/ui/base-ui';+import { ArrowUpRight, ChevronUp } from 'lucide-react';+import { useCallback, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import GoalDecisionCase, {+ GoalDecisionAsker,+ type GoalGateCategory,+ goalGateCategory,+ useGateSummary,+} from '@/features/AgentGoals/GoalDecision';+import ClarificationQuestions, {+ type ClarificationAnswer,+} from '@/features/ClarificationQuestions';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { mutate } from '@/libs/swr';+import { goalKeys } from '@/libs/swr/keys';+import { verifyService } from '@/services/verify';+import { useGoalStore } from '@/store/goal';++import { styles } from './styles';+import type { IslandGoalItem } from './usePendingGoalDecisions';++interface GoalDecisionCardProps {+ item: IslandGoalItem;+ onCollapse?: () => void;+}++const SIGN_OFF = { accept: 'signOff', requestChanges: 'requestChanges' } as const;++/**+ * A goal gate or a goal sign-off in the island: the same question the goal+ * page asks, answerable from wherever the user is. The goal's own title leads,+ * the way a run approval leads with its agent — several goals can be waiting.+ */+const GoalDecisionCard = ({ item, onCollapse }: GoalDecisionCardProps) => {+ const { t } = useTranslation('chat');+ const navigate = useWorkspaceAwareNavigate();+ const decideGoal = useGoalStore((s) => s.decideGoal);+ const gateSummary = useGateSummary();+ const [actionsPortalTarget, setActionsPortalTarget] = useState<HTMLDivElement | null>(null);++ const goal =+ item.type === 'decision'+ ? { agentId: item.decision.agentId, id: item.decision.goalId, title: item.decision.goalTitle }+ : { agentId: item.signOff.agentId, id: item.signOff.goalId, title: item.signOff.goalTitle };++ const category =+ item.type === 'decision'+ ? (goalGateCategory({+ nodeTitle: item.decision.nodeTitle,+ options: item.decision.options,+ }) as Exclude<GoalGateCategory, 'clarify'>)+ : undefined;++ const openGoal = () =>+ navigate(goal.agentId ? `/agent/${goal.agentId}/goal/${goal.id}` : `/goal/${goal.id}`);++ const signOffQuestions = useMemo(+ () => [+ {+ description: t('goalProcess.signOff.description'),+ header: '',+ id: 'signOff',+ options: [+ {+ description: t('goalProcess.signOff.acceptEffect'),+ id: SIGN_OFF.accept,+ label: t('goalProcess.signOff.accept'),+ recommended: true,+ },+ {+ description: t('goalProcess.signOff.requestChangesEffect'),+ id: SIGN_OFF.requestChanges,+ label: t('goalProcess.signOff.requestChanges'),+ },+ ],+ question: t('goalProcess.signOff.question'),+ },+ ],+ [t],+ );++ const signOff = useCallback(+ async (answers: ClarificationAnswer[]) => {+ if (item.type !== 'signOff') return;+ const [answer] = answers;+ if (!answer) return;+ // Words with no pick are a change request: that is the only answer that+ // needs them.+ const accept = answer.type === 'option' && answer.optionId === SIGN_OFF.accept;+ const comment = (answer.type === 'option' ? answer.note : answer.text)?.trim() || undefined;+ if (accept) await verifyService.acceptDelivery(item.signOff.acceptanceId, comment);+ else+ await verifyService.rejectDelivery(item.signOff.acceptanceId, comment, { dispatch: true });+ toast.success({+ placement: 'top',+ title: accept ? t('goalProcess.signOff.accepted') : t('goalProcess.signOff.sentBack'),+ });+ // The inbox carries the same sign-off; it is settled on the server with+ // the acceptance, so re-read it there too.+ await Promise.all([+ mutate(goalKeys.pendingForIsland()),+ mutate((key) => Array.isArray(key) && key[0] === 'brief:list'),+ ]);+ },+ [item, t],+ );++ return (+ <div data-pending-hotkey-scope className={styles.card}>+ {/* The goal's agent asks, the way a run approval leads with the agent+ whose run is waiting; a machine gate is asked by the system. */}+ <div className={styles.header}>+ <div className={styles.headerMeta}>+ <GoalDecisionAsker+ agentId={goal.agentId}+ category={category ?? 'judgment'}+ subtitle={item.type === 'signOff' ? t('goalProcess.signOff.islandSubtitle') : undefined}+ />+ </div>+ <ActionIcon+ icon={ArrowUpRight}+ size="small"+ title={t('goalProcess.clarify.openGoal')}+ onClick={openGoal}+ />+ {onCollapse && (+ <ActionIcon+ icon={ChevronUp}+ size="small"+ title={t('globalApproval.collapse')}+ onClick={onCollapse}+ />+ )}+ </div>++ <div className={styles.requestContext}>+ <div className={styles.headerTitle}>{goal.title}</div>+ </div>++ <div className={styles.content}>+ {item.type === 'decision' ? (+ <GoalDecisionCase+ hideAsker+ actionsPortalTarget={actionsPortalTarget}+ basis={item.decision.description}+ category={category!}+ summary={gateSummary(category!, item.decision.sourceTitle)}+ task={item.decision.sourceTitle ? { title: item.decision.sourceTitle } : undefined}+ decision={{+ id: item.decision.decisionId,+ options: item.decision.options,+ question: item.decision.question,+ recommendedOptionId: item.decision.recommendedOptionId,+ }}+ onDecide={(optionId, resolution) =>+ decideGoal(item.decision.goalId, {+ decisionId: item.decision.decisionId,+ optionId,+ resolution,+ })+ }+ />+ ) : (+ <ClarificationQuestions+ actionsPortalTarget={actionsPortalTarget}+ draftKey={`goal-sign-off:${item.signOff.acceptanceId}`}+ key={item.signOff.acceptanceId}+ questions={signOffQuestions}+ submitLabel={t('goalProcess.decision.submit')}+ supplementPlaceholder={t('goalProcess.signOff.notePlaceholder')}+ onSubmit={signOff}+ />+ )}+ </div>++ <div className={styles.actions} ref={setActionsPortalTarget} />+ </div>+ );+};++export default GoalDecisionCard;diff --git a/src/features/GlobalApprovalNotification/index.tsx b/src/features/GlobalApprovalNotification/index.tsxindex 1e88bc6a917..8cc50df25bf 100644--- a/src/features/GlobalApprovalNotification/index.tsx+++ b/src/features/GlobalApprovalNotification/index.tsx@@ -10,10 +10,12 @@ import { isDesktop } from '@/const/version';import ApprovalCard from './ApprovalCard';import GoalClarificationCard from './GoalClarificationCard';+import GoalDecisionCard from './GoalDecisionCard';import { styles } from './styles';import { useApprovalIslandCollapse } from './useApprovalIslandCollapse';import { useGlobalPendingApprovals } from './useGlobalPendingApprovals';import { usePendingGoalClarifications } from './usePendingGoalClarifications';+import { usePendingGoalDecisions } from './usePendingGoalDecisions';const SPRING = { damping: 30, stiffness: 320, type: 'spring' } as const;@@ -34,7 +36,10 @@ const GlobalApprovalNotification = memo(() => {// A goal waiting on its clarification round asks through the same island.// Run approvals go first: a run is blocked mid-turn, a goal has not started.const goalGroups = usePendingGoalClarifications();- const total = groups.length + goalGroups.length;+ // Then the gates a running goal stopped on, then finished goals awaiting+ // sign-off — each blocks less than the one before it.+ const goalItems = usePendingGoalDecisions();+ const total = groups.length + goalGroups.length + goalItems.length;const [collapsed, setCollapsed] = useApprovalIslandCollapse(total);const hasApprovals = total > 0;@@ -44,6 +49,7 @@ const GlobalApprovalNotification = memo(() => {// approvals queue behind a count and surface as each one resolves.const top = groups[0];const topGoal = top ? undefined : goalGroups[0];+ const topGoalItem = top || topGoal ? undefined : goalItems[0];const extraCount = total - 1;return (@@ -101,6 +107,19 @@ const GlobalApprovalNotification = memo(() => {<GoalClarificationCard group={topGoal} onCollapse={() => setCollapsed(true)} /></m.div>)}+ {topGoalItem && (+ <m.div+ layout+ animate={{ opacity: 1, scale: 1, y: 0 }}+ exit={{ opacity: 0, scale: 0.96, y: -16 }}+ initial={{ opacity: 0, scale: 0.96, y: -16 }}+ key={topGoalItem.key}+ style={{ pointerEvents: 'auto', width: '100%' }}+ transition={SPRING}+ >+ <GoalDecisionCard item={topGoalItem} onCollapse={() => setCollapsed(true)} />+ </m.div>+ )}</AnimatePresence>{extraCount > 0 && (<div className={styles.moreHint}>diff --git a/src/features/GlobalApprovalNotification/usePendingGoalDecisions.test.ts b/src/features/GlobalApprovalNotification/usePendingGoalDecisions.test.tsnew file mode 100644index 00000000000..2c58b52acc6--- /dev/null+++ b/src/features/GlobalApprovalNotification/usePendingGoalDecisions.test.ts@@ -0,0 +1,49 @@+import { describe, expect, it } from 'vitest';++import { selectIslandGoalItems } from './usePendingGoalDecisions';++const decision = (goalId: string, decisionId: string) => ({+ agentId: null,+ decisionId,+ description: null,+ goalId,+ goalTitle: goalId,+ nodeTitle: 'Choose how to recover failed task',+ options: [],+ question: 'Retry?',+ recommendedOptionId: 'retry',+ sourceTitle: null,+});+const signOff = (goalId: string) => ({+ acceptanceId: `acc-${goalId}`,+ agentId: null,+ briefId: `brief-${goalId}`,+ goalId,+ goalTitle: goalId,+});++describe('selectIslandGoalItems', () => {+ const data = {+ decisions: [decision('g1', 'd1'), decision('g2', 'd2')],+ signOffs: [signOff('g3')],+ };++ it('asks gates before sign-offs', () => {+ expect(+ selectIslandGoalItems(data, { canAnswer: true, onGoalPage: false }).map((i) => i.key),+ ).toEqual(['goal-decision:d1', 'goal-decision:d2', 'goal-sign-off:acc-g3']);+ });++ it('stays out of a goal page and skips the goal open beside the conversation', () => {+ expect(selectIslandGoalItems(data, { canAnswer: true, onGoalPage: true })).toEqual([]);+ expect(+ selectIslandGoalItems(data, { canAnswer: true, onGoalPage: false, portalGoalId: 'g1' }).map(+ (i) => i.key,+ ),+ ).toEqual(['goal-decision:d2', 'goal-sign-off:acc-g3']);+ });++ it('asks nothing of someone who cannot answer', () => {+ expect(selectIslandGoalItems(data, { canAnswer: false, onGoalPage: false })).toEqual([]);+ });+});diff --git a/src/features/GlobalApprovalNotification/usePendingGoalDecisions.ts b/src/features/GlobalApprovalNotification/usePendingGoalDecisions.tsnew file mode 100644index 00000000000..6b3f2fe5ab8--- /dev/null+++ b/src/features/GlobalApprovalNotification/usePendingGoalDecisions.ts@@ -0,0 +1,91 @@+import type { GoalDecisionOption } from '@lobechat/types';+import { useMemo } from 'react';+import { useLocation } from 'react-router';++import { usePermission } from '@/hooks/usePermission';+import { useChatStore } from '@/store/chat';+import { chatPortalSelectors } from '@/store/chat/selectors';+import { useGoalStore } from '@/store/goal';+import { useUserStore } from '@/store/user';+import { labPreferSelectors } from '@/store/user/selectors';++import { goalIdFromPath } from './usePendingGoalClarifications';++export interface IslandGoalDecision {+ agentId: string | null;+ decisionId: string;+ description: string | null;+ goalId: string;+ goalTitle: string;+ nodeTitle: string;+ options: GoalDecisionOption[];+ question: string;+ recommendedOptionId: string | null;+ sourceTitle: string | null;+}++export interface IslandGoalSignOff {+ acceptanceId: string;+ agentId: string | null;+ briefId: string;+ goalId: string;+ goalTitle: string;+}++export type IslandGoalItem =+ | { decision: IslandGoalDecision; key: string; type: 'decision' }+ | { key: string; signOff: IslandGoalSignOff; type: 'signOff' };++/**+ * What the island should ask, given where the user is — the same rule as the+ * clarification rounds: a goal page asks its own gates in place, so the island+ * stays out of it; beside a conversation only the goal open in the portal is+ * skipped. Gates go before sign-offs: a gate holds work up, a sign-off closes+ * work already done.+ */+export const selectIslandGoalItems = (+ data: { decisions: IslandGoalDecision[]; signOffs: IslandGoalSignOff[] } | undefined,+ {+ canAnswer,+ onGoalPage,+ portalGoalId,+ }: { canAnswer: boolean; onGoalPage: boolean; portalGoalId?: string },+): IslandGoalItem[] => {+ if (!data || !canAnswer || onGoalPage) return [];+ return [+ ...data.decisions+ .filter((decision) => decision.goalId !== portalGoalId)+ .map((decision) => ({+ decision,+ key: `goal-decision:${decision.decisionId}`,+ type: 'decision' as const,+ })),+ ...data.signOffs+ .filter((signOff) => signOff.goalId !== portalGoalId)+ .map((signOff) => ({+ key: `goal-sign-off:${signOff.acceptanceId}`,+ signOff,+ type: 'signOff' as const,+ })),+ ];+};++/** Goal gates and sign-offs the island should ask, oldest first. */+export const usePendingGoalDecisions = (): IslandGoalItem[] => {+ const enabled = useUserStore(labPreferSelectors.enableGoals);+ const { allowed: canAnswer } = usePermission('create_content');+ const useFetchPendingForIsland = useGoalStore((s) => s.useFetchPendingForIsland);+ const { data } = useFetchPendingForIsland(enabled && canAnswer);+ const { pathname } = useLocation();+ const portalGoalId = useChatStore(chatPortalSelectors.goalPortalId);++ return useMemo(+ () =>+ selectIslandGoalItems(data, {+ canAnswer,+ onGoalPage: goalIdFromPath(pathname) !== undefined,+ portalGoalId,+ }),+ [canAnswer, data, pathname, portalGoalId],+ );+};diff --git a/src/features/HomeInbox/InboxBriefCard.tsx b/src/features/HomeInbox/InboxBriefCard.tsxindex bbe1bec4af3..0599a40e0af 100644--- a/src/features/HomeInbox/InboxBriefCard.tsx+++ b/src/features/HomeInbox/InboxBriefCard.tsx@@ -1,8 +1,9 @@import { DEFAULT_AVATAR, INBOX_SESSION_ID } from '@lobechat/const';import { agentDisplayName } from '@lobechat/types';-import { Block, Flexbox } from '@lobehub/ui';+import { Block, Flexbox, Icon } from '@lobehub/ui';import { Avatar, Text } from '@lobehub/ui/base-ui';import { createStaticStyles, cssVar, cx } from 'antd-style';+import { Target } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';@@ -60,6 +61,15 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {const isError = brief.type === 'error';const hasTaskMeta = Boolean(brief.taskStatus || brief.taskIdentifier || brief.taskName);+ // A goal brief has no task of its own; the goal it speaks for takes the+ // meta row, and a click there lands on the goal.+ const goal = brief.metadata?.goal;+ const openGoal = () => {+ if (!goal) return;+ navigate(+ brief.agentId ? `/agent/${brief.agentId}/goal/${goal.goalId}` : `/goal/${goal.goalId}`,+ );+ };const openTask = () => {if (!brief.taskId) return;@@ -71,6 +81,14 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {{/* A brief raised outside a task has no status / ref / name to show, whichleft the meta row as an empty band with a lone timestamp. Drop the rowentirely in that case and let the title line carry the time. */}+ {!hasTaskMeta && goal && (+ <Flexbox horizontal align={'center'} className={styles.meta} gap={7} onClick={openGoal}>+ <Icon color={cssVar.colorTextTertiary} icon={Target} size={14} />+ <span className={cx(homeType.meta, styles.taskName)}>{goal.goalTitle}</span>+ <Flexbox flex={1} />+ <Time date={brief.createdAt} />+ </Flexbox>+ )}{hasTaskMeta && (<Flexboxhorizontal@@ -119,7 +137,7 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {<Text ellipsis className={homeType.itemTitle} style={{ flex: 1, minWidth: 0 }}>{brief.title}</Text>- {!hasTaskMeta && <Time date={brief.createdAt} />}+ {!hasTaskMeta && !goal && <Time date={brief.createdAt} />}</Flexbox><BriefCardSummary summary={brief.summary} /><BriefCardArtifacts artifacts={brief.artifacts} />@@ -131,6 +149,8 @@ const InboxBriefCard = memo<InboxBriefCardProps>(({ bare, brief }) => {agentId={brief.agentId ?? brief.agent?.id}briefId={brief.id}briefType={brief.type}+ labelsLocalized={!!goal}+ recommendedActionKey={goal?.recommendedAction}resolvedAction={brief.resolvedAction}taskId={brief.taskId}taskStatus={brief.taskStatus}diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.tsindex 731a4549b02..857aee2ad24 100644--- a/src/libs/swr/keys.ts+++ b/src/libs/swr/keys.ts@@ -330,6 +330,8 @@ export const goalKeys = {metricSeries: def('goal:metricSeries', (goalId: string) => ['goal:metricSeries', goalId]),/** Clarifications waiting on the user across every goal they own. */pendingClarifications: def('goal:pendingClarifications', () => ['goal:pendingClarifications']),+ /** Gates and sign-offs waiting on the user across every goal, for the approval island. */+ pendingForIsland: def('goal:pendingForIsland', () => ['goal:pendingForIsland']),/** Goals whose planning conversation is this topic (`subject_type = 'topic'`). */topicGoals: def('goal:topicGoals', (topicId: string) => ['goal:topicGoals', topicId]),};diff --git a/src/services/goal.ts b/src/services/goal.tsindex 3a063939672..e80c0306f4a 100644--- a/src/services/goal.ts+++ b/src/services/goal.ts@@ -105,6 +105,12 @@ class GoalService {return data ?? [];};+ /** Gates and sign-offs waiting on the user across their goals, for the approval island. */+ pendingForIsland = async () => {+ const { data } = await lambdaClient.goal.pendingForIsland.query();+ return data ?? { decisions: [], signOffs: [] };+ };+/** End the goal by hand and interrupt its live runs. Reopen with `resume`. */close = async (id: string, status: 'achieved' | 'canceled') =>lambdaClient.goal.close.mutate({ id, status });diff --git a/src/store/brief/slices/list/action.ts b/src/store/brief/slices/list/action.tsindex 6ad1306dbe1..4eed6fb0a6a 100644--- a/src/store/brief/slices/list/action.ts+++ b/src/store/brief/slices/list/action.ts@@ -4,7 +4,7 @@ import { useEffect } from 'react';import { type SWRResponse } from 'swr';import { mutate, useClientDataSWR, useClientDataSWRWithSync } from '@/libs/swr';-import { briefKeys } from '@/libs/swr/keys';+import { briefKeys, goalKeys } from '@/libs/swr/keys';import { getCacheScope } from '@/libs/swr/useCacheScope';import { briefService } from '@/services/brief';import { taskService } from '@/services/task';@@ -102,11 +102,22 @@ export class BriefListActionImpl {};resolveBrief = async (id: string, action?: string, comment?: string) => {+ const goal = this.#get().briefs.find((brief) => brief.id === id)?.metadata?.goal;await briefService.resolve(id, { action, comment });this.internal_updateBrief(id, {resolvedAction: action,resolvedAt: new Date().toISOString(),});+ // A goal brief answered the goal itself: the island and the goal views+ // asking the same question have to drop it too.+ if (goal)+ void mutate(+ (key) =>+ Array.isArray(key) &&+ (key[0] === goalKeys.pendingForIsland()[0] ||+ key[0] === 'task:homeGoals' ||+ (key[0] === 'goal:graph' && key[1] === goal.goalId)),+ );};// Free-form feedback from the brief card: resolve the brief with thediff --git a/src/store/brief/types.ts b/src/store/brief/types.tsindex 22247aa3743..c67fb09f815 100644--- a/src/store/brief/types.ts+++ b/src/store/brief/types.ts@@ -1,6 +1,7 @@import {type BriefAction,type BriefArtifacts,+ type BriefMetadata,type BriefType,type TaskStatus,} from '@lobechat/types';@@ -22,6 +23,8 @@ export interface BriefItem {createdAt: Date | string;cronJobId: string | null;id: string;+ /** Feature-owned payload; a goal brief names its goal here. */+ metadata?: BriefMetadata | null;priority: string | null;readAt: Date | string | null;resolvedAction: string | null;diff --git a/src/store/goal/action.ts b/src/store/goal/action.tsindex f76480cb60a..abf1e6426e1 100644--- a/src/store/goal/action.ts+++ b/src/store/goal/action.ts@@ -160,7 +160,15 @@ export class GoalActionImpl {params: { decisionId: string; optionId: string; resolution?: string },): Promise<void> => {await goalService.decide({ id: goalId, ...params });- await this.refreshGoalGraph(goalId);+ // The same gate is asked by the island, the inbox brief and the home goal+ // rail; answered in one place, every other one stops asking.+ await Promise.all([+ this.refreshGoalGraph(goalId),+ mutate(goalKeys.pendingForIsland()),+ mutate(+ (key) => Array.isArray(key) && (key[0] === 'brief:list' || key[0] === 'task:homeGoals'),+ ),+ ]);};/** Answer a goal's clarification round in one call, then refresh every view of it. */@@ -238,6 +246,17 @@ export class GoalActionImpl {{ refreshInterval: PENDING_CLARIFICATIONS_POLL_INTERVAL, revalidateOnFocus: true },);+ /**+ * Gates and sign-offs waiting on the user across their goals — what the+ * island asks outside the goal page. Same cadence as the clarifications.+ */+ useFetchPendingForIsland = (enabled: boolean) =>+ useClientDataSWR(+ enabled ? goalKeys.pendingForIsland() : null,+ () => goalService.pendingForIsland(),+ { refreshInterval: PENDING_CLARIFICATIONS_POLL_INTERVAL, revalidateOnFocus: true },+ );+/** The Goal Graph snapshot behind the process-control surface. */useFetchGoalGraph = (goalId?: string | null) =>useClientDataSWR(goalId ? goalKeys.graph(goalId) : null, () => goalService.getGraph(goalId!), {