diff --git a/web/src/features/build/console-entry.test.ts b/web/src/features/build/console-entry.test.ts index 2162093..4a6131a 100644 --- a/web/src/features/build/console-entry.test.ts +++ b/web/src/features/build/console-entry.test.ts @@ -4,6 +4,7 @@ // resume the same server session; the wait is bounded and stops typed. import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test' import { createBuildSessionsApi, type BuildSessionsApi } from '../../api/build-sessions' +import { getDraft } from '../../api/build' import { createConsoleMockFetch, resetMocks, type ConsoleMockFetch } from '../../api/testing/console-mock-fetch' import { createTestGateway } from '../../api/testing/gateway' import { readConsoleStart } from './console-session-state' @@ -54,6 +55,21 @@ test('a console-v1 start creates one server session, follows advance to its draf expect(readConsoleStart(storage)).toBeUndefined() }) +test('a console-v1 start sends a byte-bounded opening but keeps the original words for replay', async () => { + const opening = '来客受付'.repeat(400) + const create = spyOn(api, 'create') + restore.push(() => create.mockRestore()) + mock.rewrites.push({ method: 'POST', path: CREATE, once: true, body: (wire) => ({ ...wire, id: 'SENTINEL' }) }) + await expect(startConsoleBuild(opening, 'g-team-a', deps())).rejects.toBeInstanceOf(BuildStartError) + expect(readConsoleStart(storage)?.intent).toBe(opening) + await startConsoleBuild(opening, 'g-team-a', deps()) + expect(create.mock.calls).toHaveLength(2) + const [payload, key] = create.mock.calls[0]! + expect(new TextEncoder().encode(payload.intent).length).toBeLessThanOrEqual(4000) + expect(create.mock.calls[1]).toEqual([payload, key]) + expect(await sessions()).toHaveLength(1) +}) + test('a lost create answer: the next start replays the same key and gets the same session (no second one)', async () => { mock.rewrites.push({ method: 'POST', path: CREATE, once: true, body: (wire) => ({ ...wire, id: 'SENTINEL' }) }) const error = await startConsoleBuild(INTENT, 'g-team-a', deps()).catch((caught: unknown) => caught) @@ -151,6 +167,15 @@ describe('the new-session engine (server flag) at beginBuild', () => { expect(mock.requests.filter((item) => item.path.startsWith('/api/console/v1/'))).toEqual([]) expect((await api.resolve(draft.id)).engine).toBe('platform-v1') }) + test('an oversized original creates one bounded Platform draft and resumes it by its complete words', async () => { + const opening = '在庫管理'.repeat(400) + const options = { groupId: 'g-team-a', ownerSubject: 'sub-yamada' } + const { id } = await beginBuild('commerce', opening, options) + const stored = (await getDraft('commerce', id)).intent + expect(new TextEncoder().encode(stored).length).toBeLessThanOrEqual(4000) + expect((await beginBuild('commerce', opening, options)).id).toBe(id) + expect(mock.count('POST', /\/application-drafts$/)).toBe(1) + }) test('console-v1 creates a console session and does not look up or adopt a legacy draft', async () => { const legacy = await beginBuild('commerce', INTENT, { groupId: 'g-team-a', ownerSubject: 'sub-yamada' }) const started = await beginBuild('commerce', INTENT, { groupId: 'g-team-a', ownerSubject: 'sub-yamada', newSessionEngine: 'console-v1' }) diff --git a/web/src/features/build/entry.ts b/web/src/features/build/entry.ts index 3c7f7dc..3f9e69d 100644 --- a/web/src/features/build/entry.ts +++ b/web/src/features/build/entry.ts @@ -4,6 +4,7 @@ import { buildSessionsApi, intentKeys, isVersionConflict, mintIdempotencyKey, ty import { ConsoleApiError } from '../../api/console' import { boundedRetryAfter, buildPollDelay, ERROR_BACKOFF_MS } from '../../api/queries/build-sessions' import { membershipRoots, type BuildError, type BuildSession, type Group, type Me } from '../../model/contracts/console' +import { boundBuildOpening } from '../../model/build/questions' import { findResumableDraft } from '../../model/build/resume' import { currentLanguage } from '../../shell/language' import { readConsoleStart, saveConsoleStart, type ConsoleStart } from './console-session-state' @@ -35,12 +36,12 @@ export async function beginBuild(projectId: string, intent: string, options: { g if (!options.groupId) throw new Error(text.page.noGroup.body) if (options.newSessionEngine === 'console-v1') return startConsoleBuild(intent, options.groupId) const drafts = await listDrafts(projectId) - const existing = findResumableDraft(drafts.data, intent) + const existing = await findResumableDraft(drafts.data, intent) if (existing) { if (!readBuildSession(existing.id)) saveBuildSession(existing.id, initialSession({ projectId, ownerSubject: options.ownerSubject, groupId: options.groupId, baseIntent: existing.intent })) return existing } - const draft = await createDraft(projectId, { title: titleFromIntent(intent), intent: intent.trim() }) + const draft = await createDraft(projectId, { title: titleFromIntent(intent), intent: await boundBuildOpening(intent.trim()) }) saveBuildSession(draft.id, initialSession({ projectId, ownerSubject: options.ownerSubject, groupId: options.groupId, baseIntent: intent.trim() })) return draft } @@ -100,7 +101,7 @@ export async function startConsoleBuild(intent: string, groupId: string, deps: P saveConsoleStart(start, storage) let session: BuildSession try { - session = start.sessionId ? await api.get(start.sessionId) : await api.create({ kind: 'new-app', groupId, intent: words, locale: start.locale }, start.key) + session = start.sessionId ? await api.get(start.sessionId) : await api.create({ kind: 'new-app', groupId, intent: await boundBuildOpening(words), locale: start.locale }, start.key) } catch (error) { // The create may have happened; the kept key replays it on the next start. Nothing else is sent. if (isResponseContractError(error)) throw new BuildStartError('unconfirmed', start.sessionId ? { sessionId: start.sessionId } : {}) diff --git a/web/src/features/build/use-build-session.test.tsx b/web/src/features/build/use-build-session.test.tsx index 540fc67..62d5ab3 100644 --- a/web/src/features/build/use-build-session.test.tsx +++ b/web/src/features/build/use-build-session.test.tsx @@ -173,6 +173,58 @@ describe('kickoff to plan handoff', () => { expect(generation).toHaveBeenCalledTimes(1) }) + test('an intent PATCH rejection keeps the reply queued with a Platform reference and never starts an AI turn', async () => { + const message = "'intent' must be 4000 characters or fewer" + update.mockRejectedValueOnce(new ORPCError('BAD_REQUEST', { + status: 400, data: { body: { error: { code: 'invalid_argument', message } } }, + })) + await mount({ ...draft, conversationTurns: [turn('opening', buildCopy.questions.firstTurn, 0)] }) + await act(async () => { build.send('一覧を作る') }) + expect(build.failure).toMatchObject({ kind: 'platform', title: buildCopy.failure.platform.title, reference: { draftId: draft.id } }) + expect(build.session.pending.map((item) => item.text)).toEqual(['一覧を作る']) + expect(createTurn).not.toHaveBeenCalled() + }) + + test.each([3954, 4000, 4050])('a fresh tab can send a kickoff and plan from a %i-byte draft with 14 replies', async (storedBytes) => { + const generation = mockGeneration() + const utf8 = new TextEncoder() + const replies = Array.from({ length: 14 }, (_, i) => `${i + 1}: ${'仕入'.repeat(40)}`) + // Legacy wire format, independent of the formatter under test. The 3954-byte case is 1542 characters. + const heading = '\n\n### 追記\n\n' + const opening = '在庫管理' + replies[0] += '数'.repeat(54) + replies[0] += 'x'.repeat(storedBytes - utf8.encode([opening, ...replies].join(heading)).length) + const stored = [opening, ...replies].join(heading) + expect(utf8.encode(stored)).toHaveLength(storedBytes) + if (storedBytes === 3954) expect(stored).toHaveLength(1542) + const turns = replies.map((reply, i) => ({ ...turn(`t-${i}`, reply, 0), startedAt: new Date(Date.parse(at) + i * 1000).toISOString() })) + update.mockImplementation(async (_project, _id, { intent }) => { + if (!intent || utf8.encode(intent).length > 4000) throw new ORPCError('BAD_REQUEST', { + status: 400, data: { body: { error: { code: 'invalid_argument', message: "'intent' must be 4000 characters or fewer" } } }, + }) + return { ...client.getQueryData(queryKey)!, intent } + }) + client.setQueryData(queryKey, draftOf({ ...draft, intent: stored, conversationTurns: turns })) + await render() + + const message = 'この内容で提案して' + await act(async () => { build.send(message) }) + expect(createTurn).toHaveBeenCalledTimes(1) + expect(createTurn).toHaveBeenCalledWith(me.projectId, draft.id, { message }) + const patches = update.mock.calls.map(([, , payload]) => payload.intent) + expect(patches).toHaveLength(2) + for (const intent of patches) { + expect(utf8.encode(intent).length).toBeLessThanOrEqual(4000) + expect(intent).toContain(opening) + expect(intent).toContain(message) + } + expect(patches[0]!.endsWith(message)).toBe(true) + expect(patches[1]!.endsWith('\n\n公開: する')).toBe(true) + expect(build.session.lastPlannedIntent).toBe(patches[1]) + expect(generation).toHaveBeenCalledTimes(1) + expect(client.getQueryData(queryKey)?.conversationTurns.map((item) => item.userMessage)).toEqual([...replies, message]) + }) + test.each(['saved', 'missing', 'invalid'] as const)('reload with %s session recovers succeeded kickoff from the draft', async (storage) => { const generation = mockGeneration() if (storage === 'saved') saveBuildSession(draft.id, initial) @@ -448,7 +500,7 @@ test('a saved implementation can retry before the console app binding loads', as }) test('fresh tabs and legacy sessions show the original opening rather than composed metadata', async () => { - const composed = composeBuildIntent(draft.intent, ['検索する'], true) + const composed = await composeBuildIntent(draft.intent, ['検索する'], true) await mount({ ...draft, intent: composed }, { ...initial, baseIntent: composed }) expect(build.messages[0]).toMatchObject({ role: 'user', text: draft.intent }) }) diff --git a/web/src/features/build/use-build-session.ts b/web/src/features/build/use-build-session.ts index f18d8e7..d6cf4b4 100644 --- a/web/src/features/build/use-build-session.ts +++ b/web/src/features/build/use-build-session.ts @@ -193,11 +193,13 @@ export function useBuildSession(observed: BuildDraft, me: Me, groupId: string, o return } void perform('turn', async () => { - const currentDraft = draftRef.current - const replies = conversationTurns(currentDraft.conversationTurns).map((item) => item.userMessage) - const intent = composeBuildIntent(decomposeBuildIntent(session.baseIntent), [...replies, pending.text]) - // The intent is the plan's input; 用意する answers do not change the plan in use. - if (!asking) await receive(await api.updateDraft(projectId, draft.id, { intent })) + // The persisted opening is shared by fresh and resumed tabs. Preparation answers do not change the plan. + if (!asking) { + const current = draftRef.current + const replies = conversationTurns(current.conversationTurns).map((item) => item.userMessage) + const intent = await composeBuildIntent(current.intent, [...replies, pending.text]) + await receive(await api.updateDraft(projectId, draft.id, { intent })) + } try { const created = await api.createTurn(projectId, draft.id, { message: pending.text }) const latest = draftRef.current @@ -243,7 +245,7 @@ export function useBuildSession(observed: BuildDraft, me: Me, groupId: string, o return } if ([latestGeneration, current.conversationTurns.at(-1)].some(isBuildPending)) return - const intent = composeBuildIntent(decomposeBuildIntent(session.baseIntent), conversationTurns(current.conversationTurns).map((item) => item.userMessage), true) + const intent = await composeBuildIntent(current.intent, conversationTurns(current.conversationTurns).map((item) => item.userMessage), true) const updated = current.intent === intent ? current : await api.updateDraft(projectId, draft.id, { intent }) await receive(updated) const attemptKey = `build-plan-${draft.id}-${current.conversationTurns.at(-1)?.id ?? 'initial'}-${previousGenerationId ?? 'initial'}` diff --git a/web/src/model/build/copy.en.ts b/web/src/model/build/copy.en.ts index 8e7c13d..7206b45 100644 --- a/web/src/model/build/copy.en.ts +++ b/web/src/model/build/copy.en.ts @@ -1,7 +1,7 @@ import type { textJa } from './copy' export const textEn: typeof textJa = { - intent: { reply: '### Follow-up', publish: 'Publish: yes' }, + intent: { reply: '### Follow-up', publish: 'Publish: yes', omitted: (count) => `(${count} earlier follow-up${count === 1 ? '' : 's'} omitted)` }, unreadablePlan: { title: 'The saved plan could not be read', detail: 'This console cannot show the contents of the plan saved on the platform.' }, questions: { firstTurn: 'Ask me one question at a time about the decisions needed to build this app.', diff --git a/web/src/model/build/copy.ts b/web/src/model/build/copy.ts index b499b56..daa12c8 100644 --- a/web/src/model/build/copy.ts +++ b/web/src/model/build/copy.ts @@ -2,7 +2,7 @@ import { localized } from '../../shell/language' import { textEn } from './copy.en' export const textJa = { - intent: { reply: '### 追記', publish: '公開: する' }, + intent: { reply: '### 追記', publish: '公開: する', omitted: (count: number) => `(以前の追記 ${count} 件を省略)` }, unreadablePlan: { title: '保存された計画を読めませんでした', detail: '基盤に保存された計画の内容を、このコンソールでは確認できません。' }, questions: { firstTurn: 'このアプリを作るために決めるべきことを、一つずつ質問してください。', diff --git a/web/src/model/build/failure.test.ts b/web/src/model/build/failure.test.ts index 477323d..5e46413 100644 --- a/web/src/model/build/failure.test.ts +++ b/web/src/model/build/failure.test.ts @@ -31,6 +31,16 @@ test('unrelated invalid requests retain their preparation failure classification expect(classifyBuildFailure('groupId is invalid', 400, 'prepare').kind).toBe('platform') }) +test.each(['turn', 'plan'] as const)('an invalid intent PATCH before a %s is a Platform request rejection', (context) => { + const message = "'intent' must be 4000 characters or fewer" + const reference = { draftId: 'draft-1', at: '2026-11-17T00:00:00Z' } + expect(classifyBuildFailure(message, 400, context, reference, 'invalid_argument')).toEqual({ + kind: 'platform', ...buildCopy.failure.platform, raw: message, reference, + }) + expect(classifyBuildFailure("'message' must be shorter", 400, context, reference, 'invalid_argument').kind).toBe('failed') + expect(classifyBuildFailure(message, undefined, context).kind).toBe('failed') +}) + test('department failure is localized without a platform support reference', () => { setLanguage('en') const failure = classifyBuildFailure('groupId must be one of your directory groups', 400, 'prepare', { draftId: 'draft-1', at: '2026-10-18T11:22:00Z' }, 'invalid_request') diff --git a/web/src/model/build/failure.ts b/web/src/model/build/failure.ts index 989031e..a373ff6 100644 --- a/web/src/model/build/failure.ts +++ b/web/src/model/build/failure.ts @@ -130,6 +130,10 @@ export function classifyBuildFailure(text: string, status: number | undefined, c return { kind: 'interrupted', title: buildCopy.progress.interrupted.title, reason: buildCopy.progress.interrupted.hint, raw: text } } if (/(?:generation|conversation.turn).*(?:limit|maximum|at most|20|50)|(?:limit|maximum|reached (?:20|50)).*(?:generation|conversation.turn)/i.test(text)) return { kind: 'limit', ...copy.limit, raw: text } + // The draft PATCH was rejected before any conversation or plan generation was started. + if ((context === 'turn' || context === 'plan') && status === 400 && code === 'invalid_argument' && /^['"]intent['"]\s/i.test(text)) { + return { kind: 'platform', ...copy.platform, raw: text, ...(reference ? { reference } : {}) } + } // The plan's validation asks no AI: a gateway answer to it is the platform's failure, with its reference (APT-1094). if (operation === 'plan.validate' && (status === 502 || status === 503 || status === 504)) return { kind: 'platform', ...copy.platform, raw: text, ...(reference ? { reference } : {}) } if (status === 412 || status === 502 || status === 503 || status === 504 || /runtime is not available|codex.*(?:unavailable|not available|not configured)|codexAvailable/i.test(text)) return { kind: 'unavailable', ...copy.unavailable, raw: text } diff --git a/web/src/model/build/questions.ts b/web/src/model/build/questions.ts index 52c74df..ee10d4d 100644 --- a/web/src/model/build/questions.ts +++ b/web/src/model/build/questions.ts @@ -44,19 +44,73 @@ export function replyOptions(messages: BuildMessage[]): string[] { return successful >= 3 && !options.some(isKickoffReply) ? [...options, buildCopy.questions.kickoffReply] : options } -/** Conversation replies enter the plan in order; publication keeps its explicit marker. */ -export function composeBuildIntent(base: string, replies: string[], publish?: boolean): string { - const parts = [base.trim()] - for (const reply of replies) if (reply.trim()) parts.push(`${buildCopy.intent.reply}\n\n${reply.trim()}`) - const marker = publish === true ? `\n\n${buildCopy.intent.publish}` : '' - let content = parts.filter(Boolean).join('\n\n').slice(0, 8000 - marker.length) - // Do not leave half a UTF-16 surrogate at the storage boundary. - if (/[\uD800-\uDBFF]$/.test(content)) content = content.slice(0, -1) - return content.trimEnd() + marker -} - -/** Recover the user-authored opening from the console's persisted intent envelope. */ -export function decomposeBuildIntent(intent: string): string { +// Older Platform versions enforce the draft field's 4000-character limit in UTF-8 bytes. +const INTENT_BYTES = 4000 +const utf8 = new TextEncoder() +const bytes = (value: string) => utf8.encode(value).length +const openingStamp = /…\n$/ + +function prefix(value: string, budget: number): string { + // encodeInto stops before the first code point that would not fit. + const { read } = utf8.encodeInto(value, new Uint8Array(budget)) + return value.slice(0, read).trimEnd() +} + +async function openingId(value: string): Promise { + const digest = await crypto.subtle.digest('SHA-256', utf8.encode(value)) + return Array.from(new Uint8Array(digest, 0, 16), (byte) => byte.toString(16).padStart(2, '0')).join('') +} + +/** An abbreviated opening still identifies the original words, not every request with the same prefix. */ +export async function boundBuildOpening(opening: string, budget = INTENT_BYTES): Promise { + if (bytes(opening) <= budget) return opening + const existing = openingStamp.exec(opening) + const stamp = `…\n` + return prefix(existing ? opening.slice(0, existing.index) : opening, budget - bytes(stamp)) + stamp +} + +/** A compact plan input, not the transcript: conversationTurns retains every complete message. */ +export async function composeBuildIntent(intent: string, replies: readonly string[], publish?: boolean): Promise { + let opening = openingEnvelope(intent) + const messages = replies.map((reply) => reply.trim()).filter(Boolean) + // Persisted headings (including legacy English drafts) and the automatic first turn travel with + // the conversation. Switching the display language must not change a plan's input. + const metadata = intent.trim().slice(opening.length).trimStart() + const copy = metadata.startsWith(`${textEn.intent.reply}\n\n`) || metadata === textEn.intent.publish + || (!metadata && messages[0] === textEn.questions.firstTurn) ? textEn.intent : textJa.intent + const heading = `\n\n${copy.reply}\n\n` + const footer = publish ? `\n\n${copy.publish}` : '' + const budget = INTENT_BYTES - bytes(footer) + if (!messages.length) return (await boundBuildOpening(opening, budget)) + footer + const headingBytes = bytes(heading) + const sizes = messages.map((reply) => headingBytes + bytes(reply)) + const latest = messages.length - 1 + const omitted = (count: number) => count ? heading + copy.omitted(count) : '' + const repliesBytes = sizes.reduce((total, size) => total + size, 0) + let first = 0 + if (bytes(opening) + repliesBytes > budget) { + // Reserve the newest follow-up and its omission notice before spending bytes on older replies. + // If even opening + newest cannot fit, a short one stays whole; two large ones share the space. + const olderBytes = repliesBytes - sizes[latest]! + const available = budget - Math.min(olderBytes, bytes(omitted(latest))) - headingBytes + const newest = messages[latest]! + const newestBytes = sizes[latest]! - headingBytes + opening = await boundBuildOpening(opening, Math.max(available - newestBytes, Math.floor(available / 2))) + const openingBytes = bytes(opening) + const room = available - openingBytes + if (newestBytes > room) messages[latest] = prefix(newest, room - bytes('…')) + '…' + let remaining = budget - openingBytes - headingBytes - bytes(messages[latest]!) + // A few short replies may cost less than saying they were omitted. + first = olderBytes <= remaining ? 0 : latest + while (first > 0 && sizes[first - 1]! + bytes(omitted(first - 1)) <= remaining) { + remaining -= sizes[--first]! + } + } + return opening + omitted(first) + heading + messages.slice(first).join(heading) + footer +} + +/** Keep a clipped opening's identity when recomposing a stored draft. */ +function openingEnvelope(intent: string): string { let base = intent.trim() for (const catalog of [textJa, textEn]) { const reply = base.indexOf(`\n\n${catalog.intent.reply}\n\n`) @@ -64,7 +118,20 @@ export function decomposeBuildIntent(intent: string): string { const marker = `\n\n${catalog.intent.publish}` if (base.endsWith(marker)) base = base.slice(0, -marker.length) } - return base + return base.trimEnd() +} + +/** Recover only user-facing text (no replay metadata) for the opening chat message. */ +export function decomposeBuildIntent(intent: string): string { + return openingEnvelope(intent).replace(openingStamp, '…') +} + +export async function sameBuildOpening(intent: string, wanted: string): Promise { + const opening = openingEnvelope(intent) + const stamp = openingStamp.exec(opening) + if (!stamp) return opening === wanted + const excerpt = opening.slice(0, stamp.index) + return wanted.startsWith(excerpt) && await openingId(wanted) === stamp[1] } /** Integrated entities already exclude headers, reports and merged duplicates. */ diff --git a/web/src/model/build/resume.test.ts b/web/src/model/build/resume.test.ts index a0152d7..a20d007 100644 --- a/web/src/model/build/resume.test.ts +++ b/web/src/model/build/resume.test.ts @@ -2,10 +2,11 @@ import { describe, expect, test } from 'bun:test' import type { ApplicationDraft } from '@appthrust/api-schema/platform-api' import { draftOf } from '../../api/testing/build-domain' import * as model from './resume' +import { composeBuildIntent } from './questions' /** The fixture the production reader resumed (fixtures carry distinct ids per call). */ -const findResumableDraft = (drafts: readonly T[], intent: string) => { - const found = model.findResumableDraft(drafts.map(draftOf), intent) +const findResumableDraft = async (drafts: readonly T[], intent: string) => { + const found = await model.findResumableDraft(drafts.map(draftOf), intent) return found && drafts.find((draft) => draft.id === found.id) } import { textJa } from './copy' @@ -18,32 +19,40 @@ const base: ApplicationDraft = { } describe('pressing AI と作る again resumes instead of multiplying', () => { - test('the newest unfinished draft with the same words wins; appended replies and whitespace are ignored', () => { + test('the newest unfinished draft with the same words wins; appended replies and whitespace are ignored', async () => { const older = { ...base, id: 'old', updatedAt: '2026-10-09T01:00:00Z' } const newer = { ...base, id: 'new', phase: 'planned' as const, intent: '在庫管理したい\n\n### 追記\n\n質問してください\n\n### 追記\n\nCSV も', updatedAt: '2026-10-09T02:00:00Z' } - expect(findResumableDraft([older, newer], ' 在庫管理したい\n')?.id).toBe('new') + expect((await findResumableDraft([older, newer], ' 在庫管理したい\n'))?.id).toBe('new') }) - test('different words, created apps and archived drafts never resume', () => { - expect(findResumableDraft([base], '在庫管理したい。')).toBeUndefined() - expect(findResumableDraft([{ ...base, phase: 'created' }], base.intent)).toBeUndefined() - expect(findResumableDraft([{ ...base, createdApplicationStackId: 'stack-1' }], base.intent)).toBeUndefined() - expect(findResumableDraft([{ ...base, phase: 'archived' }], base.intent)).toBeUndefined() - expect(findResumableDraft([base], ' ')).toBeUndefined() + test('different words, created apps and archived drafts never resume', async () => { + expect(await findResumableDraft([base], '在庫管理したい。')).toBeUndefined() + expect(await findResumableDraft([{ ...base, phase: 'created' }], base.intent)).toBeUndefined() + expect(await findResumableDraft([{ ...base, createdApplicationStackId: 'stack-1' }], base.intent)).toBeUndefined() + expect(await findResumableDraft([{ ...base, phase: 'archived' }], base.intent)).toBeUndefined() + expect(await findResumableDraft([base], ' ')).toBeUndefined() }) - test('saved drafts resume across languages with translated reply and publication markers', () => { + test('saved drafts resume across languages with translated reply and publication markers', async () => { const originalLanguage = currentLanguage() try { for (const language of ['en', 'ja'] as const) { setLanguage(language) for (const copy of [textJa, textEn]) { const draft = { ...base, intent: `${base.intent}\n\n${copy.intent.reply}\n\nCSV\n\n${copy.intent.publish}` } - expect(findResumableDraft([draft], base.intent)).toBe(draft) + expect(await findResumableDraft([draft], base.intent)).toBe(draft) const published = { ...base, intent: `${base.intent}\n\n${copy.intent.publish}` } - expect(findResumableDraft([published], base.intent)).toBe(published) + expect(await findResumableDraft([published], base.intent)).toBe(published) } } } finally { setLanguage(originalLanguage) } }) + test('a twice-shortened opening resumes only the original request, never a shared prefix', async () => { + const common = '在庫'.repeat(750) + const wanted = common + '倉庫用' + const initial = await composeBuildIntent(wanted, []) + const current = { ...base, intent: await composeBuildIntent(initial, ['詳細'.repeat(800), '追記'.repeat(800)], true) } + expect(await findResumableDraft([current], wanted)).toBe(current) + expect(await findResumableDraft([current], common + '店舗用')).toBeUndefined() + }) }) diff --git a/web/src/model/build/resume.ts b/web/src/model/build/resume.ts index d86b5a5..4fb7916 100644 --- a/web/src/model/build/resume.ts +++ b/web/src/model/build/resume.ts @@ -3,25 +3,15 @@ // visits, so a second press (back button, reload, retry) otherwise multiplies // 作りかけ. A draft whose app was already created is a different thing. import type { BuildDraft } from '../contracts/build' -import { textJa } from './copy' -import { textEn } from './copy.en' +import { sameBuildOpening } from './questions' -const INTENT_MARKERS = [textJa.intent, textEn.intent] - -/** Read saved replies from either language so switching never creates a duplicate draft. */ -function baseIntent(intent: string): string { - let base = intent - for (const marker of INTENT_MARKERS) { - base = base.split(`\n\n${marker.reply}\n\n`, 1)[0]!.split(`\n\n${marker.publish}`, 1)[0]! - } - return base.trim() -} - -export function findResumableDraft(drafts: readonly BuildDraft[], intent: string): BuildDraft | undefined { +export async function findResumableDraft(drafts: readonly BuildDraft[], intent: string): Promise { const wanted = intent.trim() if (!wanted) return undefined - return drafts - // A phase this console does not know may already be past creation: never resume into it. - .filter((draft) => baseIntent(draft.intent) === wanted && draft.phase.kind === 'known' && draft.phase.value !== 'created' && draft.phase.value !== 'archived' && !draft.createdApplicationStackId) - .sort((a, b) => Date.parse(b.updatedAt) - Date.parse(a.updatedAt))[0] + let newest: BuildDraft | undefined + for (const draft of drafts) { + if (draft.phase.kind !== 'known' || draft.phase.value === 'created' || draft.phase.value === 'archived' || draft.createdApplicationStackId) continue + if ((!newest || Date.parse(draft.updatedAt) > Date.parse(newest.updatedAt)) && await sameBuildOpening(draft.intent, wanted)) newest = draft + } + return newest } diff --git a/web/src/model/build/spec.test.ts b/web/src/model/build/spec.test.ts index a45e70d..288f031 100644 --- a/web/src/model/build/spec.test.ts +++ b/web/src/model/build/spec.test.ts @@ -41,14 +41,14 @@ describe('spec front matter', () => { }) describe('build intent', () => { - test('recovers the user-authored opening after composition and a language switch', () => { + test('recovers the user-authored opening after composition and a language switch', async () => { const restore = preserveLanguage() try { for (const language of ['ja', 'en'] as const) { setLanguage(language) for (const publish of [undefined, false, true]) { for (const replies of [[], ['検索も', 'PDF も出す']]) { - const intent = composeBuildIntent('見積を作る\n入力はかんたんに', replies, publish) + const intent = await composeBuildIntent('見積を作る\n入力はかんたんに', replies, publish) setLanguage(language === 'ja' ? 'en' : 'ja') expect(decomposeBuildIntent(intent)).toBe('見積を作る\n入力はかんたんに') setLanguage(language) @@ -58,21 +58,58 @@ describe('build intent', () => { expect(decomposeBuildIntent('普通の本文に ### 追記 と書く')).toBe('普通の本文に ### 追記 と書く') } finally { restore() } }) - test('composes follow-ups in order without a console-authored premises block', () => { - expect(composeBuildIntent(' 見積を作る ', [' PDF も出す ', ' ', '検索も'])).toBe('見積を作る\n\n### 追記\n\nPDF も出す\n\n### 追記\n\n検索も') + test('keeps the English envelope of a resumed plan independently of the current display language', async () => { + const stored = 'Track stock\n\n### Follow-up\n\nCSV\n\nPublish: yes' + const replies = ['CSV', 'x'.repeat(3800), 'y'.repeat(3800), 'Use a barcode'] + const result = await composeBuildIntent(stored, replies, true) + expect(result).toContain('(2 earlier follow-ups omitted)') + expect(result.endsWith('\n\n### Follow-up\n\nUse a barcode\n\nPublish: yes')).toBe(true) + expect(await composeBuildIntent(result, replies, true)).toBe(result) }) - test('publication keeps the explicit marker', () => { - expect(composeBuildIntent('見積を作る', [])).not.toContain('公開: する') - expect(composeBuildIntent('見積を作る', [], false)).not.toContain('公開: する') - expect(composeBuildIntent('見積を作る', [], true)).toBe('見積を作る\n\n公開: する') + test('composes follow-ups in order without a console-authored premises block', async () => { + expect(await composeBuildIntent(' 見積を作る ', [' PDF も出す ', ' ', '検索も'])).toBe('見積を作る\n\n### 追記\n\nPDF も出す\n\n### 追記\n\n検索も') }) - test('bounds all inputs to 8000 characters, reserving an intact publication marker', () => { - for (const publish of [undefined, false, true]) { - const result = composeBuildIntent('あ'.repeat(7999) + '😀', ['追記'.repeat(8000)], publish) - expect(result.length).toBeLessThanOrEqual(8000) - expect(result).not.toMatch(/[\uD800-\uDBFF]$/) - if (publish) expect(result.endsWith('\n\n公開: する')).toBe(true) + test('publication keeps the explicit marker', async () => { + expect(await composeBuildIntent('見積を作る', [])).not.toContain('公開: する') + expect(await composeBuildIntent('見積を作る', [], false)).not.toContain('公開: する') + expect(await composeBuildIntent('見積を作る', [], true)).toBe('見積を作る\n\n公開: する') + }) + test('keeps an exact 4000-byte Japanese opening and abbreviates an oversized one without splitting a code point', async () => { + const exact = '見'.repeat(1332) + '😀' + expect(await composeBuildIntent(exact, [])).toBe(exact) + const oversized = '😀見'.repeat(600) + const result = await composeBuildIntent(oversized, []) + const excerpt = decomposeBuildIntent(result) + expect(new TextEncoder().encode(result).length).toBeLessThanOrEqual(4000) + expect(excerpt).toMatch(/^(?:😀見)+(?:😀)?…$/u) + expect(await composeBuildIntent(result, [])).toBe(result) + }) + test('keeps a chronological suffix of complete replies and marks the omitted count deterministically', async () => { + const base = '在庫管理' + const replies = Array.from({ length: 30 }, (_, i) => `要件${i}: ${'棚卸'.repeat(40)}`) + const result = await composeBuildIntent(base, replies, true) + const count = Number(/以前の追記 (\d+) 件を省略/.exec(result)?.[1]) + expect(count).toBeGreaterThan(0) + expect(count).toBeLessThan(replies.length - 1) + expect(result).toBe([base, `(以前の追記 ${count} 件を省略)`, ...replies.slice(count)].join('\n\n### 追記\n\n') + '\n\n公開: する') + expect(new TextEncoder().encode(result).length).toBeLessThanOrEqual(4000) + const restore = preserveLanguage() + try { + setLanguage('en') + expect(await composeBuildIntent(base, [...replies], true)).toBe(result) + expect(await composeBuildIntent(result, replies, true)).toBe(result) + } finally { restore() } + }) + test('even a full opening cannot crowd out the newest message or the publication decision', async () => { + const opening = 'a'.repeat(4000) + const earlier = '以前の変更'.repeat(300) + for (const latest of ['この内容で提案して', '変更点:' + '😀'.repeat(1200)]) { + const result = await composeBuildIntent(opening, [earlier, latest], true) + expect(result).toContain(latest.length < 100 ? latest : '変更点:😀') + expect(result).not.toContain(earlier) + expect(result.endsWith('\n\n公開: する')).toBe(true) + expect(new TextEncoder().encode(result).length).toBeLessThanOrEqual(4000) + expect(await composeBuildIntent(result, [earlier, latest], true)).toBe(result) } - expect(composeBuildIntent('x'.repeat(8000), [])).toHaveLength(8000) }) })