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
64 changes: 56 additions & 8 deletions web/src/features/build/build-failure-notice.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,14 @@ import { expect, spyOn, test } from 'bun:test'
import type { ApplicationDraft, BuildFailure } from '@appthrust/api-schema/platform-api'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { createMemoryHistory, createRootRoute, createRoute, createRouter, RouterProvider } from '@tanstack/react-router'
import { act } from 'react'
import { act, type ReactElement } from 'react'
import { draftOf, turnOf } from '../../api/testing/build-domain'
import { createRoot } from 'react-dom/client'
import { renderToStaticMarkup } from 'react-dom/server'
import * as api from '../../api/build'
import { buildKeys } from '../../api/queries/build'
import { ImproveButton } from '../improve/entry'
import { buildCopy } from '../../model/build/copy'
import { BuildFailureNotice } from './build-failure-notice'

const at = '2026-11-01T00:00:00Z'
Expand All @@ -22,27 +25,29 @@ test('cause is plain escaped text; viewers and successful builds have no repair
expect(renderToStaticMarkup(<BuildFailureNotice failure={undefined} projectId="pj-demo" stackId="stack-web" title="台帳" canEdit />)).toBe('')
})

test('one click creates an improvement draft and sends exactly the cause lines as its first turn', async () => {
async function exerciseStart(entry: ReactElement, interact: (container: HTMLDivElement, expectNoWrites: () => void) => Promise<string>) {
const create = spyOn(api, 'createDraft').mockResolvedValue(draftOf(draft))
const list = spyOn(api, 'listDrafts').mockResolvedValue({ data: [], unreadable: [] })
const turn = spyOn(api, 'createTurn').mockImplementation(async (_projectId, _draftId, payload) => turnOf({ id: 'turn-1', kind: 'conversation', userMessage: payload.message, status: 'pending', startedAt: at, devWorkspaceId: 'workspace' }))
const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } })
client.setQueryData(buildKeys.drafts('pj-demo'), { data: [], unreadable: [] })
const container = document.createElement('div')
document.body.append(container)
const root = createRoot(container)
const rootRoute = createRootRoute()
const route = createRoute({ getParentRoute: () => rootRoute, path: '/', component: () => <BuildFailureNotice failure={failure} projectId="pj-demo" stackId="stack-web" title="台帳" canEdit /> })
const route = createRoute({ getParentRoute: () => rootRoute, path: '/', component: () => entry })
const destination = createRoute({ getParentRoute: () => rootRoute, path: '/-/improve/$draftId', component: () => <p>改善</p> })
const router = createRouter({ routeTree: rootRoute.addChildren([route, destination]), history: createMemoryHistory({ initialEntries: ['/'] }) })
try {
await router.load()
await act(async () => { root.render(<QueryClientProvider client={client}><RouterProvider router={router} /></QueryClientProvider>) })
const button = container.querySelector<HTMLButtonElement>('[data-testid="repair-build-with-ai"]')
expect(button?.textContent).toContain('AI に直させる')
await act(async () => { button!.click() })
const message = await interact(container, () => {
expect(create).not.toHaveBeenCalled()
expect(turn).not.toHaveBeenCalled()
})
expect(create).toHaveBeenCalledTimes(1)
expect(create).toHaveBeenCalledWith('pj-demo', { kind: 'improvement', applicationStackId: 'stack-web', title: '台帳', intent: failure.lines.join('\n') })
expect(turn).toHaveBeenCalledWith('pj-demo', 'repair-draft', { message: failure.lines.join('\n') })
expect(create).toHaveBeenCalledWith('pj-demo', { kind: 'improvement', applicationStackId: 'stack-web', title: '台帳', intent: message })
expect(turn).toHaveBeenCalledWith('pj-demo', 'repair-draft', { message })
expect(router.state.location.pathname).toBe('/-/improve/repair-draft')
} finally {
await act(async () => { root.unmount() })
Expand All @@ -52,4 +57,47 @@ test('one click creates an improvement draft and sends exactly the cause lines a
list.mockRestore()
turn.mockRestore()
}
}

test('one click creates an improvement draft and sends exactly the cause lines as its first turn', async () => {
await exerciseStart(<BuildFailureNotice failure={failure} projectId="pj-demo" stackId="stack-web" title="台帳" canEdit />, async (container) => {
const button = container.querySelector<HTMLButtonElement>('[data-testid="repair-build-with-ai"]')!
expect(button.textContent).toContain('AI に直させる')
await act(async () => { button.click() })
return failure.lines.join('\n')
})
})

test.each(['improve', 'repair'])('an oversized %s request is kept for editing; only the corrected 4000 bytes are sent', async (mode) => {
const lines = ['在庫'.repeat(666), '欠品']
const entry = mode === 'repair'
? <BuildFailureNotice failure={{ lines }} projectId="pj-demo" stackId="stack-web" title="台帳" canEdit />
: <ImproveButton app={{ displayName: '台帳' }} projectId="pj-demo" stackId="stack-web" />
await exerciseStart(entry, async (container, expectNoWrites) => {
await act(async () => { container.querySelector<HTMLButtonElement>('[data-testid$="-with-ai"]')!.click() })
const dialog = document.querySelector<HTMLElement>('[role="dialog"]')!
const input = dialog.querySelector('textarea')!
const form = dialog.querySelector('form')!
const submit = dialog.querySelector<HTMLButtonElement>('button[type="submit"]')!
const type = async (value: string) => {
await act(async () => {
Object.getOwnPropertyDescriptor(Object.getPrototypeOf(input), 'value')!.set!.call(input, value)
input.dispatchEvent(new window.Event('input', { bubbles: true }) as unknown as Event)
})
}
const original = lines.join('\n')
if (mode === 'improve') await type(original)
expect(input.value).toBe(original)
expect(dialog.textContent).toContain(buildCopy.inputBytes.over(3))
expect(submit.disabled).toBe(true)
await act(async () => { form.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event) })
expectNoWrites()

const edited = '在庫'.repeat(666) + '😀'
await type(edited)
expect(dialog.textContent).toContain(buildCopy.inputBytes.remaining(0))
expect(submit.disabled).toBe(false)
await act(async () => { form.dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }) as unknown as Event) })
return edited
})
})
10 changes: 6 additions & 4 deletions web/src/features/build/build-failure-notice.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ export function BuildFailureNotice({ failure, projectId, stackId, title, canEdit
canEdit: boolean
behind?: { runUrl?: string }
}) {
const repair = canEdit && stackId && failure
? <ImproveButton app={{ displayName: title }} projectId={projectId} stackId={stackId} initialMessage={failure.lines.join('\n')} actionLabel="AI に直させる" />
const cause = failure?.lines.join('\n')
// Pass the full cause: the improvement entry opens it for editing if it cannot be sent in one click.
const repair = canEdit && stackId && cause
? <ImproveButton app={{ displayName: title }} projectId={projectId} stackId={stackId} initialMessage={cause} actionLabel="AI に直させる" />
: null
if (behind) {
const runUrl = behind.runUrl && /^https?:\/\//i.test(behind.runUrl) ? behind.runUrl : undefined
Expand All @@ -28,12 +30,12 @@ export function BuildFailureNotice({ failure, projectId, stackId, title, canEdit
{repair}
</> : undefined}>
<p>{copy.detail}</p>
{failure ? <p className="mt-1 whitespace-pre-wrap break-words" data-testid="build-failure-cause">{copy.cause(failure.lines.join('\n'))}</p> : null}
{cause ? <p className="mt-1 whitespace-pre-wrap break-words" data-testid="build-failure-cause">{copy.cause(cause)}</p> : null}
</Notice></div>
}
if (!failure) return null
return <Notice tone="error">
<p className="whitespace-pre-wrap break-words" data-testid="build-failure-cause">ビルドが失敗しました。原因: {failure.lines.join('\n')}</p>
<p className="whitespace-pre-wrap break-words" data-testid="build-failure-cause">ビルドが失敗しました。原因: {cause}</p>
{repair ? <div className="mt-3">{repair}</div> : null}
</Notice>
}
2 changes: 1 addition & 1 deletion web/src/features/build/composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export interface ComposerProps {
onChip(value: string, label: string): void
}

export const MAX_LENGTH = 4000
const MAX_LENGTH = 4000
const MIN_ROWS = 3
const MAX_ROWS = 8

Expand Down
18 changes: 12 additions & 6 deletions web/src/features/build/console-entry.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import { afterEach, beforeEach, describe, expect, spyOn, test } from 'bun:test'
import { createBuildSessionsApi, type BuildSessionsApi } from '../../api/build-sessions'
import { getDraft } from '../../api/build'
import { buildCopy } from '../../model/build/copy'
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 @@ -55,17 +56,20 @@ 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)
test('a console-v1 start replays the complete 4000-byte opening and never sends an oversized one', async () => {
const opening = '受'.repeat(1332) + '😀'
const create = spyOn(api, 'create')
restore.push(() => create.mockRestore())
await expect(startConsoleBuild(opening + '字', 'g-team-a', deps())).rejects.toThrow(buildCopy.inputBytes.over(3))
expect(readConsoleStart(storage)).toBeUndefined()
expect(create).not.toHaveBeenCalled()
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(payload.intent).toBe(opening)
expect(create.mock.calls[1]).toEqual([payload, key])
expect(await sessions()).toHaveLength(1)
})
Expand Down Expand Up @@ -167,12 +171,14 @@ 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)
test('Platform rejects an oversized opening locally and resumes an exact 4000-byte opening without truncation', async () => {
const opening = '庫'.repeat(1332) + '😀'
const options = { groupId: 'g-team-a', ownerSubject: 'sub-yamada' }
await expect(beginBuild('commerce', opening + '字', options)).rejects.toThrow(buildCopy.inputBytes.over(3))
expect(mock.count('POST', /\/application-drafts$/)).toBe(0)
const { id } = await beginBuild('commerce', opening, options)
const stored = (await getDraft('commerce', id)).intent
expect(new TextEncoder().encode(stored).length).toBeLessThanOrEqual(4000)
expect(stored).toBe(opening)
expect((await beginBuild('commerce', opening, options)).id).toBe(id)
expect(mock.count('POST', /\/application-drafts$/)).toBe(1)
})
Expand Down
26 changes: 20 additions & 6 deletions web/src/features/build/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ 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 { buildCopy } from '../../model/build/copy'
import { remainingIntentBytes } 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 All @@ -27,6 +28,11 @@ export function resolveBuildGroup(me: Pick<Me, 'effectiveGroupIds'>, groups: rea
return membershipRoots(me, groups)[0]?.id
}

function checkOpeningSize(words: string): void {
const remaining = remainingIntentBytes(words)
if (remaining < 0) throw new Error(buildCopy.inputBytes.over(-remaining))
}

/**
* Starts building from `intent` and answers the draft to open (`paths.build(id)`).
* platform-v1 (the default): resumes the caller's unfinished draft with these exact words, otherwise creates one.
Expand All @@ -35,14 +41,21 @@ export function resolveBuildGroup(me: Pick<Me, 'effectiveGroupIds'>, groups: rea
export async function beginBuild(projectId: string, intent: string, options: { groupId: string; ownerSubject: string; newSessionEngine?: NewSessionEngine }): Promise<{ id: string }> {
if (!options.groupId) throw new Error(text.page.noGroup.body)
if (options.newSessionEngine === 'console-v1') return startConsoleBuild(intent, options.groupId)
const words = intent.trim()
const drafts = await listDrafts(projectId)
const existing = await findResumableDraft(drafts.data, intent)
const existing = await findResumableDraft(drafts.data, words)
if (existing) {
if (!readBuildSession(existing.id)) saveBuildSession(existing.id, initialSession({ projectId, ownerSubject: options.ownerSubject, groupId: options.groupId, baseIntent: existing.intent }))
const saved = readBuildSession(existing.id)
if (!saved || saved.projectId !== projectId || saved.ownerSubject !== options.ownerSubject) {
saveBuildSession(existing.id, initialSession({ projectId, ownerSubject: options.ownerSubject, groupId: options.groupId, baseIntent: words }))
} else if (saved.baseIntent !== words) {
saveBuildSession(existing.id, { ...saved, baseIntent: words })
}
return existing
}
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() }))
checkOpeningSize(words)
const draft = await createDraft(projectId, { title: titleFromIntent(words), intent: words })
saveBuildSession(draft.id, initialSession({ projectId, ownerSubject: options.ownerSubject, groupId: options.groupId, baseIntent: words }))
return draft
}

Expand Down Expand Up @@ -98,10 +111,11 @@ export async function startConsoleBuild(intent: string, groupId: string, deps: P
let start: ConsoleStart = saved && saved.intent === words && saved.groupId === groupId
? saved
: { intent: words, groupId, locale: currentLanguage(), key: mintIdempotencyKey() }
if (!start.sessionId) checkOpeningSize(words)
saveConsoleStart(start, storage)
let session: BuildSession
try {
session = start.sessionId ? await api.get(start.sessionId) : await api.create({ kind: 'new-app', groupId, intent: await boundBuildOpening(words), locale: start.locale }, start.key)
session = start.sessionId ? await api.get(start.sessionId) : await api.create({ kind: 'new-app', groupId, intent: 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
27 changes: 25 additions & 2 deletions web/src/features/build/use-build-session.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { keys } from '../../api/queries/shared'
import { sessionExpiryStore } from '../../api/session-expiry'
import { buildCopy } from '../../model/build/copy'
import { shareScopeLabel } from '../../model/access'
import { composeBuildIntent } from '../../model/build/questions'
import { boundBuildOpening, composeBuildIntent, decomposeBuildIntent } from '../../model/build/questions'
import { parseSpec, serializeSpec } from '../../model/build/spec'
import type { BuildFailure, BuildMessage, BuildPrimary, BuildStage } from '../../model/build/types'
import * as appViews from '../app/use-app-views'
Expand Down Expand Up @@ -180,11 +180,34 @@ describe('kickoff to plan handoff', () => {
}))
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.failure).toMatchObject({ kind: 'platform', ...buildCopy.failure.requestRejected, reference: { draftId: draft.id } })
expect(build.session.pending.map((item) => item.text)).toEqual(['一覧を作る'])
expect(createTurn).not.toHaveBeenCalled()
})

test('a long turn receives the full reply while the following kickoff plans with the complete opening', async () => {
const opening = '在庫'.repeat(600)
const message = '倉庫'.repeat(1500)
const generation = mockGeneration()
const firstTurn = buildCopy.questions.firstTurn
const stored = `${await boundBuildOpening(opening, 1941)}\n\n### 追記\n\n${firstTurn}`
createTurn.mockImplementation(async (_project, _draftId, { message }) => turnOf(turn(message === buildCopy.questions.kickoffReply ? 'kickoff' : 'large', message, 2)))
await mount({ ...draft, intent: stored, conversationTurns: [turn('opening', firstTurn, 0)] }, { ...initial, baseIntent: opening })
await act(async () => { build.send(message) })
expect(createTurn).toHaveBeenCalledWith(me.projectId, draft.id, { message })
await act(async () => { build.send(buildCopy.questions.kickoffReply) })
const intents = update.mock.calls.map(([, , patch]) => patch.intent!)
expect(intents).toHaveLength(3)
for (const intent of intents) {
expect(decomposeBuildIntent(intent)).toBe(opening)
expect(new TextEncoder().encode(intent).length).toBeLessThanOrEqual(4000)
}
expect(intents[0]).not.toContain(message)
expect(intents[2]).toContain(buildCopy.questions.kickoffReply)
expect(build.session.lastPlannedIntent).toBe(intents[2])
expect(generation).toHaveBeenCalledTimes(1)
})

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()
Expand Down
Loading