Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion apps/web/client/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,6 @@ async function loadNaturalResearch() {
onRecover: recoverRun,
onKeysChanged: keys => { if (state.session?.account) state.session.account.savedKeys = keys; providerAddress(); },
onSample: () => void openSample(),
onHistory: openHistory,
agentActivity, formalizationActivity,
onLean: () => { chooseEntry('lean'); startDraft(); },
onGuidance: (run, text?: string, taskId?: string) => openGuidance(run, text, undefined, taskId),
Expand Down
10 changes: 1 addition & 9 deletions apps/web/client/chatSession.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { WebConversation, WebConversationMessage, WebConversationRequest, WebConversationSummary } from '../conversationTypes';
import { webFormalizationDefaults, webFormalizationLimits, type WebFormalization, type WebFormalizationCapabilities } from '../formalizationTypes';
import { webFormalizationDefaults, type WebFormalization, type WebFormalizationCapabilities } from '../formalizationTypes';
import type { WebRun, WebSavedKey, WebSession } from '../shared';
import { locale, localizeMessage, t } from '../i18n';
import { researchExamples } from '../problemExamples';
Expand Down Expand Up @@ -61,7 +61,6 @@ type Options = {
onRecover(run: WebRun, action: string, button: HTMLButtonElement): void;
onKeysChanged(keys: WebSavedKey[]): void;
onSample(): void;
onHistory(): void;
/** What the formalization and the Agents of this conversation did; both are owner-only reads, so a sample run has none. */
agentActivity: AgentActivity;
formalizationActivity: FormalizationActivityStore;
Expand Down Expand Up @@ -1099,7 +1098,6 @@ export class ChatSession {
onRename: (id, title) => this.renameConversation(id, title), onDelete: id => this.deleteConversation(id),
records: this.formalization && !this.formalizations.some(item => item.id === this.formalization!.id) ? [...this.formalizations, this.formalization] : this.formalizations,
runs: this.run ? [...(this.options.runs?.() ?? []).filter(run => run.id !== this.run!.id), this.run] : this.options.runs?.(),
recordLimit: this.capabilities?.limits.recordsPerOwner ?? webFormalizationLimits.recordsPerOwner,
onRefreshRecords: () => void this.loadCapabilities(), onDeleteRecord: id => this.deleteRecord(id) });
}
private async renameConversation(id: string, title: string) {
Expand Down Expand Up @@ -1165,11 +1163,6 @@ export class ChatSession {
this.drawHistory();
} catch (error) { if (owner === this.ownerRevision) throw new Error(reason(error)); }
}
private openRecords() {
this.options.onHistory();
const details = this.list.querySelector<HTMLDetailsElement>('#chat-problem-records');
if (details) { details.open = true; details.querySelector<HTMLElement>('summary')?.focus(); details.scrollIntoView({ block: 'nearest' }); }
}
private useExample(id: string) {
const example = researchExamples.find(item => item.id === id);
if (example) { this.keepOriginal(); if (!this.submissionIdentity.unresolved) this.environment = webTaskEnvironment; this.fillOriginal(locale === 'en' ? example.originalEn : example.original); }
Expand Down Expand Up @@ -1297,7 +1290,6 @@ export class ChatSession {
onConfigure: home.onConfigure,
onFirstExample: () => this.useExample('add-zero'),
...(this.options.session()?.sample ? { onSample: this.options.onSample } : {}),
...(this.error === t('形式化记录已满,请先删除不需要的记录。') ? { onManageRecords: () => this.openRecords() } : {}),
onArtifact: (kind, target, auto) => { this.reading.capture(); this.drawOriginal(); this.options.onArtifact(kind, target, auto); },
onOpenLivePlan: () => this.openLivePlan(),
...(this.run && !this.options.isSample(this.run) ? {
Expand Down
10 changes: 4 additions & 6 deletions apps/web/client/ui/ChatWorkspace.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ export type ChatThreadProps = {
startGuide?: { onTemplate(): void; onLean(): void; ready: boolean };
overview?: ResearchOverviewProps;
onSample?(): void;
onManageRecords?(): void;
};

function StatementDecision(props: ChatThreadProps) {
Expand Down Expand Up @@ -332,8 +331,7 @@ function GuidanceReceipt({ message, onGuidanceReceipt, onWithdraw, withdrawing,
function ChatThread(props: ChatThreadProps & { readingArea: HTMLElement }) {
const { conversation, loading, error } = props;
const errorNotice = error && <div id="formalize-error" class="chat-error" role="alert"><p>{error}</p>
{props.onRetry && <button type="button" class="text-button" onClick={props.onRetry}>{t("重试")}</button>}
{props.onManageRecords && <button type="button" class="text-button" data-chat-error-records onClick={props.onManageRecords}>{t('管理题目记录')}</button>}</div>;
{props.onRetry && <button type="button" class="text-button" onClick={props.onRetry}>{t("重试")}</button>}</div>;
if (!conversation && (props.run || props.formalization)) {
const original = props.formalization?.original ?? props.run?.formalization?.original;
return <div class="chat-messages" data-research-conversation={props.run?.id}>
Expand Down Expand Up @@ -723,7 +721,7 @@ export type ChatHistoryProps = {
items: WebConversationSummary[]; selectedId?: string; onOpen(id: string): void; failed?: boolean; onRetry?(): void;
runs?: readonly WebRun[];
onRename(id: string, title: string): Promise<void>; onDelete(id: string): Promise<void>;
records: WebFormalization[]; recordLimit: number; onDeleteRecord(id: string): Promise<void>; onRefreshRecords(): void;
records: WebFormalization[]; onDeleteRecord(id: string): Promise<void>; onRefreshRecords(): void;
};
type HistoryGroup = 'waiting' | 'running' | 'recent';
function ChatHistory(props: ChatHistoryProps) {
Expand Down Expand Up @@ -877,8 +875,8 @@ function ChatHistory(props: ChatHistoryProps) {
: failed ? <p class="chat-history-empty" role="alert">{t("对话列表暂时没有加载出来。")}<button type="button" class="text-button" data-chat-history-retry onClick={onRetry}>{t("重试")}</button></p>
: <p class="chat-history-empty">{t("还没有对话")}</p>}
<details id="chat-problem-records" class="chat-problem-records" onToggle={event => { if (event.currentTarget.open) props.onRefreshRecords(); }}>
<summary>{t('管理题目记录')}<span>{props.records.length} / {props.recordLimit}</span></summary>
<p class="chat-history-empty">{t('记录满后可在这里清理。有研究使用的题目,需要先删除关联研究。')}</p>
<summary>{t('管理题目记录')}<span>{props.records.length}</span></summary>
<p class="chat-history-empty">{t('删除题目之前,请先删除关联的研究。')}</p>
{props.records.map(item => <div class="chat-problem-record" key={item.id} data-chat-record={item.id}>
<a href={`formalize.html?id=${encodeURIComponent(item.id)}`} target="_blank" rel="noreferrer" translate={false}><Rich text={item.original} inline /></a>
<div>{item.runId && <a class="text-button" href={`?run=${encodeURIComponent(item.runId)}`}>{t('查看关联研究')}</a>}
Expand Down
2 changes: 1 addition & 1 deletion apps/web/formalizationTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { LeanStatementContextProtocol } from '../../src/math/leanStatementS
import type { FormalizationAuditResult } from '../../src/math/formalizationAuditProtocol';

export const webFormalizationLimits = Object.freeze({ maxOriginalBytes: 32_768, maxRunSeconds: 1800, maxTotalTokens: 2_000_000,
maxRounds: 3, maxPlanningRounds: 2, reviewers: 2, concurrency: 1, queueLimit: 8, perOwner: 2, recordsPerOwner: 20 });
maxRounds: 3, maxPlanningRounds: 2, reviewers: 2, concurrency: 1, queueLimit: 8, perOwner: 2 });
/** Each 0 means unlimited. Execution time includes planning/revisions and excludes human approval waits. */
export type WebResearchBudget = { maxRunSeconds: number; maxTurns: number; maxTotalTokens: number };
export const webFormalizationDefaults = Object.freeze({ maxRunSeconds: 0, maxTotalTokens: 0,
Expand Down
3 changes: 1 addition & 2 deletions apps/web/formalizations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ export class WebFormalizations {
private auditsRunning = 0;
private closing = false;
constructor(private readonly runner: WebRunner, private readonly storage: WebStorage,
private readonly limits: Pick<typeof webFormalizationLimits, 'concurrency' | 'queueLimit' | 'perOwner' | 'recordsPerOwner'> = webFormalizationLimits,
private readonly limits: Pick<typeof webFormalizationLimits, 'concurrency' | 'queueLimit' | 'perOwner'> = webFormalizationLimits,
private readonly startResearch?: StartResearch, private readonly backgroundResearch?: BackgroundResearch) {
for (const owner of storage.listRecords(['owners'])) for (const id of storage.listRecords(['owners', owner, 'formalizations'])) {
const stored = storage.getRecord<Record>(['owners', owner, 'formalizations', id, 'record.json']);
Expand Down Expand Up @@ -269,7 +269,6 @@ export class WebFormalizations {
if (this.jobs.size >= this.limits.queueLimit) throw new WebStorageError(429, '形式化队列已满,请稍后重试。');
if ([...this.jobs.values()].filter(job => job.record.owner === owner).length >= this.limits.perOwner)
throw new WebStorageError(429, '当前账号的形式化队列已满,请等待已有任务结束。');
if (this.list(owner).length >= this.limits.recordsPerOwner) throw new WebStorageError(429, '形式化记录已满,请先删除不需要的记录。');
const now = new Date().toISOString(), id = crypto.randomUUID();
const formalization: WebFormalization = { id, original: request.original, environment: request.environment, model, providerId: provider.id,
contextProtocol: LEAN_STATEMENT_CONTEXT_PROTOCOL,
Expand Down
1 change: 0 additions & 1 deletion apps/web/i18n/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,6 @@ export const errors: Record<string, string> = {
"形式化运行环境尚未就绪。": "The formalization runtime is not ready.",
"请检查原题、证明环境与 API Key。": "Check the original problem, proof environment and API key.",
"请先取消进行中的形式化任务。": "Cancel the active formalization first.",
"形式化记录已满,请先删除不需要的记录。": "The formalization history is full. Delete records you no longer need first.",
"形式化队列已满,请稍后重试。": "The formalization queue is full. Try again shortly.",
"请先确认原题与 Lean 声明的对应关系。": "Confirm the correspondence between the original problem and the Lean statement first.",
"确认内容已改变,请刷新并重新核对。": "The content to confirm has changed. Refresh and check it again.",
Expand Down
2 changes: 1 addition & 1 deletion apps/web/i18n/release.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ export const release: Record<string, string> = {
'这条指导或它关联的证明任务不存在。': 'This guidance or its proof task no longer exists.',
'撤回未能提交。': 'The withdrawal could not be submitted.',
'一条尚未送达的数学指导已撤回,Agent 不会收到它。': 'Guidance that had not been delivered was withdrawn; no agent will receive it.',
'记录满后可在这里清理。有研究使用的题目,需要先删除关联研究。': 'Clear records here when storage is full. Delete a problem’s linked research before deleting the problem.',
'删除题目之前,请先删除关联的研究。': 'Delete a problem’s linked research before deleting the problem.',
'查看关联研究': 'View linked research',
'删除题目': 'Delete problem',
'替换已保存的 Key': 'Replace saved key',
Expand Down
2 changes: 1 addition & 1 deletion tests/webBackgroundReviewWorkflow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ beforeAll(async () => {
runs: () => [], onOpenRun: noop, connected: () => true,
onSelection: noop, onConversation: noop, onNavigate: noop,
onArtifact: kind => { document.body.dataset.chatArtifact = kind; }, onShare: noop,
onRecover: noop, onKeysChanged: noop, onSample: noop, onHistory: noop, onLean: noop, onGuidance: noop, onCancelRun: noop,
onRecover: noop, onKeysChanged: noop, onSample: noop, onLean: noop, onGuidance: noop, onCancelRun: noop,
planApproval: () => undefined, onApprovePlan: noop, onPlan: noop,
isSample: () => false,
agentActivity: {
Expand Down
26 changes: 24 additions & 2 deletions tests/webLifecyclePersistence.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import type { WebObservation } from '../apps/web/collaboration';
import { readWebConfig } from '../apps/web/config';
import { WebExplanations } from '../apps/web/explanations';
import { WebFormalizations } from '../apps/web/formalizations';
import type { WorkerFormalizationInput, WorkerFormalizationMessage } from '../apps/web/formalizationTypes';
import type { WebFormalization, WorkerFormalizationInput, WorkerFormalizationMessage } from '../apps/web/formalizationTypes';
import { WebJobs } from '../apps/web/jobs';
import type { WebRunner } from '../apps/web/runner';
import { createWebService } from '../apps/web/server';
Expand Down Expand Up @@ -69,7 +69,7 @@ const cleanups: (() => Promise<void>)[] = [];
function setup(kind: Kind, concurrency = 1, dataRoot?: string) {
const root = dataRoot ?? fs.mkdtempSync(path.join(os.tmpdir(), 'web-lifecycle-'));
const storage = new WebStorage(root), runner = new Runner();
const limits = { concurrency, queueLimit: 8, perOwner: 3, recordsPerOwner: 8 };
const limits = { concurrency, queueLimit: 8, perOwner: 3 };
let service: Service;
if (kind === 'research') {
const jobs = new WebJobs(runner, limits, { storage });
Expand Down Expand Up @@ -103,6 +103,28 @@ function setup(kind: Kind, concurrency = 1, dataRoot?: string) {
}
afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); });

it('accepts and preserves a 21st formalization record for the same owner', async () => {
const { storage, runner } = setup('formalization');
const owner = 'alice', original = 'Prove True.', now = new Date().toISOString();
const earlierIds = Array.from({ length: 20 }, () => crypto.randomUUID());
for (const id of earlierIds) {
const formalization: WebFormalization = { id, original, environment: 'standard', model: 'fixture', effort: 'high',
status: 'error', createdAt: now, updatedAt: now };
storage.saveRecord(['owners', mathDigest(owner), 'formalizations', id, 'record.json'], { owner, formalization });
}
const jobs = new WebFormalizations(runner, storage);
try {
const created = jobs.create(owner, { original, environment: 'standard', effort: 'high', apiKey: KEY }, provider, 'fixture');
expect(created.status).toBe('queued');
jobs.cancel(owner, created.id);
const reopened = new WebFormalizations(new Runner(), new WebStorage(storage.root));
expect(new Set(reopened.list(owner).map(record => record.id))).toEqual(new Set([...earlierIds, created.id]));
expect(reopened.list('another-owner')).toEqual([]);
} finally {
await jobs.close();
}
});

describe('research restart with partially written run state', () => {
const restart = (root: string, writeTail?: (storage: WebStorage) => void) => {
// Copy the crash image so cleanup of the simulated old process cannot write into the restored run.
Expand Down
Loading