mirror of
https://github.com/eigent-ai/eigent.git
synced 2026-12-06 06:39:57 +00:00
fix: stop timers for failed legacy histories (#1946)
This commit is contained in:
parent
b94f401102
commit
cd1dce5cf1
8 changed files with 454 additions and 20 deletions
|
|
@ -31,12 +31,11 @@ const STORE_NAME = 'projectCache';
|
|||
const DB_VERSION = 1;
|
||||
|
||||
/**
|
||||
* Bump when CachedProject shape or projection semantics change. Version 9
|
||||
* rejects incomplete task projections (for example hasMessages=true with an
|
||||
* empty messages array) so a disposable cache can never suppress canonical
|
||||
* SQLite replay and leave a Project permanently blank.
|
||||
* Bump when CachedProject shape or projection semantics change. Version 10
|
||||
* rebuilds legacy failures previously cached with zero elapsed time, so they
|
||||
* use persisted playback timestamps even when the history has no END event.
|
||||
*/
|
||||
export const PROJECT_CACHE_SCHEMA_VERSION = 9;
|
||||
export const PROJECT_CACHE_SCHEMA_VERSION = 10;
|
||||
|
||||
export interface CachedTask {
|
||||
/** Anything stored on `chatStore.tasks[taskId]` that's safe to serialize. */
|
||||
|
|
|
|||
|
|
@ -332,13 +332,19 @@ export function reduceProjectedRun(
|
|||
(event.eventType === 'interaction.resolved' ||
|
||||
event.eventType === 'approval.decided') &&
|
||||
event.payload.continued_attempt === true;
|
||||
let lifecycleStatus = RUN_STATUS_BY_EVENT[event.eventType];
|
||||
if (!lifecycleStatus && event.source !== 'canonical') {
|
||||
if (event.legacyStep === 'end') lifecycleStatus = 'completed';
|
||||
// Failed legacy turns emit ERROR and close without an END frame.
|
||||
if (event.legacyStep === 'error') {
|
||||
lifecycleStatus =
|
||||
event.payload.retryable === true ? 'interrupted' : 'failed';
|
||||
}
|
||||
}
|
||||
const candidateStatus =
|
||||
(interactionDecisionContinued
|
||||
? 'running'
|
||||
: RUN_STATUS_BY_EVENT[event.eventType]) ||
|
||||
(event.source !== 'canonical' && event.legacyStep === 'end'
|
||||
? 'completed'
|
||||
: previousRun?.status || 'running');
|
||||
(interactionDecisionContinued ? 'running' : lifecycleStatus) ||
|
||||
previousRun?.status ||
|
||||
'running';
|
||||
const status =
|
||||
previousRun &&
|
||||
((TERMINAL_RUN_STATUSES.has(previousRun.status) &&
|
||||
|
|
@ -350,7 +356,7 @@ export function reduceProjectedRun(
|
|||
: previousRun.runVersion > 0))
|
||||
? previousRun.status
|
||||
: !interactionDecisionContinued &&
|
||||
!RUN_STATUS_BY_EVENT[event.eventType] &&
|
||||
!lifecycleStatus &&
|
||||
previousRun &&
|
||||
previousRun.status !== 'running' &&
|
||||
previousRun.status !== 'interrupted' &&
|
||||
|
|
@ -391,7 +397,10 @@ export function reduceProjectedRun(
|
|||
previousRun &&
|
||||
(event.source === 'canonical'
|
||||
? event.runVersion < previousRun.runVersion
|
||||
: previousRun.runVersion > 0)
|
||||
: previousRun.runVersion > 0 ||
|
||||
// Cleanup receipts cannot extend a settled legacy turn's duration.
|
||||
(status === previousRun.status &&
|
||||
(TERMINAL_RUN_STATUSES.has(status) || status === 'interrupted')))
|
||||
? previousRun.updatedAt
|
||||
: event.createdAt,
|
||||
origin: previousRun?.origin ?? event.origin ?? null,
|
||||
|
|
|
|||
|
|
@ -4863,14 +4863,21 @@ const chatStore = (initial?: Partial<ChatStore>) =>
|
|||
const isRetryableRunError =
|
||||
agentMessages.data?.retryable === true;
|
||||
|
||||
// Freeze the live clock before switching to FINISHED. The work
|
||||
// Freeze the clock before switching to FINISHED. The work
|
||||
// log only advances taskTime while RUNNING; skipping this step
|
||||
// made every error path render "Worked for 0s".
|
||||
const failedTask = tasks[currentTaskId];
|
||||
const settledElapsed = settleTaskElapsedMs(
|
||||
failedTask,
|
||||
Date.now()
|
||||
);
|
||||
const playbackElapsed =
|
||||
(type === 'replay' || type === 'share') &&
|
||||
playbackFirstStepTimeMs !== null &&
|
||||
playbackLastStepTimeMs !== null
|
||||
? Math.max(
|
||||
0,
|
||||
playbackLastStepTimeMs - playbackFirstStepTimeMs
|
||||
)
|
||||
: null;
|
||||
const settledElapsed =
|
||||
playbackElapsed ?? settleTaskElapsedMs(failedTask, Date.now());
|
||||
setTaskTime(currentTaskId, 0);
|
||||
setElapsed(currentTaskId, settledElapsed);
|
||||
get().setDurableRunStatus(currentTaskId, 'failed');
|
||||
|
|
|
|||
|
|
@ -12,13 +12,21 @@
|
|||
// limitations under the License.
|
||||
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
|
||||
|
||||
import { presentChatSemanticEntities } from '@/components/ChatBox/EventTimeline/presentationPolicy';
|
||||
import { TimelineModeRenderer } from '@/components/ChatBox/TimelineModes';
|
||||
import { selectRenderableChatNodes } from '@/lib/projector/chat';
|
||||
import {
|
||||
composeTimelineRuns,
|
||||
reconcileTimelineRun,
|
||||
reconcileTimelineRuns,
|
||||
} from '@/lib/projector/chat/presentation';
|
||||
import type { ChatProjectionNode } from '@/lib/projector/chat/types';
|
||||
import { enqueueChatEventProjection } from '@/store/chatEventProjectionBridge';
|
||||
import { getSessionPreviewSlice, usePageTabStore } from '@/store/pageTabStore';
|
||||
import {
|
||||
getProjectEventStore,
|
||||
releaseProjectEventStore,
|
||||
} from '@/store/projectEventStore';
|
||||
import { SessionMode } from '@/types/constants';
|
||||
import { act, fireEvent, render, screen, within } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
|
|
@ -2113,6 +2121,106 @@ describe('ChatBox timeline modes', () => {
|
|||
expect(screen.getByText('10s')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[false, 'failed', 'Failed after 10m 00s'],
|
||||
[true, 'interrupted', 'Interrupted after 10m 00s'],
|
||||
] as const)(
|
||||
'freezes legacy error history without END (retryable: %s)',
|
||||
(retryable, expectedStatus, summary) => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date('2026-09-15T00:00:00Z'));
|
||||
const projectId = 'legacy-error-history';
|
||||
const runId = 'legacy-error-run';
|
||||
const startedAt = Date.parse('2026-08-18T00:00:00Z') / 1000;
|
||||
releaseProjectEventStore(projectId);
|
||||
const store = getProjectEventStore(projectId, {
|
||||
scheduleFlush: () => () => {},
|
||||
});
|
||||
const history = [
|
||||
{
|
||||
step: 'confirmed',
|
||||
data: { question: 'Build a satellite model' },
|
||||
timestamp: startedAt,
|
||||
},
|
||||
{
|
||||
step: 'ask',
|
||||
data: { question: 'Allow the shell operation?', agent_name: 'Agent' },
|
||||
timestamp: startedAt + 1,
|
||||
},
|
||||
{
|
||||
step: 'activate_toolkit',
|
||||
data: {
|
||||
agent_name: 'Agent',
|
||||
toolkit_name: 'terminal',
|
||||
method_name: 'shell_exec',
|
||||
message: 'Build the model',
|
||||
},
|
||||
timestamp: startedAt + 2,
|
||||
},
|
||||
{
|
||||
step: 'error',
|
||||
data: { message: 'The model build failed.', retryable },
|
||||
timestamp: startedAt + 600,
|
||||
},
|
||||
{
|
||||
step: 'deactivate_agent',
|
||||
data: { agent_name: 'Agent' },
|
||||
timestamp: startedAt + 660,
|
||||
},
|
||||
];
|
||||
|
||||
try {
|
||||
for (const [index, event] of history.entries()) {
|
||||
expect(
|
||||
enqueueChatEventProjection(
|
||||
{
|
||||
raw: { id: 26_870 + index, task_id: runId, ...event },
|
||||
projectId,
|
||||
runId,
|
||||
sequence: index + 1,
|
||||
sourceId: 'cloud-error-playback',
|
||||
transport: 'legacy_chat',
|
||||
historical: true,
|
||||
},
|
||||
true,
|
||||
true
|
||||
)
|
||||
).toBe('accepted');
|
||||
store.flushAll();
|
||||
}
|
||||
const snapshot = store.getSnapshot();
|
||||
const runs = reconcileTimelineRuns(
|
||||
composeTimelineRuns(
|
||||
presentChatSemanticEntities(
|
||||
selectRenderableChatNodes(snapshot.chat)
|
||||
)
|
||||
),
|
||||
snapshot.view.runs
|
||||
);
|
||||
const { container } = render(
|
||||
<TimelineModeRenderer detailLevel="narrative" runs={runs} />
|
||||
);
|
||||
|
||||
expect(runs).toHaveLength(1);
|
||||
expect(runs[0].status).toBe(expectedStatus);
|
||||
expect(runs[0].timestamps.durationMs).toBe(600_000);
|
||||
expect(runs[0].timestamps.elapsedAnchor?.anchoredAt).toBeNull();
|
||||
const trigger = screen.getByRole('button', { name: summary });
|
||||
fireEvent.click(trigger);
|
||||
expect(container.querySelectorAll('.shiny-text')).toHaveLength(0);
|
||||
expect(
|
||||
screen.queryByText(/Working on tasks for/)
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
act(() => vi.advanceTimersByTime(60_000));
|
||||
expect(screen.getByRole('button', { name: summary })).toBe(trigger);
|
||||
expect(container.querySelectorAll('.shiny-text')).toHaveLength(0);
|
||||
} finally {
|
||||
releaseProjectEventStore(projectId);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('renders the completed work-log duration without translation markup', () => {
|
||||
render(
|
||||
<TimelineModeRenderer
|
||||
|
|
|
|||
97
test/unit/lib/projectCache.test.ts
Normal file
97
test/unit/lib/projectCache.test.ts
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
|
||||
import {
|
||||
getCachedProject,
|
||||
putCachedProject,
|
||||
type CachedProject,
|
||||
} from '@/lib/projectCache';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const entries = new Map<string, CachedProject>();
|
||||
const scope = { userId: 'cache-test-user', projectId: 'cache-test-project' };
|
||||
const cacheKey = `${scope.userId}|${scope.projectId}`;
|
||||
|
||||
function successfulRequest<T>(result: T): IDBRequest<T> {
|
||||
const request = { result } as IDBRequest<T>;
|
||||
queueMicrotask(() => request.onsuccess?.call(request, new Event('success')));
|
||||
return request;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
entries.clear();
|
||||
// Exercise the real cache API while keeping all database operations in memory.
|
||||
const store = {
|
||||
get: (key: string) => successfulRequest(entries.get(key)),
|
||||
put: (value: CachedProject, key: string) => {
|
||||
entries.set(key, value);
|
||||
return successfulRequest(key);
|
||||
},
|
||||
delete: (key: string) => {
|
||||
entries.delete(key);
|
||||
return successfulRequest(undefined);
|
||||
},
|
||||
};
|
||||
vi.stubGlobal('indexedDB', {
|
||||
open: () =>
|
||||
successfulRequest({
|
||||
transaction: () => ({ objectStore: () => store }),
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('project cache projection version', () => {
|
||||
const historicalProjection = {
|
||||
serverUpdatedAt: 1_787_011_800_000,
|
||||
localCanonicalUpdatedAt: null,
|
||||
taskIds: ['legacy-failed-run'],
|
||||
tasks: {
|
||||
'legacy-failed-run': {
|
||||
taskState: {
|
||||
status: 'finished',
|
||||
durableRunStatus: 'failed',
|
||||
elapsed: 0,
|
||||
taskTime: 0,
|
||||
messages: [{ role: 'user', content: 'Build a report' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
it('rejects and discards a version 9 legacy failure cached with zero duration', async () => {
|
||||
entries.set(cacheKey, {
|
||||
...historicalProjection,
|
||||
schemaVersion: 9,
|
||||
cachedAt: 1_787_011_800_000,
|
||||
});
|
||||
|
||||
expect(await getCachedProject(scope)).toBeNull();
|
||||
await vi.waitFor(() => expect(entries.has(cacheKey)).toBe(false));
|
||||
});
|
||||
|
||||
it('writes and reads version 10 with the reconstructed historical duration', async () => {
|
||||
const restoredProjection = {
|
||||
...historicalProjection,
|
||||
tasks: {
|
||||
'legacy-failed-run': {
|
||||
taskState: {
|
||||
...historicalProjection.tasks['legacy-failed-run'].taskState,
|
||||
elapsed: 600_000,
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
await putCachedProject(scope, restoredProjection);
|
||||
|
||||
expect(await getCachedProject(scope)).toEqual({
|
||||
...restoredProjection,
|
||||
schemaVersion: 10,
|
||||
cachedAt: expect.any(Number),
|
||||
});
|
||||
expect(entries.has(cacheKey)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
|
@ -90,6 +90,86 @@ function semanticReplayPair(step: 'decompose_text' | 'write_file') {
|
|||
}
|
||||
|
||||
describe('projector pipeline', () => {
|
||||
it.each([
|
||||
[false, 'failed'],
|
||||
[true, 'interrupted'],
|
||||
] as const)(
|
||||
'settles a legacy error without END as %s / %s and ignores cleanup time',
|
||||
(retryable, status) => {
|
||||
const steps = [
|
||||
{ step: 'confirmed', timestamp: '2026-08-18T00:00:00Z', data: {} },
|
||||
{
|
||||
step: 'error',
|
||||
timestamp: '2026-08-18T00:10:00Z',
|
||||
data: { message: 'Turn failed', retryable },
|
||||
},
|
||||
{
|
||||
step: 'deactivate_agent',
|
||||
timestamp: '2026-08-18T00:11:00Z',
|
||||
data: { agent_id: 'agent-1' },
|
||||
},
|
||||
].map((step, index) =>
|
||||
normalizeEvent(
|
||||
{ ...step, id: index + 1, project_id: 'project-1', task_id: 'run-1' },
|
||||
'chat_step_v1'
|
||||
)
|
||||
);
|
||||
const state = steps.reduce(
|
||||
reduceProjectView,
|
||||
createProjectViewState('project-1', 'replay')
|
||||
);
|
||||
expect(state.runs['run-1']).toMatchObject({
|
||||
status,
|
||||
runVersion: 0,
|
||||
lastSequence: 0,
|
||||
updatedAt: '2026-08-18T00:10:00.000Z',
|
||||
});
|
||||
expect(state.legacySteps).toHaveLength(3);
|
||||
if (retryable) {
|
||||
const resumed = reduceProjectView(
|
||||
state,
|
||||
normalizeEvent(
|
||||
event({
|
||||
event_type: 'run.attempt_started',
|
||||
created_at: '2026-08-18T00:12:00Z',
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(resumed.runs['run-1']).toMatchObject({
|
||||
status: 'running',
|
||||
runVersion: 1,
|
||||
lastSequence: 1,
|
||||
updatedAt: '2026-08-18T00:12:00.000Z',
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('keeps canonical lifecycle authority over a legacy error and subtask failure', () => {
|
||||
const running = reduceProjectView(
|
||||
createProjectViewState('project-1', 'replay'),
|
||||
normalizeEvent(event({ event_type: 'run.attempt_started' }))
|
||||
);
|
||||
const legacyError = normalizeEvent(
|
||||
{
|
||||
project_id: 'project-1',
|
||||
task_id: 'run-1',
|
||||
id: 10_000,
|
||||
step: 'error',
|
||||
timestamp: '2026-08-18T00:10:00Z',
|
||||
data: { message: 'Old failure', retryable: false },
|
||||
},
|
||||
'chat_step_v1'
|
||||
);
|
||||
const state = reduceProjectView(running, legacyError);
|
||||
expect(state.runs['run-1']).toEqual(running.runs['run-1']);
|
||||
const subtaskFailure = reduceProjectView(
|
||||
createProjectViewState('project-1', 'replay'),
|
||||
{ ...legacyError, legacyStep: 'failed' }
|
||||
);
|
||||
expect(subtaskFailure.runs['run-1'].status).toBe('running');
|
||||
});
|
||||
|
||||
it.each(['decompose_text', 'write_file'] as const)(
|
||||
'pairs semantic %s mirrors in either arrival order without dropping repeated steps',
|
||||
(step) => {
|
||||
|
|
|
|||
|
|
@ -1538,6 +1538,140 @@ describe('ChatStore - Core Functionality', () => {
|
|||
}
|
||||
});
|
||||
|
||||
it('freezes failed legacy replay at the persisted error time without an end event', async () => {
|
||||
const taskId = 'legacy-failed-history';
|
||||
const startedAt = Date.parse('2026-08-18T00:00:00Z') / 1000;
|
||||
vi.mocked(fetchEventSource).mockImplementation(async (_url, opts) => {
|
||||
for (const [index, event] of [
|
||||
{
|
||||
step: 'confirmed',
|
||||
data: { task_id: taskId, question: 'Build a report' },
|
||||
timestamp: startedAt,
|
||||
},
|
||||
{
|
||||
step: 'error',
|
||||
data: {
|
||||
message:
|
||||
"tool 'shell_exec' may have produced an external side effect",
|
||||
retryable: false,
|
||||
},
|
||||
timestamp: startedAt + 600,
|
||||
},
|
||||
{
|
||||
step: 'deactivate_agent',
|
||||
data: { agent_id: 'single-agent', tokens: 0 },
|
||||
timestamp: startedAt + 610,
|
||||
},
|
||||
].entries()) {
|
||||
await opts.onmessage?.({
|
||||
data: JSON.stringify({
|
||||
id: 26_870 + index,
|
||||
task_id: taskId,
|
||||
...event,
|
||||
}),
|
||||
} as any);
|
||||
}
|
||||
opts.onclose?.();
|
||||
});
|
||||
|
||||
try {
|
||||
const { result } = renderHook(() => useChatStore());
|
||||
await act(async () => {
|
||||
await result.current.getState().replay(taskId, 'Build a report', 0);
|
||||
});
|
||||
expect(result.current.getState().tasks[taskId]).toMatchObject({
|
||||
status: ChatTaskStatus.FINISHED,
|
||||
durableRunStatus: 'failed',
|
||||
elapsed: 600_000,
|
||||
taskTime: 0,
|
||||
});
|
||||
} finally {
|
||||
releaseProjectEventStore('proj-replay');
|
||||
}
|
||||
});
|
||||
|
||||
it.each([undefined, 'normal'] as const)(
|
||||
'settles a live error from its active clock (type=%s)',
|
||||
async (type) => {
|
||||
const taskId = 'live-failed-task';
|
||||
const now = Date.parse('2026-09-16T00:00:00Z');
|
||||
const nowSpy = vi.spyOn(Date, 'now').mockReturnValue(now);
|
||||
const { result } = renderHook(() => useChatStore());
|
||||
vi.mocked(useProjectStore.getState).mockReturnValue({
|
||||
...replayProjectState(),
|
||||
appendInitChatStore: () => {
|
||||
result.current.getState().create(taskId);
|
||||
return { taskId, chatStore: result.current };
|
||||
},
|
||||
getAllChatStores: () => [],
|
||||
getProjectModel: () => null,
|
||||
setProjectModel: vi.fn(),
|
||||
setProjectSpace: vi.fn(),
|
||||
setHistoryId: vi.fn(),
|
||||
getProjectThinkingEffortOverride: () => undefined,
|
||||
} as any);
|
||||
vi.mocked(proxyFetchGet).mockImplementation((url: string) =>
|
||||
Promise.resolve(
|
||||
url.includes('snapshots')
|
||||
? []
|
||||
: {
|
||||
value: 'test-cloud-key',
|
||||
api_url: 'https://models.example.test',
|
||||
items: [],
|
||||
warning_code: null,
|
||||
}
|
||||
)
|
||||
);
|
||||
vi.mocked(fetchEventSource).mockImplementation(async (_url, opts) => {
|
||||
await opts.onmessage?.({
|
||||
data: JSON.stringify({
|
||||
step: 'confirmed',
|
||||
data: { task_id: taskId, question: 'Build a report' },
|
||||
timestamp: 100,
|
||||
}),
|
||||
} as any);
|
||||
result.current.getState().setTaskTime(taskId, now - 5_000);
|
||||
result.current.getState().setElapsed(taskId, 2_000);
|
||||
await opts.onmessage?.({
|
||||
data: JSON.stringify({
|
||||
step: 'error',
|
||||
data: { message: 'Live execution failed', retryable: false },
|
||||
timestamp: 700,
|
||||
}),
|
||||
} as any);
|
||||
opts.onclose?.();
|
||||
});
|
||||
|
||||
try {
|
||||
await act(async () => {
|
||||
await result.current
|
||||
.getState()
|
||||
.startTask(
|
||||
taskId,
|
||||
type,
|
||||
undefined,
|
||||
undefined,
|
||||
'Build a report',
|
||||
[],
|
||||
undefined,
|
||||
'proj-replay'
|
||||
);
|
||||
});
|
||||
await vi.waitFor(() => {
|
||||
expect(result.current.getState().tasks[taskId]).toMatchObject({
|
||||
status: ChatTaskStatus.FINISHED,
|
||||
durableRunStatus: 'failed',
|
||||
elapsed: 7_000,
|
||||
taskTime: 0,
|
||||
});
|
||||
});
|
||||
} finally {
|
||||
nowSpy.mockRestore();
|
||||
releaseProjectEventStore('proj-replay');
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('keeps one narration and file receipt after partial canonical replay falls back to cloud', async () => {
|
||||
vi.stubEnv('VITE_CHATBOX_EVENT_BUS', 'true');
|
||||
releaseProjectEventStore('proj-replay');
|
||||
|
|
|
|||
|
|
@ -96,8 +96,8 @@ function deferred<T>() {
|
|||
}
|
||||
|
||||
describe('projectStore runtime shape', () => {
|
||||
it('uses the cache schema that rejects incomplete message projections', () => {
|
||||
expect(PROJECT_CACHE_SCHEMA_VERSION).toBe(9);
|
||||
it('uses the cache schema that rebuilds stale legacy failure durations', () => {
|
||||
expect(PROJECT_CACHE_SCHEMA_VERSION).toBe(10);
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue