Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

fix(agent): a run that got nowhere twice stops being offered again

esenginefc628403a384
diff --git a/desktop/electron/agent/host.ts b/desktop/electron/agent/host.ts
index b1ce1f747..c6799f1da 100644
--- a/desktop/electron/agent/host.ts
+++ b/desktop/electron/agent/host.ts
@@ -154,6 +154,9 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
let endpoint = '';
/** Memory handed to the next session this creates — see {@link AgentHost.resume}. */
let resuming: unknown;
+ /** Identical failing calls, counted across the conversation rather than the
+ * turn — see KernelDeps.failing. Emptied with the conversation. */
+ let failing = new Map<string, number>();
/** Sortable and filename-safe. Time first so a directory listing reads
* chronologically even before anything parses it. */
@@ -347,7 +350,7 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
await runTurn(
{
driver: deps.driver, session: session!, model: model ?? '',
- acceptsImages, confirm, emit,
+ acceptsImages, confirm, emit, failing,
standing: deps.standing, journal: deps.journal,
},
text,
@@ -415,6 +418,7 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
// its last turn — it was saved then, and nothing here takes that back.
conversationId = null;
resuming = undefined;
+ failing = new Map();
phase = 'idle';
error = null;
log.length = 0;
@@ -444,6 +448,9 @@ export function createAgentHost(deps: AgentHostDeps): AgentHost {
startedAt = conversation.startedAt;
endpoint = conversation.endpoint;
resuming = conversation.memory;
+ // The count belongs to the run, not to the transcript: a conversation put
+ // back is one nobody has watched fail anything yet.
+ failing = new Map();
phase = 'idle';
error = null;
log.length = 0;
diff --git a/desktop/electron/agent/kernel.ts b/desktop/electron/agent/kernel.ts
index d200eb663..653a08fad 100644
--- a/desktop/electron/agent/kernel.ts
+++ b/desktop/electron/agent/kernel.ts
@@ -255,9 +255,9 @@ export async function runTurn(
let builtSomething = false;
let sawPixels = false;
let askedToLook = false;
- // How often each identical failing call has been re-issued, and the ones
- // that just crossed the line — see REPEAT_LIMIT.
- const failing = new Map<string, number>();
+ // Counted across the CONVERSATION when the host holds the map: a fresh one
+ // per turn hands a stuck model three more attempts every `Carry on`.
+ const failing = deps.failing ?? new Map<string, number>();
const stuck: string[] = [];
const turn: TurnState = { criteria: [], wroteAnything: false };
let toldFailures = false;
diff --git a/desktop/electron/agent/types.ts b/desktop/electron/agent/types.ts
index 87c8d7d77..8ffd60056 100644
--- a/desktop/electron/agent/types.ts
+++ b/desktop/electron/agent/types.ts
@@ -318,6 +318,12 @@ export interface KernelDeps {
* takes effect without reopening the project.
*/
standing?(): readonly Criterion[];
+ /**
+ * How often each identical failing call has been re-issued, ACROSS the
+ * conversation. Held by the host so a `Carry on` does not hand a stuck model
+ * three fresh attempts at the call it has already failed ten times.
+ */
+ failing?: Map<string, number>;
journal?: {
/** Open one around this turn; null when it could not be opened. */
begin(): string | null;
diff --git a/desktop/src/components/AgentDrawer.tsx b/desktop/src/components/AgentDrawer.tsx
index 0ee1e5f99..9023e1208 100644
--- a/desktop/src/components/AgentDrawer.tsx
+++ b/desktop/src/components/AgentDrawer.tsx
@@ -33,7 +33,7 @@ import { useEditorStore } from '@/store/editorStore';
import {
useAgent, agentEffort, sendAgentMessage, stopAgentTurn, confirmAgentCall, startNewConversation,
peekEntities, entitiesInInput, effectiveSelection, selectAgentModel, retryAgentTurn, setAgentDraft,
- RESUMABLE, openAgentHistory, closeAgentHistory, resumeConversation, forgetConversation,
+ RESUMABLE, canCarryOn, openAgentHistory, closeAgentHistory, resumeConversation, forgetConversation,
addAgentAttachments, removeAgentAttachment, latestContext, agentAcceptsImages, resolveProvider,
type AgentTurn, type AgentEntry, type AgentToolEntry, type AgentProseEntry,
} from '@/store/AgentStore';
@@ -730,10 +730,12 @@ function Elapsed({ from, to, className }: { from: number; to: number | null; cla
* finished run in the conversation re-rendered — and re-read the undo stack —
* on every token of the newest one.
*/
-const Turn = memo(function Turn({ turn, isLast, running }: {
+const Turn = memo(function Turn({ turn, isLast, running, carryOn }: {
turn: AgentTurn;
isLast: boolean;
running: boolean;
+ /** Whether continuing is still worth offering — see AgentStore's canCarryOn. */
+ carryOn: boolean;
}) {
// A finished run folds to its header: the stat line already IS the summary, so
// the body becomes detail you ask for rather than detail you scroll past.
@@ -838,13 +840,19 @@ const Turn = memo(function Turn({ turn, isLast, running }: {
stopped: picking a stopped run up from three turns ago would carry
on from a scene that has since moved. */}
{isLast && !running && turn.reason && RESUMABLE.has(turn.reason) && (
- <button
- type="button"
- className="ag-continue"
- onClick={() => void sendAgentMessage(t('agent.continue.message'))}
- >
- <ArrowRight size={13} strokeWidth={2} />{t('agent.continue')}
- </button>
+ carryOn
+ ? (
+ <button
+ type="button"
+ className="ag-continue"
+ onClick={() => void sendAgentMessage(t('agent.continue.message'))}
+ >
+ <ArrowRight size={13} strokeWidth={2} />{t('agent.continue')}
+ </button>
+ )
+ // Withdrawn rather than left there to be pressed again: two runs
+ // that went nowhere are a loop, and the button is what feeds it.
+ : <div className="ag-sys">{t('agent.continue.fruitless')}</div>
)}
{turn.reason !== null && <Verdict turn={turn} />}
{turn.reason !== null && <ChangeSet turn={turn} />}
@@ -1377,6 +1385,7 @@ function Compose({ autoFocus }: { autoFocus?: boolean }) {
export function AgentPanel({ docked }: { docked?: boolean }) {
const setOpen = useEditorStore((s) => s.setAgentDrawer);
const turns = useAgent((s) => s.turns);
+ const carryOn = canCarryOn(turns);
const status = useAgent((s) => s.status);
const queued = useAgent((s) => s.queued);
const historyOpen = useAgent((s) => s.historyOpen);
@@ -1469,6 +1478,7 @@ export function AgentPanel({ docked }: { docked?: boolean }) {
turn={turn}
isLast={i === turns.length - 1}
running={status.phase !== 'idle'}
+ carryOn={carryOn}
/>
))}
{/* Held until the run ends. Shown rather than merely promised: a message
diff --git a/desktop/src/i18n/messages/agent.ts b/desktop/src/i18n/messages/agent.ts
index d638b715d..f8d270b32 100644
--- a/desktop/src/i18n/messages/agent.ts
+++ b/desktop/src/i18n/messages/agent.ts
@@ -140,6 +140,12 @@ export const agentMessages = defineMessages({
zh: '它在干完之前用光了单轮的工具调用次数。已经做完的部分都留着。',
},
'agent.continue': { en: 'Carry on', zh: '接着干' },
+ // The offer is withdrawn rather than left to be pressed again — it is what
+ // feeds the loop, and each press starts a fresh budget.
+ 'agent.continue.fruitless': {
+ en: 'Two runs in a row ended without changing anything. Carrying on would start the same one again — say what to do differently.',
+ zh: '连着两轮都没有改动任何东西。接着干只会再来一遍同样的 —— 换个说法告诉它该怎么做。',
+ },
'agent.continue.message': {
en: 'Carry on from where you stopped.',
zh: '从你停下的地方接着干。',
diff --git a/desktop/src/store/AgentStore.ts b/desktop/src/store/AgentStore.ts
index c48ed0349..38d05fc47 100644
--- a/desktop/src/store/AgentStore.ts
+++ b/desktop/src/store/AgentStore.ts
@@ -117,6 +117,28 @@ export type TurnReason = 'end_turn' | 'aborted' | 'error' | 'refusal' | 'max_rou
*/
export const RESUMABLE: ReadonlySet<TurnReason> = new Set<TurnReason>(['aborted', 'max_rounds', 'error']);
+/** Ended somewhere it could go on from, having changed nothing at all. */
+const fruitless = (turn: AgentTurn): boolean =>
+ turn.reason !== null && RESUMABLE.has(turn.reason)
+ && turn.steps === 0 && turn.files.length === 0;
+
+/** How many fruitless runs in a row before the offer is withdrawn. Two, because
+ * one is a dropped socket and two is a loop. */
+const FRUITLESS_LIMIT = 2;
+
+/**
+ * Whether to offer carrying on from the newest run. The offer exists to
+ * continue WORK, and a run that ended where it could go on while changing
+ * nothing produced none — offering it again is how a long task becomes the same
+ * round trip repeated, each press starting a fresh budget.
+ */
+export function canCarryOn(turns: readonly AgentTurn[]): boolean {
+ const last = turns[turns.length - 1];
+ if (!last?.reason || !RESUMABLE.has(last.reason)) return false;
+ const recent = turns.slice(-FRUITLESS_LIMIT);
+ return recent.length < FRUITLESS_LIMIT || !recent.every(fruitless);
+}
+
export interface AgentTurn {
/** Position in the conversation; stable, so React keys are too. */
id: number;
diff --git a/desktop/tests/agent-kernel.test.ts b/desktop/tests/agent-kernel.test.ts
index 10644fd49..267a9fdcc 100644
--- a/desktop/tests/agent-kernel.test.ts
+++ b/desktop/tests/agent-kernel.test.ts
@@ -898,6 +898,20 @@ describe('a call that keeps failing the same way', () => {
expect(s.context.filter((c) => c.includes('3 times'))).toHaveLength(1);
});
+ // A fresh count per turn hands a stuck model three more attempts every time
+ // the person presses Carry on, which is the loop this is meant to end.
+ it('counts across the conversation when the host holds the count', async () => {
+ const failing = new Map<string, number>();
+ const first = fakeSession([same(), same(), ends()]);
+ await runTurn({ ...deps(first), failing }, 'move it', null, new AbortController().signal);
+ expect(first.context.some((c) => c.includes('3 times'))).toBe(false);
+
+ // The turn after — a Carry on — is where the third attempt lands.
+ const second = fakeSession([same(), ends()]);
+ await runTurn({ ...deps(second), failing }, 'carry on', null, new AbortController().signal);
+ expect(second.context.some((c) => c.includes('set_field') && c.includes('3 times'))).toBe(true);
+ });
+
// Different arguments are a model TRYING something, which is the behaviour
// the nudge exists to provoke — counting them together would punish it.
it('counts each set of arguments on its own', async () => {
diff --git a/desktop/tests/agent-revert-scope.test.ts b/desktop/tests/agent-revert-scope.test.ts
index d9c627468..f169c6f48 100644
--- a/desktop/tests/agent-revert-scope.test.ts
+++ b/desktop/tests/agent-revert-scope.test.ts
@@ -8,7 +8,7 @@
* steps-only checkpoint had nothing to say about.
*/
import { describe, it, expect } from 'vitest';
-import { revertScope, type AgentTurn } from '@/store/AgentStore';
+import { revertScope, canCarryOn, type AgentTurn } from '@/store/AgentStore';
import type { FileChange } from '../electron/agent/types';
const turn = (over: Partial<AgentTurn>): AgentTurn => ({
@@ -65,3 +65,57 @@ describe('what a turn offers to take back', () => {
expect(scope?.stranded.map((f) => f.path)).toEqual(['Video/intro.mp4']);
});
});
+
+/**
+ * When carrying on is still worth offering.
+ *
+ * The offer exists to continue WORK. A run that ended where it could go on but
+ * changed nothing produced none, and offering it again is how a long task turns
+ * into the same round trip repeated — each press starting a fresh budget.
+ */
+describe('whether to offer carrying on', () => {
+ const ran = (over: Partial<AgentTurn>): AgentTurn => turn({ steps: 3, ...over });
+ const nothing = (reason: AgentTurn['reason']): AgentTurn =>
+ turn({ reason, steps: 0, files: [] });
+
+ it('offers it after a run that stopped part-way having done something', () => {
+ expect(canCarryOn([ran({ reason: 'max_rounds' })])).toBe(true);
+ expect(canCarryOn([ran({ reason: 'aborted' })])).toBe(true);
+ expect(canCarryOn([ran({ reason: 'error' })])).toBe(true);
+ });
+
+ it('does not offer it for a run that finished', () => {
+ expect(canCarryOn([ran({ reason: 'end_turn' })])).toBe(false);
+ expect(canCarryOn([ran({ reason: 'refusal' })])).toBe(false);
+ });
+
+ // One fruitless run is a dropped socket; the offer is exactly what it is for.
+ it('still offers it after ONE fruitless run', () => {
+ expect(canCarryOn([nothing('error')])).toBe(true);
+ expect(canCarryOn([ran({ reason: 'end_turn' }), nothing('error')])).toBe(true);
+ });
+
+ // Two is a loop, and the button is what feeds it.
+ it('withdraws it after two fruitless runs in a row', () => {
+ expect(canCarryOn([nothing('error'), nothing('error')])).toBe(false);
+ expect(canCarryOn([nothing('max_rounds'), nothing('aborted')])).toBe(false);
+ });
+
+ it('offers it again once a run got somewhere', () => {
+ expect(canCarryOn([nothing('error'), ran({ reason: 'max_rounds' })])).toBe(true);
+ });
+
+ // Files count as having got somewhere: a turn that only wrote scripts records
+ // no undo steps, and reading steps alone would call it fruitless.
+ it('counts a run that only wrote files as having got somewhere', () => {
+ const wrote = turn({
+ reason: 'max_rounds', steps: 0,
+ files: [{ path: 'src/HP.ts', kind: 'add', unjournaled: false }],
+ });
+ expect(canCarryOn([nothing('error'), wrote])).toBe(true);
+ });
+
+ it('offers nothing when there are no runs at all', () => {
+ expect(canCarryOn([])).toBe(false);
+ });
+});