Skip to content
Merged
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
25 changes: 25 additions & 0 deletions web/src/features/build/console-entry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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' })
Expand Down
7 changes: 4 additions & 3 deletions web/src/features/build/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -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 } : {})
Expand Down
54 changes: 53 additions & 1 deletion web/src/features/build/use-build-session.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<BuildDraft>(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<BuildDraft>(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)
Expand Down Expand Up @@ -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 })
})
Expand Down
14 changes: 8 additions & 6 deletions web/src/features/build/use-build-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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'}`
Expand Down
2 changes: 1 addition & 1 deletion web/src/model/build/copy.en.ts
Original file line number Diff line number Diff line change
@@ -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.',
Expand Down
2 changes: 1 addition & 1 deletion web/src/model/build/copy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: 'このアプリを作るために決めるべきことを、一つずつ質問してください。',
Expand Down
10 changes: 10 additions & 0 deletions web/src/model/build/failure.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
4 changes: 4 additions & 0 deletions web/src/model/build/failure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down
Loading