diff --git a/web/e2e/stories/app-delete.mock.spec.ts b/web/e2e/stories/app-delete.mock.spec.ts index 8ea5730..e5c5a86 100644 --- a/web/e2e/stories/app-delete.mock.spec.ts +++ b/web/e2e/stories/app-delete.mock.spec.ts @@ -1,3 +1,4 @@ +import type { Route } from '@playwright/test' import { test, expect, seed, captureWrite, withExpectedFailures } from '../support/fixtures' test.describe('App delete @app', () => { @@ -69,4 +70,49 @@ test.describe('App delete @app', () => { await expect(main.getByText(appPath, { exact: true })).toBeVisible() await expect(page.getByRole('heading', { level: 1, name: app.name, exact: true })).toHaveCount(0) }) + + // APT-1234: Platform refuses to delete an app that still has work areas (412 `branch_has_active_delivery`, the + // blockers counted by kind). Only that answer is rewritten in the browser; once they are gone the same dialog + // deletes the app. + test('a deletion stopped by the app\'s remaining work areas says what blocks it and what to do, never the platform\'s message @mock @story', async ({ page, mock }, testInfo) => { + void mock + const app = seed.apps.keihi + const stackPath = `/api/v1/projects/${seed.projectId}/application-stacks/${app.slug}` + const deletes: number[] = [] + await page.route(`**${stackPath}`, (route: Route) => { + if (route.request().method() !== 'DELETE') return route.continue() + deletes.push(412) + return route.fulfill({ status: 412, json: { error: { code: 'failed_precondition', message: 'application branch still has active delivery consumers', details: { + reason: 'branch_has_active_delivery', + activeConsumers: [{ kind: 'DevWorkspace', count: 2 }], + nextActions: ['Stop or delete the listed delivery consumers, then retry the Application Branch deletion.'], + } } } }) + }) + + await page.goto(`/${app.groupPath}/${app.slug}/-/settings`) + await expect(page.getByRole('heading', { level: 1, name: app.name, exact: true })).toBeVisible() + await expect(page.getByTestId('env-table').getByRole('row').filter({ hasText: 'APP_TITLE' })).toContainText(app.slug) + await page.getByRole('region', { name: '危険な操作', exact: true }).getByRole('button', { name: '削除する', exact: true }).click() + const dialog = page.getByRole('dialog', { name: `「${app.name}」を削除しますか?`, exact: true }) + await dialog.getByLabel(`確認のため「${app.name}」と入力してください。`, { exact: true }).fill(app.name) + const confirm = dialog.getByRole('button', { name: '完全に削除する', exact: true }) + + await withExpectedFailures([{ method: 'DELETE', path: stackPath, status: 412, count: 1, reason: 'the app still has work areas' }], async () => { + await confirm.click() + const refusal = dialog.getByRole('alert') + await expect(refusal).toContainText('このアプリにはまだ残っているものがあるため、削除できませんでした') + await expect(refusal).toContainText('このアプリの作業場所が 2 か所残っています。') + await expect(refusal).toContainText('この画面からは片づけられません。基盤の担当者に片づけてもらってから、もう一度「完全に削除する」を押してください。') + }) + for (const word of ['application branch', 'delivery consumers', 'DevWorkspace', '操作に失敗しました']) await expect(dialog.getByText(word)).toHaveCount(0) + expect(deletes).toEqual([412]) + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true) + await page.screenshot({ path: testInfo.outputPath('delete-blocked.png'), fullPage: true }) + + // The work areas are gone: the same dialog deletes the app. + await page.unroute(`**${stackPath}`) + await confirm.click() + await expect(page).toHaveURL(`/${app.groupPath}`) + await expect(page.getByRole('main').getByRole('link', { name: new RegExp(app.name) })).toHaveCount(0) + }) }) diff --git a/web/e2e/stories/improve-start-refused.mock.spec.ts b/web/e2e/stories/improve-start-refused.mock.spec.ts new file mode 100644 index 0000000..e771e6e --- /dev/null +++ b/web/e2e/stories/improve-start-refused.mock.spec.ts @@ -0,0 +1,89 @@ +import type { APIRequestContext, Route } from '@playwright/test' +import { test, expect, seed, withExpectedFailures, type MockControl } from '../support/fixtures' + +// APT-1232: Platform refuses a new improvement run while the session's proposal awaits the owner's review or is +// closed (409 `source_change_proposal_run_blocked`). A start the page still offered (its last read of the proposal +// was older than the refusal) is answered on screen in the user's words, once, with no retry; and while the +// proposal awaits review or is closed, the change card explains why instead of offering 「この内容で直す」. Only the +// proposal read is rewritten in the browser (an older phase, as an earlier read showed it); the mock answers the start. +const project = `/api/v1/projects/${seed.projectId}` +const PENDING = { title: '提案の確認を待っています', reason: '所有者が提案を確認しているあいだは、作業を進められません。やり直しを求められたら、そこから続けられます。' } +const CLOSED = { title: 'この提案は締め切られています', reason: '反映・見送り・取り下げ・期限切れのどれかで終わっていて、この提案では続けられません。続けて直すときは、アプリの画面の「AIで直す」から始めてください。' } + +/** + * 山田 (an owner of 見積作成, so also its reviewer) improves it until the proposal awaits review, asks for changes, + * talks a new change through (the conversation shows it with 「この内容で直す」), and sends the proposal back for review. + */ +async function changeAwaitingReview(request: APIRequestContext, mock: MockControl): Promise<{ draftId: string; proposalPath: string }> { + const created = await (await request.post(`${project}/application-drafts`, { data: { kind: 'improvement', applicationStackId: seed.apps.mitsumori.slug, title: seed.apps.mitsumori.name, intent: '一覧に絞り込みを足したい' } })).json() + const draftPath = `${project}/application-drafts/${created.id as string}` + const talk = async (messages: string[]) => { + for (const message of messages) { + expect((await request.post(`${draftPath}/conversation-turns`, { data: { message } })).ok()).toBe(true) + await mock.advance() + } + } + await talk(['一覧に絞り込みを足したい', '状態で絞り込みたい']) + expect((await request.post(`${draftPath}/implementation-runs`, { data: {} })).ok()).toBe(true) + for (let i = 0; i < 12; i++) await mock.advance() + const proposalPath = `${project}/source-change-proposals/${(await (await request.get(draftPath)).json()).proposalId as string}` + expect((await (await request.get(proposalPath)).json()).phase).toBe('Proposed') + expect((await request.post(`${proposalPath}/decisions`, { data: { decision: 'RequestChanges', comment: '今月の分も表示してください' } })).ok()).toBe(true) + await talk(['CSV で書き出したい', '今月の分だけ']) + expect((await request.post(`${proposalPath}/submit`)).ok()).toBe(true) + expect((await (await request.get(proposalPath)).json()).phase).toBe('Proposed') + return { draftId: created.id as string, proposalPath } +} + +test.describe('improvement start refused @improve', () => { + test.afterEach(async ({ page }) => { + await page.unrouteAll({ behavior: 'ignoreErrors' }) + }) + + test('a refused start is said once in the user\'s words with no retry; a waiting or closed proposal explains instead of offering 「この内容で直す」 @mock @story', async ({ page, request, mock }, testInfo) => { + test.setTimeout(90_000) + const { draftId, proposalPath } = await changeAwaitingReview(request, mock) + // The page's last read of the proposal still shows it sent back for changes. + let stale = true + await page.route(`**${proposalPath}`, async (route: Route) => { + if (route.request().method() !== 'GET' || !stale) return route.continue() + const response = await route.fetch() + return route.fulfill({ response, json: { ...(await response.json()), phase: 'ChangesRequested' } }) + }) + const starts: number[] = [] + page.on('response', (response) => { + if (response.request().method() === 'POST' && new URL(response.url()).pathname === `${project}/application-drafts/${draftId}/implementation-runs`) starts.push(response.status()) + }) + + await page.goto(`/-/improve/${draftId}`) + const card = page.getByTestId('improve-proposal') + const start = card.getByRole('button', { name: 'この内容で直す', exact: true }) + await expect(start).toBeEnabled() + + await withExpectedFailures([{ method: 'POST', path: `${project}/application-drafts/{draftId}/implementation-runs`, status: 409, count: 1, reason: 'Platform refuses a new run while the proposal awaits review' }], async () => { + await start.click() + const refusal = card.getByRole('alert') + await expect(refusal).toContainText(PENDING.title) + await expect(refusal).toContainText(PENDING.reason) + }) + await expect(card.getByRole('button', { name: 'もう一度試す', exact: true })).toHaveCount(0) + await expect(start).toBeDisabled() + await expect(page.getByText('source change proposal')).toHaveCount(0) + expect(starts).toEqual([409]) + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth)).toBe(true) + await page.screenshot({ path: testInfo.outputPath('start-refused.png'), fullPage: true }) + + // The next read shows the proposal awaiting review: the card explains, and 「この内容で直す」 is not offered. + stale = false + await expect(card.getByRole('status').filter({ hasText: PENDING.title })).toContainText(PENDING.reason, { timeout: 15_000 }) + await expect(card.getByRole('button')).toHaveCount(0) + await expect(card.getByRole('alert')).toHaveCount(0) + + // The owner declines: the card says the proposal is closed and where to start again; nothing is sent. + expect((await request.post(`${proposalPath}/decisions`, { data: { decision: 'Reject' } })).ok()).toBe(true) + await expect(card.getByRole('status').filter({ hasText: CLOSED.title })).toContainText(CLOSED.reason, { timeout: 15_000 }) + await expect(card.getByRole('button')).toHaveCount(0) + await page.screenshot({ path: testInfo.outputPath('proposal-closed.png'), fullPage: true }) + expect(starts).toEqual([409]) + }) +}) diff --git a/web/src/copy/apps.en.ts b/web/src/copy/apps.en.ts index b2b4f68..185fe4a 100644 --- a/web/src/copy/apps.en.ts +++ b/web/src/copy/apps.en.ts @@ -282,6 +282,19 @@ export const appsEn: typeof apps = { deleteKeepsRepository: (repository?: string) => repository ? `Your code on GitHub (${repository}) will be kept.` : 'Your code on GitHub will be kept.', deleteSourceBusy: 'The app has stopped but is still connected to your code; wait a moment, then choose “Delete permanently” again.', + deleteRefused: { + inUse: 'Some parts of this app are still left, so it was not deleted', + workAreas: (count: number) => `This app still has ${count === 1 ? '1 work area' : `${count} work areas`} left.`, + workAreasNext: 'They cannot be cleared from this screen. Ask your administrator to clear them, then choose “Delete permanently” again.', + others: 'Something else connected to this app is still left.', + othersNext: 'Wait a moment, then choose “Delete permanently” again. If this continues, contact your administrator.', + waiting: 'The app is not ready to be deleted yet', + waitingWorkAreas: (count: number) => `${count === 1 ? '1 work area' : `${count} work areas`} of this app ${count === 1 ? 'is' : 'are'} being cleared.`, + waitingOthers: 'Things connected to this app are being cleared.', + waitingNext: 'Wait a moment, then choose “Delete permanently” again.', + failed: 'The app could not be deleted', + failedNext: 'Wait a moment, then choose “Delete permanently” again. If this continues, contact your administrator.', + }, deleteAction: 'Delete', deleteConfirm: 'Delete permanently', deleting: 'Deleting…', diff --git a/web/src/copy/apps.ts b/web/src/copy/apps.ts index a06bfee..1fc1736 100644 --- a/web/src/copy/apps.ts +++ b/web/src/copy/apps.ts @@ -296,6 +296,25 @@ export const apps = { deleteKeepsRepository: (repository?: string) => repository ? `GitHub の置き場(${repository})は消さずに残ります。` : 'GitHub の置き場は消さずに残ります。', deleteSourceBusy: 'アプリは止めましたが、置き場とのつながりをまだ外せていません。少し待ってから、もう一度「完全に削除する」を押してください。', + /** + * Platform refused the deletion: something of the app is still left (`inUse`; its work areas are named and + * counted, whatever made them and whether or not they run, and nothing in the console removes them) or is + * still being removed (`waiting`: the user presses again shortly; the console does not wait on its own). + * Never Platform's own message. + */ + deleteRefused: { + inUse: 'このアプリにはまだ残っているものがあるため、削除できませんでした', + workAreas: (count: number) => `このアプリの作業場所が ${count} か所残っています。`, + workAreasNext: 'この画面からは片づけられません。基盤の担当者に片づけてもらってから、もう一度「完全に削除する」を押してください。', + others: 'このアプリにつながっている、ほかのものがまだ残っています。', + othersNext: '少し待ってから、もう一度「完全に削除する」を押してください。続くときは基盤の担当者に相談してください。', + waiting: '削除の準備がまだ終わっていません', + waitingWorkAreas: (count: number) => `このアプリの作業場所 ${count} か所を片づけています。`, + waitingOthers: 'このアプリにつながっているものを片づけています。', + waitingNext: '少し待ってから、もう一度「完全に削除する」を押してください。', + failed: '削除できませんでした', + failedNext: '少し待ってから、もう一度「完全に削除する」を押してください。続くときは基盤の担当者に相談してください。', + }, deleteAction: '削除する', deleteConfirm: '完全に削除する', deleting: '削除しています…', diff --git a/web/src/dev/mock-improve.test.ts b/web/src/dev/mock-improve.test.ts index 79ebef9..d9509ef 100644 --- a/web/src/dev/mock-improve.test.ts +++ b/web/src/dev/mock-improve.test.ts @@ -63,7 +63,8 @@ test('question → proposal → run → review, in the application workspace', a expect(current.proposalId).toBeDefined() const proposalPath = `${project}/source-change-proposals/${current.proposalId}` expect((await call('GET', proposalPath)).body.phase).toBe('Proposed') - expect((await call('POST', `${path}/implementation-runs`)).status).toBe(409) + // Like Platform, a start while the proposal awaits review is refused with its own code (not another tab's `conflict`). + expect(await call('POST', `${path}/implementation-runs`)).toMatchObject({ status: 409, body: { error: { code: 'source_change_proposal_run_blocked' } } }) expect((await call('POST', `${proposalPath}/decisions`, { decision: 'RequestChanges', comment: '今月の分も表示してください' })).status).toBe(200) // The next request starts over with a question, then a new proposal with new tasks. diff --git a/web/src/dev/mock-platform.ts b/web/src/dev/mock-platform.ts index ceb5223..12aa22f 100644 --- a/web/src/dev/mock-platform.ts +++ b/web/src/dev/mock-platform.ts @@ -2306,7 +2306,9 @@ const routes: Array<[method: string, pattern: RegExp, handler: Handler]> = [ if (!draft) return error(404, 'not_found', 'application draft not found') if (state.role === 'Viewer') return error(403, 'forbidden', 'team role Viewer cannot implement applications') const proposal = draft.proposalId ? state.proposals.get(draft.proposalId) : undefined - if (proposal && (proposalWaiting(proposal.phase) || proposalTerminal(proposal.phase))) return error(409, 'conflict', 'proposal is awaiting review or is closed') + // Like platform-api (application_draft_proposal.go admitImprovementImplementation): a run starts only while the + // proposal is drafted or sent back for changes (not in ApplyFailed either), refused with its own code. + if (proposal && proposal.phase !== 'Drafting' && proposal.phase !== 'ChangesRequested') return error(409, 'source_change_proposal_run_blocked', 'source change proposal is awaiting review, applying, or closed') const handoff = draft.creationPlan?.implementationHandoff if (draft.phase !== 'created' || !draft.createdApplicationId || !handoff?.tasks.length) return error(412, 'failed_precondition', 'created application and handoff tasks are required') const previous = draft.implementationRuns?.at(-1) diff --git a/web/src/features/app/delete-dialog.test.ts b/web/src/features/app/delete-dialog.test.ts new file mode 100644 index 0000000..b27433f --- /dev/null +++ b/web/src/features/app/delete-dialog.test.ts @@ -0,0 +1,57 @@ +// APT-1234: a deletion Platform refused is said in the user's words, never with Platform's message. +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { ORPCError } from '@orpc/client' +import { preserveLanguage } from '../../../test/language' +import { ResponseContractError } from '../../api/boundary' +import { copy } from '../../copy' +import { setLanguage } from '../../shell/language' +import { deletionRefusal } from './delete-dialog' + +let restoreLanguage: () => void +beforeEach(() => { restoreLanguage = preserveLanguage() }) +afterEach(() => restoreLanguage()) + +const MESSAGE = 'application branch still has active delivery consumers' +const platform = (status: number, code: string, details?: Record) => + new ORPCError('UNKNOWN', { status, data: { body: { error: { code, message: MESSAGE, ...(details ? { details } : {}) } } } }) +const activeDelivery = (activeConsumers: unknown) => platform(412, 'failed_precondition', { reason: 'branch_has_active_delivery', activeConsumers, nextActions: ['Stop or delete the listed delivery consumers, then retry the Application Branch deletion.'] }) +const said = (error: unknown) => { + const refusal = deletionRefusal(error) + return refusal ? [refusal.title, ...refusal.lines].join(' ') : '' +} + +test.each(['ja', 'en'] as const)('remaining work areas are named and counted, with who can clear them, in %s', (language) => { + setLanguage(language) + const words = copy.app.settings.deleteRefused + expect(deletionRefusal(activeDelivery([{ kind: 'DevWorkspace', count: 2 }]))).toEqual({ title: words.inUse, lines: [words.workAreas(2), words.workAreasNext] }) + expect(deletionRefusal(activeDelivery([{ kind: 'DevWorkspace', count: 1 }, { kind: 'Release', count: 1 }]))).toEqual({ title: words.inUse, lines: [words.workAreas(1), words.others, words.workAreasNext] }) + // Something else, or nothing listed: no count, and to try again shortly. + for (const consumers of [[{ kind: 'Release', count: 1 }], undefined, 'unreadable']) { + expect(deletionRefusal(activeDelivery(consumers))).toEqual({ title: words.inUse, lines: [words.others, words.othersNext] }) + } + for (const consumers of [[{ kind: 'DevWorkspace', count: 2 }], [{ kind: 'HTTPPublish', count: 1 }]]) { + for (const hidden of [MESSAGE, 'DevWorkspace', 'HTTPPublish', 'delivery', 'workspace', 'branch_has_active_delivery', copy.common.actionFailed]) expect(said(activeDelivery(consumers))).not.toContain(hidden) + } +}) + +test.each(['ja', 'en'] as const)('a deletion Platform holds while it clears something says what is being cleared and to press again shortly, in %s', (language) => { + setLanguage(language) + const words = copy.app.settings.deleteRefused + const deleting = (dependents: unknown) => platform(409, 'conflict', { reason: 'dependents_deleting', retryAfterSeconds: 5, dependents }) + expect(deletionRefusal(deleting([{ kind: 'DevWorkspace', id: 'devws-1', name: '経費精算' }, { kind: 'DevWorkspace', id: 'devws-2', name: '経費精算' }]))).toEqual({ title: words.waiting, lines: [words.waitingWorkAreas(2), words.waitingNext] }) + expect(deletionRefusal(deleting([{ kind: 'Component', id: 'db', name: 'db' }]))).toEqual({ title: words.waiting, lines: [words.waitingOthers, words.waitingNext] }) + expect(deletionRefusal(platform(409, 'idempotency_in_progress', { reason: 'idempotency_in_progress', retryable: true }))).toEqual({ title: words.waiting, lines: [words.waitingOthers, words.waitingNext] }) + expect(said(deleting([{ kind: 'DevWorkspace', id: 'devws-1', name: '経費精算' }]))).not.toContain('devws-1') +}) + +test('any other Platform refusal says it was not deleted without Platform\'s message; what ActionError owns is left to it', () => { + setLanguage('ja') + const words = copy.app.settings.deleteRefused + expect(deletionRefusal(platform(409, 'conflict'))).toEqual({ title: words.failed, lines: [words.failedNext] }) + expect(deletionRefusal(platform(403, 'forbidden'))).toEqual({ title: words.failed, lines: [copy.errors.forbidden] }) + expect(said(platform(500, 'internal'))).not.toContain(MESSAGE) + expect(deletionRefusal(new ORPCError('UNAUTHORIZED', { status: 401 }))).toBeUndefined() + expect(deletionRefusal(new ResponseContractError({ source: 'platform', operationId: 'platformApiDeleteApplicationStack', method: 'DELETE', routeTemplate: '/application-stacks/{id}', issues: [{ path: '/', code: 'missing' }] }))).toBeUndefined() + expect(deletionRefusal(new Error(MESSAGE))).toBeUndefined() + expect(deletionRefusal(null)).toBeUndefined() +}) diff --git a/web/src/features/app/delete-dialog.tsx b/web/src/features/app/delete-dialog.tsx index 398a633..eea777e 100644 --- a/web/src/features/app/delete-dialog.tsx +++ b/web/src/features/app/delete-dialog.tsx @@ -1,4 +1,6 @@ import { useQueryClient } from '@tanstack/react-query' +import { isResponseContractError } from '../../api/boundary' +import { isAccessDenied, platformErrorEnvelope } from '../../api/platform-error' import { consoleKeys } from '../../api/queries/console' import { keys } from '../../api/queries/shared' import { copy } from '../../copy' @@ -16,6 +18,53 @@ export function deleteHelpText(view: AppView, sourceRepository: SourceRepository return sourceRepositoryIdFor(view) ? help + copy.app.settings.deleteKeepsRepository(repositoryNameOf(sourceRepository)) : help } +/** What a refused deletion says: a title and its sentences, never Platform's message. */ +export interface DeletionRefusal { + title: string + lines: string[] +} + +/** Platform's kind for an app's work areas (those of its build and improvement sessions among them); other kinds are not named. */ +const WORK_AREA_KIND = 'DevWorkspace' + +function entries(value: unknown): Record[] { + return Array.isArray(value) ? value.filter((item): item is Record => !!item && typeof item === 'object') : [] +} + +/** + * A deletion Platform refused, in the user's words; one attempt per 「完全に削除する」, the console never waits and + * sends again on its own: + * - 412 `branch_has_active_delivery` (platform-api application_branch.go `applicationBranchActiveDeliveryError`): + * what is left, from `activeConsumers` (kind and count); work areas are named and counted, and since nothing here + * removes them, the user is told who can; + * - 409 `dependents_deleting` (with its `dependents`) or any refusal marked `retryable`: Platform is still clearing + * something, and the user presses 「完全に削除する」 again shortly; + * - any other Platform refusal: that the app was not deleted, and what to do. + * Undefined where ActionError already speaks: sign-in, an unreadable answer, an error that is not Platform's answer. + */ +export function deletionRefusal(error: unknown): DeletionRefusal | undefined { + if (isResponseContractError(error) || isAccessDenied(error)) return undefined + const envelope = platformErrorEnvelope(error) + if (!envelope) return undefined + const words = copy.app.settings.deleteRefused + const details = envelope.details + if (details?.reason === 'branch_has_active_delivery') { + const consumers = entries(details.activeConsumers) + const workAreas = consumers.reduce((sum, item) => item.kind === WORK_AREA_KIND && typeof item.count === 'number' && item.count > 0 ? sum + item.count : sum, 0) + const others = consumers.length === 0 || consumers.some((item) => item.kind !== WORK_AREA_KIND) + return { + title: words.inUse, + lines: [...(workAreas ? [words.workAreas(workAreas)] : []), ...(others ? [words.others] : []), workAreas ? words.workAreasNext : words.othersNext], + } + } + if (details?.reason === 'dependents_deleting' || details?.retryable === true) { + const dependents = entries(details.dependents) + const workAreas = dependents.filter((item) => item.kind === WORK_AREA_KIND).length + return { title: words.waiting, lines: [workAreas && workAreas === dependents.length ? words.waitingWorkAreas(workAreas) : words.waitingOthers, words.waitingNext] } + } + return { title: words.failed, lines: [envelope.status === 403 ? copy.errors.forbidden : words.failedNext] } +} + /** Type-the-name delete confirmation (ux-design §6.5); used by the header menu, the overview and 危険な操作. */ export function DeleteAppDialog({ projectId, @@ -35,6 +84,7 @@ export function DeleteAppDialog({ const queryClient = useQueryClient() const mutation = useDeleteApp(projectId, app, view) const busy = mutation.error instanceof SourceStillReferencedError + const refusal = busy ? undefined : deletionRefusal(mutation.error) // A delete whose answer could not be read may have happened: read the app and its resources back before offering it again. const confirmation = useWriteConfirmation([mutation.error], mutation.reset, () => Promise.all([ queryClient.refetchQueries({ queryKey: consoleKeys.app(app.id) }), @@ -53,6 +103,7 @@ export function DeleteAppDialog({

{deleteHelpText(view, sourceRepository)}

{busy ? {copy.app.settings.deleteSourceBusy} : null} + {refusal ? {refusal.lines.map((line) =>

{line}

)}
: null} {confirmation.unconfirmed ? void confirmation.confirm()} confirming={confirmation.confirming} /> : null}
} @@ -62,7 +113,7 @@ export function DeleteAppDialog({ onConfirm={() => mutation.mutate()} pending={mutation.isPending} disabled={confirmation.unconfirmed} - error={busy || confirmation.unconfirmed ? undefined : mutation.error ?? undefined} + error={busy || refusal || confirmation.unconfirmed ? undefined : mutation.error ?? undefined} /> ) } diff --git a/web/src/features/build/implement/start-refusal.test.tsx b/web/src/features/build/implement/start-refusal.test.tsx new file mode 100644 index 0000000..209b051 --- /dev/null +++ b/web/src/features/build/implement/start-refusal.test.tsx @@ -0,0 +1,187 @@ +// APT-1232: a 409 to an implementation start is either another tab's start (its run shows in the draft read back, +// never reported) or a refusal of this start: Platform's typed refusal (said once, never retried) or an untyped +// conflict after which the draft read back shows no new run. +import { afterEach, beforeEach, expect, spyOn, test, type Mock } from 'bun:test' +import type { ApplicationDraft } from '@appthrust/api-schema/platform-api' +import { ORPCError } from '@orpc/client' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { preserveLanguage } from '../../../../test/language' +import * as buildApi from '../../../api/build' +import { buildDraftOptions } from '../../../api/queries/build' +import { draftOf } from '../../../api/testing/build-domain' +import { buildCopy } from '../../../model/build/copy' +import { failureOffers } from '../../../model/build/failure' +import type { BuildFailure } from '../../../model/build/types' +import { setLanguage } from '../../../shell/language' +import { useImplementation } from './use-implementation' + +const at = '2026-11-17T00:00:00Z' +const tasks = [{ title: '一覧に絞り込みを足す', description: '状態で絞り込めるようにする。', acceptanceCriteria: ['絞り込める'] }] +const wire: ApplicationDraft = { + id: 'draft-1', projectId: 'p1', kind: 'improvement', title: '見積作成', intent: '一覧に絞り込みを足したい', phase: 'created', + specMarkdown: '', architectureMarkdown: '', creationPlanGenerations: [], conversationTurns: [], creationExecutions: [], implementationRuns: [], createdSourceRepositories: [], + ownerUserId: 'owner', createdAt: at, updatedAt: at, createdApplicationId: 'mitsumori', createdApplicationStackId: 'mitsumori', proposalId: 'proposal-1', + creationPlan: { summary: '絞り込み', markdown: '# 絞り込み', representation: ['ApplicationStack'], implementationHandoff: { summary: '絞り込み', workspaceMode: 'application-develop', targetApplicationRef: 'createdApplicationId', sourceRepositoryStrategy: 'existing-source-repository', tasks } }, +} +const draft = draftOf(wire) +const conflict = (code: string | undefined, message: string, details?: Record) => + new ORPCError('CONFLICT', { status: 409, data: { body: { error: { ...(code ? { code } : {}), message, ...(details ? { details } : {}) } } } }) + +let root: Root +let container: HTMLDivElement +let client: QueryClient +let restoreLanguage: () => void +let created: Mock +let reads: Mock +/** What the tests read from the hook: the start, its request failure, confirming it, and taking a refusal back. */ +let implementation: { requestFailure?: BuildFailure; startPending(): void; confirm(): void; dismissRefusal(): void } + +function Harness() { + implementation = useImplementation({ projectId: 'p1', draft, handoff: draft.creationPlan?.implementationHandoff, enabled: true }) + return null +} + +async function startOnce() { + await act(async () => { implementation.startPending() }) + for (let index = 0; index < 5; index++) await act(async () => { await Bun.sleep(0) }) +} + +beforeEach(async () => { + restoreLanguage = preserveLanguage() + setLanguage('ja') + created = spyOn(buildApi, 'createImplementationRun') + // The draft read back after an untyped conflict: unchanged unless a test says another tab started a run. + reads = spyOn(buildApi, 'getDraft').mockResolvedValue(draft) + client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + client.setQueryData(buildDraftOptions('p1', draft.id).queryKey, draft) + container = document.createElement('div') + document.body.append(container) + root = createRoot(container) + await act(async () => { root.render() }) +}) + +afterEach(async () => { + await act(async () => { root.unmount() }) + container.remove() + client.clear() + created.mockRestore() + reads.mockRestore() + restoreLanguage() +}) + +/** The draft as another tab left it: its run, finished, is the latest. */ +const startedElsewhere = (id: string) => draftOf({ ...wire, implementationRuns: [{ id, status: 'succeeded', startedAt: at, finishedAt: at, devWorkspaceId: 'ws', taskIds: [], tasks: [] }] }) + +test('another tab\'s start is read back and never reported', async () => { + const cases: { code?: string; details?: Record }[] = [{ code: 'conflict' }, { code: 'idempotency_in_progress' }, {}, { code: 'conflict', details: { reason: 'idempotency_in_progress', retryable: true } }] + for (const [index, { code, details }] of cases.entries()) { + created.mockRejectedValueOnce(conflict(code, 'implementation run is running', details)) + reads.mockResolvedValueOnce(startedElsewhere(`run-elsewhere-${index}`)) + await startOnce() + expect(reads).toHaveBeenCalledTimes(index + 1) + expect(client.getQueryData(buildDraftOptions('p1', draft.id).queryKey)?.implementationRuns.at(-1)?.id).toBe(`run-elsewhere-${index}`) + expect(implementation.requestFailure).toBeUndefined() + } + expect(created).toHaveBeenCalledTimes(4) +}) + +test('an untyped conflict after which no other start shows is a refusal of this start, with a reference', async () => { + created.mockRejectedValueOnce(conflict('conflict', 'source change proposal is being withdrawn')) + await startOnce() + expect(reads).toHaveBeenCalledTimes(1) + expect(implementation.requestFailure).toMatchObject({ kind: 'failed', reasonCode: 'StartRefused', title: buildCopy.failure.failed.implement, reason: buildCopy.failure.retry, reference: { draftId: draft.id } }) + expect(created).toHaveBeenCalledTimes(1) +}) + +test('a draft read already in flight when the conflict comes back is not the read-back: a new read shows the other tab\'s run', async () => { + // A poll that started before the start, and answers (without the other tab's run) only after the conflict. + const early = Promise.withResolvers() + reads.mockImplementationOnce(() => early.promise) + const poll = client.fetchQuery({ ...buildDraftOptions('p1', draft.id), staleTime: 0 }).catch(() => undefined) + created.mockRejectedValueOnce(conflict('conflict', 'implementation run is running')) + reads.mockResolvedValueOnce(startedElsewhere('run-elsewhere')) + await startOnce() + await act(async () => { early.resolve(draft) }) + await act(async () => { await poll }) + for (let index = 0; index < 5; index++) await act(async () => { await Bun.sleep(0) }) + expect(reads).toHaveBeenCalledTimes(2) + expect(implementation.requestFailure).toBeUndefined() + expect(created).toHaveBeenCalledTimes(1) +}) + +test('a read-back that fails after an untyped conflict is said as unconfirmed, never as a refusal', async () => { + created.mockRejectedValueOnce(conflict('conflict', 'implementation run is running')) + reads.mockRejectedValueOnce(new TypeError('Failed to fetch')) + await startOnce() + expect(implementation.requestFailure).toMatchObject({ kind: 'unconfirmed', ...buildCopy.failure.unconfirmed }) + expect(implementation.requestFailure?.reasonCode).toBeUndefined() + expect(failureOffers(implementation.requestFailure!).retry).toBe(false) +}) + +test('confirming a plain conflict whose read-back failed reads again and decides it: no new run is a refusal, a new run is observed', async () => { + const confirmOnce = async () => { + await act(async () => { implementation.confirm() }) + for (let index = 0; index < 5; index++) await act(async () => { await Bun.sleep(0) }) + } + created.mockRejectedValueOnce(conflict('conflict', 'source change proposal is being withdrawn')) + reads.mockRejectedValueOnce(new TypeError('Failed to fetch')) + await startOnce() + expect(implementation.requestFailure?.kind).toBe('unconfirmed') + // The read now answers, without another start: Platform refused this one. + reads.mockResolvedValueOnce(draft) + await confirmOnce() + expect(implementation.requestFailure).toMatchObject({ kind: 'failed', reasonCode: 'StartRefused', title: buildCopy.failure.failed.implement }) + + // Again, and this time the read shows another tab's run: it is observed, nothing is reported. + created.mockRejectedValueOnce(conflict('conflict', 'implementation run is running')) + reads.mockRejectedValueOnce(new TypeError('Failed to fetch')) + await startOnce() + expect(implementation.requestFailure?.kind).toBe('unconfirmed') + reads.mockResolvedValueOnce(startedElsewhere('run-elsewhere')) + await confirmOnce() + expect(implementation.requestFailure).toBeUndefined() + // Confirming never sends the start again. + expect(created).toHaveBeenCalledTimes(2) + expect(reads).toHaveBeenCalledTimes(4) +}) + +test('a generic conflict whose reason names a refusal is that refusal, never another tab\'s start', async () => { + created.mockRejectedValueOnce(conflict('conflict', 'source change proposal is awaiting review, applying, or closed', { reason: 'source_change_proposal_run_blocked' })) + await startOnce() + expect(implementation.requestFailure).toMatchObject({ kind: 'blocked', reasonCode: 'ProposalRunBlocked', ...buildCopy.failure.run.proposalPending }) + expect(failureOffers(implementation.requestFailure!).retry).toBe(false) + + await act(async () => { implementation.dismissRefusal() }) + created.mockRejectedValueOnce(conflict('conflict', 'the start is not admitted', { reason: 'StartNotAdmitted' })) + await startOnce() + expect(implementation.requestFailure).toMatchObject({ kind: 'blocked', title: buildCopy.failure.failed.implement, reason: buildCopy.failure.run.blocked, reference: { draftId: draft.id } }) + expect(implementation.requestFailure?.reasonCode).toBeUndefined() + expect(failureOffers(implementation.requestFailure!).retry).toBe(false) + expect(created).toHaveBeenCalledTimes(2) +}) + +test('a start refused because of the proposal is said once in the proposal\'s words, offers no retry, and is taken back when the proposal moves on', async () => { + created.mockRejectedValueOnce(conflict('source_change_proposal_run_blocked', 'source change proposal is awaiting review, applying, or closed')) + await startOnce() + const failure = implementation.requestFailure + expect(failure).toMatchObject({ kind: 'blocked', reasonCode: 'ProposalRunBlocked', ...buildCopy.failure.run.proposalPending }) + expect(failureOffers(failure!)).toEqual({ retry: false, skip: false, change: false }) + expect(failure?.reference).toBeUndefined() + expect(created).toHaveBeenCalledTimes(1) + + await act(async () => { implementation.dismissRefusal() }) + expect(implementation.requestFailure).toBeUndefined() +}) + +test('any other typed refusal is said as a stopped start with its reference, never retried', async () => { + created.mockRejectedValueOnce(conflict('idempotency_conflict', 'Idempotency-Key was already used with a different request')) + await startOnce() + const failure = implementation.requestFailure + expect(failure).toMatchObject({ kind: 'blocked', title: buildCopy.failure.failed.implement, reason: buildCopy.failure.run.blocked, reference: { draftId: draft.id } }) + expect(failureOffers(failure!).retry).toBe(false) + // Only a refusal because of the proposal is taken back by the proposal moving on. + await act(async () => { implementation.dismissRefusal() }) + expect(implementation.requestFailure).toBeDefined() +}) diff --git a/web/src/features/build/implement/use-implementation.ts b/web/src/features/build/implement/use-implementation.ts index 9669896..b5a044a 100644 --- a/web/src/features/build/implement/use-implementation.ts +++ b/web/src/features/build/implement/use-implementation.ts @@ -6,7 +6,7 @@ import { BUILD_POLL_MS, buildDraftOptions, buildKeys } from '../../../api/querie import { POLL_INTERVAL_MS } from '../../../api/queries/shared' import { platformErrorEnvelope } from '../../../api/platform-error' import { getWorkspace, restartWorkspace } from '../../../api/workspace' -import { classifyBuildFailure, unconfirmedFailure, type BuildFailure } from '../../../model/build' +import { classifyBuildFailure, startConflictFailure, startRefusedFailure, unconfirmedFailure, type BuildFailure } from '../../../model/build' import { buildCopy } from '../../../model/build/copy' import { isBuildPending } from '../../../model/build/progress' import { isOneOf, jobState, knownValue, type BuildDraft, type ImplementationHandoff, type ImplementationRun } from '../../../model/contracts/build' @@ -38,12 +38,23 @@ export interface PreviewDatabaseReset { /** The latest run as far as an unconfirmed write is concerned: which run, and its state. */ const runMark = (run: ImplementationRun | undefined) => run ? `${run.id}/${knownValue(run.status) ?? 'unknown'}` : '' +/** + * A start Platform answered with a 409 without a reason, still to be decided by a draft read: the latest run before + * the start, Platform's text and the reference. Unlike a 2xx answer that could not be read, the start was not made + * by this request; a read decides whether another tab's start made a run. + */ +interface PlainConflict { + runBefore?: ImplementationRun + text: string + reference: NonNullable +} + /** Mutations only submit intent. Draft polling owns progress, even when no build tab is open. */ export function useImplementation({ projectId, draft, handoff, enabled }: ImplementationInput) { const queryClient = useQueryClient() const lock = useRef(false) const [pending, setPending] = useState(false) - const [requestFailure, setRequestFailure] = useState<{ draftId: string; failure: BuildFailure; runBefore?: string }>() + const [requestFailure, setRequestFailure] = useState<{ draftId: string; failure: BuildFailure; runBefore?: string; conflict?: PlainConflict }>() const run = draft.implementationRuns.at(-1) const projection = projectImplementation(draft, run, handoff) const workspaceId = run?.devWorkspaceId @@ -61,8 +72,9 @@ export function useImplementation({ projectId, draft, handoff, enabled }: Implem }) const previewUrl = workspace.data ? implementationPreviewUrl(workspace.data) : undefined const previewStatus = usePreviewReadiness(previewUrl) - // An unconfirmed write is settled by the draft read back: once it shows another run, or the run in another state, that is what happened. - const failure = requestFailure?.draftId === draft.id && !(requestFailure.failure.kind === 'unconfirmed' && runMark(run) !== requestFailure.runBefore) ? requestFailure.failure : undefined + // An unconfirmed write, or a start refused without Platform's reason, is settled by the draft read back: once it + // shows another run, or the run in another state, that is what happened. + const failure = requestFailure?.draftId === draft.id && !(requestFailure.runBefore !== undefined && runMark(run) !== requestFailure.runBefore) ? requestFailure.failure : undefined const state = { ...projection, previewUrl, @@ -82,6 +94,28 @@ export function useImplementation({ projectId, draft, handoff, enabled }: Implem onError: (error) => { if (isResponseContractError(error)) void queryClient.invalidateQueries({ queryKey: workspaceKey }) }, }) + /** + * Decides a plain 409 to a start by a draft read started now (a read already in flight may predate another tab's + * start, so it is cancelled, never reused): a new run is another tab's start, observed and not reported; none means + * Platform refused this start (a proposal being withdrawn or not matching). A read that fails decides nothing: the + * start is said as unconfirmed, and confirming it reads again and decides the same way. Never sends the start again. + */ + async function decideConflict(conflict: PlainConflict) { + const queryKey = buildDraftOptions(projectId, draft.id).queryKey + await queryClient.cancelQueries({ queryKey }) + let read: BuildDraft + try { + read = await api.getDraft(projectId, draft.id) + } catch { + setRequestFailure({ draftId: draft.id, failure: unconfirmedFailure(conflict.reference), runBefore: runMark(conflict.runBefore), conflict }) + return + } + queryClient.setQueryData(queryKey, read) + const latest = read.implementationRuns.at(-1) + if (latest && latest.id !== conflict.runBefore?.id) setRequestFailure(undefined) + else setRequestFailure({ draftId: draft.id, failure: startRefusedFailure(conflict.text, conflict.reference), runBefore: runMark(latest) }) + } + async function submit(payload?: api.ImplementationRunRequest): Promise { if (!enabled || lock.current || !state.tasks.length) return false lock.current = true @@ -115,8 +149,15 @@ export function useImplementation({ projectId, draft, handoff, enabled }: Implem const envelope = platformErrorEnvelope(error) const status = typeof error === 'object' && error !== null && 'status' in error && typeof error.status === 'number' ? error.status : envelope?.status if (status === 409) { - // Another tab won the start. Observe its run; do not create a second workspace. - await queryClient.invalidateQueries({ queryKey: options.queryKey }) + const refusal = startConflictFailure(envelope?.code, envelope?.message ?? '', reference, envelope?.details) + if (refusal) { + // Platform's typed refusal: said once and never retried; the draft read back shows nothing started. + await queryClient.invalidateQueries({ queryKey: options.queryKey }) + setRequestFailure({ draftId: draft.id, failure: refusal }) + return false + } + // No reason given: a draft read decides whether another tab started a run or Platform refused this start. + await decideConflict({ runBefore: current, text: envelope?.message ?? '', reference }) return false } const failedRun = queryClient.getQueryData(options.queryKey)?.implementationRuns.at(-1) ?? run @@ -145,8 +186,16 @@ export function useImplementation({ projectId, draft, handoff, enabled }: Implem requestFailure: failure, previewDatabaseReset, start: () => { if (projection.phase === 'idle' && !requestFailure) void submit() }, - /** After a write whose answer could not be read: reads the draft back; the notice leaves once it shows what happened. Never resends. */ - confirm: () => { void queryClient.invalidateQueries({ queryKey: buildDraftOptions(projectId, draft.id).queryKey }) }, + /** + * After a write whose answer could not be read: reads the draft back; the notice leaves once it shows what + * happened. After a plain 409 whose read-back failed: reads the draft again and decides that 409. Never resends. + */ + confirm: () => { + if (requestFailure?.conflict) void decideConflict(requestFailure.conflict) + else void queryClient.invalidateQueries({ queryKey: buildDraftOptions(projectId, draft.id).queryKey }) + }, + /** Takes back a start refused because of the proposal, once a fresh read shows it admits a run again. */ + dismissRefusal: () => setRequestFailure((current) => current?.failure.reasonCode === 'ProposalRunBlocked' || current?.failure.reasonCode === 'StartRefused' ? undefined : current), /** Starts every handoff task the latest run has not made, whatever that run's outcome (improvement sessions). */ startPending: () => { void submit() }, retry: () => { diff --git a/web/src/features/build/use-build-session.test.tsx b/web/src/features/build/use-build-session.test.tsx index 540fc67..5bef1fd 100644 --- a/web/src/features/build/use-build-session.test.tsx +++ b/web/src/features/build/use-build-session.test.tsx @@ -69,7 +69,7 @@ function implementationFixture() { return { state: { ...state, previewUrl: undefined, previewStatus: 'preparing' as const, retryPending: false }, pending: false, requestFailure: undefined, previewDatabaseReset: { busy: false, pending: false, error: undefined, reset: mock(async () => true) }, - start: mock(), confirm: mock(), startPending: mock(), retry: mock(), skipTask: mock(), requestChange: mock(async () => true), + start: mock(), confirm: mock(), dismissRefusal: mock(), startPending: mock(), retry: mock(), skipTask: mock(), requestChange: mock(async () => true), } } diff --git a/web/src/features/improve/conversation.tsx b/web/src/features/improve/conversation.tsx index d8c512d..e2c6cfc 100644 --- a/web/src/features/improve/conversation.tsx +++ b/web/src/features/improve/conversation.tsx @@ -26,7 +26,8 @@ export interface ImproveConversationProps { appUrl?: string locked: boolean starting: boolean - waitingForReview?: boolean + /** Why Platform starts no run under the session's proposal: no change can be started, the change card says why. */ + review?: ProposalHold outcome?: ReactNode sendFailure?: BuildFailure startFailure?: BuildFailure @@ -43,7 +44,7 @@ function readableActivity(tail: string | undefined): string[] { return activityLines(tail).filter(isProductLanguage) } -export const ImproveConversation = forwardRef(function ImproveConversation({ draft, state, appUrl, locked, waitingForReview, outcome, starting, sendFailure, startFailure, onSend, onRetrySend, onStart, onConfirmSend, onConfirmStart }, input) { +export const ImproveConversation = forwardRef(function ImproveConversation({ draft, state, appUrl, locked, review, outcome, starting, sendFailure, startFailure, onSend, onRetrySend, onStart, onConfirmSend, onConfirmStart }, input) { const scroller = useRef(null) const content = useRef(null) const following = useRef(true) @@ -81,7 +82,7 @@ export const ImproveConversation = forwardRef {answer?.role === 'assistant' ? : null} - {turn.id === state.proposalTurnId ? : null} + {turn.id === state.proposalTurnId ? : null} {isOneOf(turn.status, 'failed') ? submit(turn.userMessage) : undefined} /> : null} {turn.status.kind === 'unknown' ? : null} {isOneOf(turn.status, 'pending', 'running') ? @@ -132,7 +133,7 @@ export const ImproveConversation = forwardRef
- +
}) @@ -158,16 +159,28 @@ function FailureNotice({ failure, onRetry, onConfirm }: { failure: BuildFailure; } -/** The change the next run will make, with 「この内容で直す」 attached where it is read. */ -function ProposalCard({ tasks, starting, disabled, failure, onStart, onConfirm }: { tasks: ImproveTask[]; starting: boolean; disabled: boolean; failure?: BuildFailure; onStart(): void; onConfirm(): void }) { +/** Why no run starts under the proposal: it awaits review or apply, is closed, or could not be applied. */ +export type ProposalHold = 'waiting' | 'closed' | 'applyFailed' + +const HOLD_COPY = { waiting: 'proposalPending', closed: 'proposalClosed', applyFailed: 'proposalApplyFailed' } as const satisfies Record + +/** + * The change the next run will make, with 「この内容で直す」 attached where it is read. While Platform starts no run + * under the proposal, the card says why and what the user can do instead of offering the start. A start Platform + * refused is said once, without a retry. + */ +function ProposalCard({ tasks, starting, disabled, review, failure, onStart, onConfirm }: { tasks: ImproveTask[]; starting: boolean; disabled: boolean; review?: ProposalHold; failure?: BuildFailure; onStart(): void; onConfirm(): void }) { const readable = tasks.filter((task) => isProductLanguage(task.title)) + const held = review ? buildCopy.failure.run[HOLD_COPY[review]] : undefined return

{text.proposal.label}

{text.proposal.lead}

{readable.length ?
    {readable.map((task) =>
  • {task.title}{task.detail ? {task.detail} : null}
  • )}
: null} -
- -
- {failure ?
: null} + {held ? {held.reason} : <> +
+ +
+ {failure ?
: null} + }
} diff --git a/web/src/features/improve/copy.test.tsx b/web/src/features/improve/copy.test.tsx index ec7edc2..278e33e 100644 --- a/web/src/features/improve/copy.test.tsx +++ b/web/src/features/improve/copy.test.tsx @@ -7,7 +7,7 @@ import { isProductLanguage } from '../../model/build/wording' import { deriveImprove } from '../../model/improve' import { setLanguage } from '../../shell/language' import { buildCopy } from '../../model/build/copy' -import { unconfirmedFailure } from '../../model/build/failure' +import { startConflictFailure, unconfirmedFailure } from '../../model/build/failure' import { text as buildText } from '../build/copy' import { implementationCopy } from '../build/implement/copy' import { implementationTodoId } from '../build/implement/state' @@ -59,7 +59,7 @@ const draft: ApplicationDraft = { conversationTurns: [{ id: 't1', kind: 'conversation', status: 'succeeded', startedAt: at, finishedAt: at, devWorkspaceId: 'ws', userMessage: '状態で絞り込みたい', assistantMessage: '## 要約\nまとめました。\n## 次の質問\nこの内容で直せます。', suggestedReplies: ['この内容で直して'] }], } -function render(wire: ApplicationDraft, appUrl?: string, failures: Pick = {}) { +function render(wire: ApplicationDraft, appUrl?: string, failures: Partial> = {}) { const value = draftOf(wire) return renderToStaticMarkup( {}} onRetrySend={() => {}} onStart={() => {}} onConfirmSend={() => {}} onConfirmStart={() => {}} {...failures} />) } @@ -73,6 +73,29 @@ test('an unreadable send or start answer offers only 「最新の状態を確認 expect(html).toMatch(/]*disabled=""[^>]*>[^<]*この内容で直す<\/button>/) }) +// APT-1232: Platform starts no run while the proposal awaits review or is closed. +test.each(['ja', 'en'] as const)('a refused start is said once with no retry, and a waiting or closed proposal explains instead of offering 「この内容で直す」, in %s', (language) => { + setLanguage(language) + const apply = `${text.proposal.apply}` + const retryButton = `${buildText.conversation.retry}` + const refused = render(draft, undefined, { startFailure: startConflictFailure('source_change_proposal_run_blocked', 'source change proposal is awaiting review, applying, or closed', { draftId: draft.id, at }) }) + expect(refused).toContain(buildCopy.failure.run.proposalPending.title) + expect(refused).toContain(buildCopy.failure.run.proposalPending.reason) + expect(refused).not.toContain(retryButton) + expect(refused).not.toContain('source change proposal') + expect(refused).toMatch(new RegExp(`]*disabled=""[^>]*>[^<]*${text.proposal.apply}`)) + for (const [review, held] of [['waiting', buildCopy.failure.run.proposalPending], ['closed', buildCopy.failure.run.proposalClosed], ['applyFailed', buildCopy.failure.run.proposalApplyFailed]] as const) { + const html = render(draft, undefined, { review, locked: true }) + expect(html).toContain(held.title) + expect(html).toContain(held.reason) + expect(html).not.toContain(apply) + expect(html).not.toContain(retryButton) + expect(html).not.toContain('role="alert"') + } + // While the proposal is open again, the change is offered as before. + expect(render(draft)).toContain(apply) +}) + test('the proposal carries 「この内容で直す」 and the reply chips; a finished run shows its version and the app', () => { const proposed = render(draft) for (const word of ['変更案', '一覧に絞り込みを足す', '状態で絞り込めるようにする。', 'この内容で直す', 'この内容で直して']) expect(proposed).toContain(word) diff --git a/web/src/features/improve/improve-page.tsx b/web/src/features/improve/improve-page.tsx index 2f0309e..f5f1ca5 100644 --- a/web/src/features/improve/improve-page.tsx +++ b/web/src/features/improve/improve-page.tsx @@ -21,7 +21,6 @@ import { ImproveSidePane } from './side-pane' import { useImproveSession } from './use-improve-session' import { text as proposalText } from '../proposals/copy' import { ProposalOutcome, ProposalStatus } from '../proposals/proposal-ui' -import { proposalWaiting } from '../proposals/model' const PILL: Record = { asking: 'unfinished', proposed: 'unfinished', running: 'deploying', failed: 'failed', done: 'live', unsupported: 'unfinished' } @@ -89,7 +88,7 @@ function Session({ draft, stale }: { draft: BuildDraft; stale: ReactNode }) {
- : undefined} starting={implementation.pending} sendFailure={session.sendFailure} startFailure={implementation.requestFailure} onSend={session.send} onRetrySend={session.retrySend} onStart={implementation.startPending} onConfirmSend={session.confirmSend} onConfirmStart={implementation.confirm} /> + : undefined} starting={implementation.pending} sendFailure={session.sendFailure} startFailure={implementation.requestFailure} onSend={session.send} onRetrySend={session.retrySend} onStart={session.start} onConfirmSend={session.confirmSend} onConfirmStart={implementation.confirm} /> {session.proposal.error ? void session.proposal.refetch()} /> : null}
diff --git a/web/src/features/improve/refusal-session.test.tsx b/web/src/features/improve/refusal-session.test.tsx new file mode 100644 index 0000000..d3f2bc0 --- /dev/null +++ b/web/src/features/improve/refusal-session.test.tsx @@ -0,0 +1,136 @@ +// APT-1232: the improvement session's start admission follows Platform's (only a proposal being drafted or sent back +// for changes admits a run), and a refused start is taken back only when a read made after it shows the proposal +// changed and admitting a run again. +import { afterEach, beforeEach, expect, spyOn, test, type Mock } from 'bun:test' +import type { ApplicationDraft } from '@appthrust/api-schema/platform-api' +import { ORPCError } from '@orpc/client' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { preserveLanguage } from '../../../test/language' +import * as buildApi from '../../api/build' +import { getSourceChangeProposalContract } from '../../api/contracts/platform/proposal' +import { apiGateway } from '../../api/gateway' +import { buildDraftOptions } from '../../api/queries/build' +import { proposalKeys, proposalOptions } from '../../api/queries/proposal' +import { draftOf } from '../../api/testing/build-domain' +import { proposalOf, proposalWire } from '../../api/testing/proposal-domain' +import { POLL_INTERVAL_MS } from '../../api/queries/shared' +import type { BuildFailure } from '../../model/build/types' +import { setLanguage } from '../../shell/language' +import { useImproveSession } from './use-improve-session' + +const at = '2026-11-17T00:00:00Z' +const tasks = [{ title: '一覧に絞り込みを足す', description: '状態で絞り込めるようにする。', acceptanceCriteria: ['絞り込める'] }] +const wire: ApplicationDraft = { + id: 'draft-1', projectId: 'p1', kind: 'improvement', title: '見積作成', intent: '一覧に絞り込みを足したい', phase: 'created', + specMarkdown: '', architectureMarkdown: '', creationPlanGenerations: [], conversationTurns: [], creationExecutions: [], implementationRuns: [], createdSourceRepositories: [], + ownerUserId: 'owner', createdAt: at, updatedAt: at, createdApplicationId: 'mitsumori', createdApplicationStackId: 'mitsumori', proposalId: 'proposal-1', + creationPlan: { summary: '絞り込み', markdown: '# 絞り込み', representation: ['ApplicationStack'], implementationHandoff: { summary: '絞り込み', workspaceMode: 'application-develop', targetApplicationRef: 'createdApplicationId', sourceRepositoryStrategy: 'existing-source-repository', tasks } }, +} +const draft = draftOf(wire) +const sentBack = (count: number, updatedAt: string) => proposalWire({ + phase: 'ChangesRequested', updatedAt, + decisions: Array.from({ length: count }, (_, index) => ({ subject: 'sub-yamada', decision: 'RequestChanges', comment: `直してほしいこと ${index + 1}`, at })), +}) +const blocked = () => new ORPCError('CONFLICT', { status: 409, data: { body: { error: { code: 'source_change_proposal_run_blocked', message: 'source change proposal is awaiting review, applying, or closed' } } } }) + +let root: Root +let container: HTMLDivElement +let client: QueryClient +let restoreLanguage: () => void +let proposal: Record +let proposalReads: number +let spies: Mock<(...args: never[]) => unknown>[] +/** What the tests read from the session. */ +let session: { review?: string; reviewLocked: boolean; requestFailure?: BuildFailure; start(): void } + +function Harness() { + const value = useImproveSession('p1', draft) + session = { review: value.review, reviewLocked: value.reviewLocked, requestFailure: value.implementation.requestFailure, start: value.start } + return null +} + +async function settle() { + for (let index = 0; index < 8; index++) await act(async () => { await Bun.sleep(1) }) +} + +/** The next read of the proposal answers `next` (the page's poll, as the test drives it). */ +async function nextRead(next: Record) { + proposal = next + await act(async () => { await client.refetchQueries({ queryKey: proposalKeys.detail('p1', 'proposal-1') }) }) + await settle() +} + +beforeEach(async () => { + restoreLanguage = preserveLanguage() + setLanguage('ja') + proposalReads = 0 + proposal = sentBack(1, '2026-11-17T00:01:00Z') + spies = [ + spyOn(buildApi, 'createImplementationRun').mockRejectedValue(blocked()), + spyOn(buildApi, 'getDraft').mockResolvedValue(draft), + spyOn(apiGateway, 'platform').mockImplementation((async (contract: unknown) => { + if (contract !== getSourceChangeProposalContract) throw new Error('unexpected Platform call') + proposalReads++ + return proposalOf(proposal) + }) as typeof apiGateway.platform), + ] as unknown as Mock<(...args: never[]) => unknown>[] + client = new QueryClient({ defaultOptions: { queries: { retry: false } } }) + client.setQueryData(buildDraftOptions('p1', draft.id).queryKey, draft) + container = document.createElement('div') + document.body.append(container) + root = createRoot(container) + await act(async () => { root.render() }) + await settle() +}) + +afterEach(async () => { + await act(async () => { root.unmount() }) + container.remove() + client.clear() + for (const spy of spies) spy.mockRestore() + restoreLanguage() +}) + +test('a refusal is kept while reads show the same proposal, and taken back when a later read shows it sent back again', async () => { + expect(session.reviewLocked).toBe(false) + const before = proposalReads + await act(async () => { session.start() }) + await settle() + expect(session.requestFailure?.reasonCode).toBe('ProposalRunBlocked') + // The refusal made the session read the proposal again; the same proposal keeps it (its submission is pending, say). + expect(proposalReads).toBeGreaterThan(before) + await nextRead(sentBack(1, '2026-11-17T00:01:00Z')) + expect(session.requestFailure?.reasonCode).toBe('ProposalRunBlocked') + // Reviewed and sent back for changes again between two reads: the same phase, but not the same proposal. + await nextRead(sentBack(2, '2026-11-17T00:09:00Z')) + expect(session.requestFailure).toBeUndefined() + expect(session.reviewLocked).toBe(false) +}) + +test('the refusal is measured against the proposal as read when the start was requested, not when the refusal arrived', async () => { + // The start goes out while the proposal reads as sent back once; its answer comes later. + const answer = Promise.withResolvers() + spies[0]!.mockImplementationOnce((() => answer.promise) as never) + await act(async () => { session.start() }) + await settle() + // Meanwhile the owner reviewed it and sent it back again: Platform refused the start in between. + await nextRead(sentBack(2, '2026-11-17T00:09:00Z')) + await act(async () => { answer.reject(blocked()) }) + await settle() + // The proposal is no longer the one the start was requested under, and it admits a run: the next read takes the refusal back. + await nextRead(sentBack(2, '2026-11-17T00:09:00Z')) + expect(session.requestFailure).toBeUndefined() + expect(session.reviewLocked).toBe(false) +}) + +test('a proposal that could not be applied admits no start and says so, and keeps being read', async () => { + await nextRead(proposalWire({ phase: 'ApplyFailed' })) + expect(session.review).toBe('applyFailed') + expect(session.reviewLocked).toBe(true) + // Not closed: the page keeps reading it, as for a proposal awaiting review. + const query = client.getQueryCache().find({ queryKey: proposalKeys.detail('p1', 'proposal-1') })! + const interval = proposalOptions('p1', 'proposal-1').refetchInterval + expect(typeof interval === 'function' ? interval(query as never) : interval).toBe(POLL_INTERVAL_MS) +}) diff --git a/web/src/features/improve/review-lock.test.ts b/web/src/features/improve/review-lock.test.ts index 21b2c74..a0a9d41 100644 --- a/web/src/features/improve/review-lock.test.ts +++ b/web/src/features/improve/review-lock.test.ts @@ -1,22 +1,23 @@ -// The improvement session's review lock (use-improve-session.ts): while the -// session's proposal is unread, awaits review or apply, is closed, or is in a -// phase this console does not know, the session takes no new changes. +// The improvement session's admission (use-improve-session.ts): Platform starts a run only while the proposal is +// being drafted or was sent back for changes (platform-api application_draft_proposal.go +// admitImprovementImplementation); an unread proposal, one awaiting review or apply, one that could not be applied, +// a closed one and a phase this console does not know take no new changes. import { expect, test } from 'bun:test' import { proposalOf, proposalWire } from '../../api/testing/proposal-domain' import { isOneOf } from '../../model/contracts/build' -import { improvementLocked } from '../proposals/model' +import { improvementAdmitted } from '../proposals/model' const phase = (value: string) => proposalOf(proposalWire({ phase: value })).phase -test('an unknown phase locks the session and is never read as Applied or Drafting', () => { +test('an unknown phase is not admitted and is never read as Applied or Drafting', () => { const unknown = phase('Merging') - expect(improvementLocked(unknown)).toBe(true) + expect(improvementAdmitted(unknown)).toBe(false) expect(isOneOf(unknown, 'Applied')).toBe(false) expect(isOneOf(unknown, 'Drafting')).toBe(false) }) -test('an unread proposal, a waiting one and a closed one lock the session; a returned one does not', () => { - expect(improvementLocked(undefined)).toBe(true) - for (const value of ['Proposed', 'Accepted', 'Applying', 'Applied', 'Rejected', 'Withdrawn', 'Expired']) expect(improvementLocked(phase(value))).toBe(true) - for (const value of ['Drafting', 'ChangesRequested', 'ApplyFailed']) expect(improvementLocked(phase(value))).toBe(false) +test('only a proposal being drafted or sent back for changes is admitted, as Platform admits it', () => { + expect(improvementAdmitted(undefined)).toBe(false) + for (const value of ['Proposed', 'Accepted', 'Applying', 'ApplyFailed', 'Applied', 'Rejected', 'Withdrawn', 'Expired']) expect(improvementAdmitted(phase(value))).toBe(false) + for (const value of ['Drafting', 'ChangesRequested']) expect(improvementAdmitted(phase(value))).toBe(true) }) diff --git a/web/src/features/improve/use-improve-session.ts b/web/src/features/improve/use-improve-session.ts index 08b0f31..abb2abf 100644 --- a/web/src/features/improve/use-improve-session.ts +++ b/web/src/features/improve/use-improve-session.ts @@ -5,11 +5,11 @@ import * as api from '../../api/build' import { buildDraftOptions, buildKeys } from '../../api/queries/build' import { platformErrorEnvelope } from '../../api/platform-error' import { classifyBuildFailure, unconfirmedFailure, type BuildFailure } from '../../model/build' -import { isOneOf, type BuildDraft } from '../../model/contracts/build' +import { isOneOf, knownValue, type BuildDraft } from '../../model/contracts/build' import { deriveImprove } from '../../model/improve' import { useImplementation } from '../build/implement' -import { proposalOptions } from '../../api/queries/proposal' -import { improvementLocked } from '../proposals/model' +import { proposalKeys, proposalOptions } from '../../api/queries/proposal' +import { improvementAdmitted, proposalTerminal, proposalWaiting } from '../proposals/model' /** * Turns and runs are server-owned: sending a message only POSTs the turn and @@ -25,7 +25,36 @@ export function useImproveSession(projectId: string, draft: BuildDraft) { const implementation = useImplementation({ projectId, draft, handoff: draft.creationPlan?.implementationHandoff, enabled: !draft.creationPlanUnreadable }) const proposal = useQuery(proposalOptions(projectId, draft.proposalId)) const phase = proposal.data?.phase - const reviewLocked = !!draft.proposalId && improvementLocked(phase) + const reviewLocked = !!draft.proposalId && !improvementAdmitted(phase) + /** + * Why the session takes no new change: its proposal awaits review or apply, is closed, or could not be applied + * (ApplyFailed is not closed: the proposal keeps being read). + */ + const review = !draft.proposalId || !phase ? undefined + : proposalWaiting(phase) ? 'waiting' as const + : proposalTerminal(phase) ? 'closed' as const + : isOneOf(phase, 'ApplyFailed') ? 'applyFailed' as const : undefined + // A start Platform refused: read the proposal again, so the page says which holds. The refusal is taken back only + // when a read made after the start was requested shows the proposal changed since then and admitting a run again; + // reads of the same proposal (still drafting with its submission pending, say) keep it. The baseline is the + // proposal as read when 「この内容で直す」 was pressed, before the request went out. + const requestFailure = implementation.requestFailure + const refusal = requestFailure?.reasonCode === 'ProposalRunBlocked' || requestFailure?.reasonCode === 'StartRefused' ? requestFailure : undefined + const proposalMark = proposal.data ? [knownValue(proposal.data.phase) ?? 'unknown', proposal.data.updatedAt, proposal.data.decisions.length].join('|') : undefined + const requested = useRef<{ mark?: string; at: number }>(undefined) + const refusedWith = useRef<{ failure: BuildFailure; mark?: string; at: number }>(undefined) + const { dismissRefusal, startPending } = implementation + useEffect(() => { + if (!refusal || !draft.proposalId) { + refusedWith.current = undefined + return + } + if (refusedWith.current?.failure !== refusal) { + refusedWith.current = { failure: refusal, ...(requested.current ?? { mark: proposalMark, at: Date.now() }) } + void queryClient.invalidateQueries({ queryKey: proposalKeys.detail(projectId, draft.proposalId) }) + } + if (proposal.dataUpdatedAt > refusedWith.current.at && proposalMark !== refusedWith.current.mark && improvementAdmitted(phase)) dismissRefusal() + }) const applied = isOneOf(phase, 'Applied') // The controller applies first; release correlation updates the private draft later. useQuery({ @@ -76,7 +105,13 @@ export function useImproveSession(projectId: string, draft: BuildDraft) { state, proposal, reviewLocked, + review, implementation, + /** 「この内容で直す」 and a stopped run's retry: notes the proposal as read now, the baseline for a refusal. */ + start: () => { + requested.current = { mark: proposalMark, at: Date.now() } + startPending() + }, sending, sendFailure: sendFailure?.failure, /** Nothing can be sent while a turn or a run is in flight (or in an unknown state), or while a send or start request is out. */ diff --git a/web/src/features/proposals/model.ts b/web/src/features/proposals/model.ts index 9077a20..07b793f 100644 --- a/web/src/features/proposals/model.ts +++ b/web/src/features/proposals/model.ts @@ -13,12 +13,13 @@ export function proposalWaiting(phase: OpenValue): boolean { } /** - * Whether an improvement session with a proposal may not take new changes: - * the proposal is not read yet, awaits review or apply, is closed, or is in a - * phase this console does not know (never read as open for changes). + * Whether Platform starts an improvement run under this proposal: only while it is being drafted or was sent back + * for changes (platform-api application_draft_proposal.go `admitImprovementImplementation`). Not when it awaits + * review or apply, could not be applied (ApplyFailed, which is not closed), is closed, or is in a phase this + * console does not know. */ -export function improvementLocked(phase: OpenValue | undefined): boolean { - return !phase || phase.kind === 'unknown' || proposalWaiting(phase) || proposalTerminal(phase) +export function improvementAdmitted(phase: OpenValue | undefined): boolean { + return isOneOf(phase, 'Drafting', 'ChangesRequested') } /** diff --git a/web/src/model/build/copy.en.ts b/web/src/model/build/copy.en.ts index 8e7c13d..de5a61f 100644 --- a/web/src/model/build/copy.en.ts +++ b/web/src/model/build/copy.en.ts @@ -115,6 +115,7 @@ export const textEn: typeof textJa = { configuration: { title: 'A platform setting stopped the work', reason: 'This is not a problem with your actions. Share the support reference below with your administrator and ask them to fix the setting.' }, proposalPending: { title: 'Waiting for the proposal to be reviewed', reason: 'Work cannot continue while the app owner is reviewing the proposal. If they request changes, you can continue from there.' }, proposalClosed: { title: 'This proposal is closed', reason: 'It has been applied, declined, withdrawn or has expired, so work on it cannot continue. To keep improving the app, start again from “Improve with AI” on the app’s page.' }, + proposalApplyFailed: { title: 'The proposal could not be applied to the app', reason: 'The owner chose to apply it, but applying it to the app stopped. Work cannot continue on this proposal. Ask your administrator to look into it.' }, }, nameTaken: 'Name already in use', urlNameTaken: 'This URL name is used by another app', diff --git a/web/src/model/build/copy.ts b/web/src/model/build/copy.ts index b499b56..528e679 100644 --- a/web/src/model/build/copy.ts +++ b/web/src/model/build/copy.ts @@ -133,6 +133,11 @@ export const textJa = { proposalPending: { title: '提案の確認を待っています', reason: '所有者が提案を確認しているあいだは、作業を進められません。やり直しを求められたら、そこから続けられます。' }, /** A closed proposal stays closed; the user starts a new one from the app's 「AIで直す」 (improve/entry.tsx). */ proposalClosed: { title: 'この提案は締め切られています', reason: '反映・見送り・取り下げ・期限切れのどれかで終わっていて、この提案では続けられません。続けて直すときは、アプリの画面の「AIで直す」から始めてください。' }, + /** + * Accepted, but applying it to the app stopped (ApplyFailed). It is not closed, so 「AIで直す」 opens this session + * again, and no run starts under it: someone on the platform side has to look at it. + */ + proposalApplyFailed: { title: '提案をアプリに反映できませんでした', reason: '所有者が反映を決めたあと、アプリへの反映が止まりました。この提案のままでは作業を進められません。基盤の担当者に確認を依頼してください。' }, }, nameTaken: '置き場の名前がすでに使われています', urlNameTaken: 'URL の名前が別のアプリで使われています', diff --git a/web/src/model/build/failure.ts b/web/src/model/build/failure.ts index 989031e..7edfb74 100644 --- a/web/src/model/build/failure.ts +++ b/web/src/model/build/failure.ts @@ -17,6 +17,39 @@ export function unconfirmedFailure(reference?: BuildFailure['reference']): Build return { kind: 'unconfirmed', ...buildCopy.failure.unconfirmed, ...(reference ? { reference } : {}) } } +/** + * Platform's codes (and `details.reason`s) on a 409 to an implementation start that another request already made or + * is making: another tab's start (`conflict` without a reason, "implementation run is running") or the same request + * still being processed (`idempotency_in_progress`). An answer without Platform's code is read the same way. + */ +const CONCURRENT_START_CODES: Record = { conflict: true, idempotency_in_progress: true } + +/** + * A 409 to an implementation start as the screen tells it. `undefined`: another tab won the start; the draft read + * back shows its run. A typed refusal of this start is shown once and never retried; its `details.reason` comes + * before the code, so a generic `conflict` that names a refusal is one. `source_change_proposal_run_blocked` + * (platform-api application_draft_proposal.go `admitImprovementImplementation`: the improvement's proposal awaits + * review or apply, or is closed), as code or reason, is worded as the proposal awaiting review, the page's next read + * of the proposal says which; any other typed refusal says the start stopped, with its support reference. + */ +export function startConflictFailure(code: string | undefined, text: string, reference: NonNullable, details?: Record): BuildFailure | undefined { + const typed = typeof details?.reason === 'string' && details.reason ? details.reason : code + if (typed === undefined || Object.hasOwn(CONCURRENT_START_CODES, typed)) return undefined + const offers = { retry: false, skip: false, change: false } + if (typed === 'source_change_proposal_run_blocked') return { kind: 'blocked', reasonCode: 'ProposalRunBlocked', ...buildCopy.failure.run.proposalPending, offers, raw: text } + return { kind: 'blocked', title: buildCopy.failure.failed.implement, reason: buildCopy.failure.run.blocked, offers, reference, raw: text } +} + +/** + * A 409 to an implementation start without Platform's reason, after which the draft read back shows no new run: it + * was not another tab's start but a refusal of this one (platform-api answers a plain `conflict` for a proposal being + * withdrawn or not matching its draft, and for a draft that changed while the start was admitted). Said once; the + * start may be tried again, and the page's next reads say whether the proposal still admits it. + */ +export function startRefusedFailure(text: string, reference: NonNullable): BuildFailure { + return { kind: 'failed', reasonCode: 'StartRefused', title: buildCopy.failure.failed.implement, reason: buildCopy.failure.retry, raw: text, reference } +} + /** * Platform's repository destination stopped the creation before anything was made: it moved * (or the plan was bound to the current one, and the user approves again), it is not set, or the diff --git a/web/src/model/build/types.ts b/web/src/model/build/types.ts index c156fd2..4320b0c 100644 --- a/web/src/model/build/types.ts +++ b/web/src/model/build/types.ts @@ -117,7 +117,12 @@ export interface BuildFailure { */ recheck?: true suggestedName?: string - reasonCode?: 'PublishURLConflict' + /** + * `PublishURLConflict`: another publish holds the URL name. `ProposalRunBlocked`: Platform refused an improvement + * run because its proposal awaits review or apply, or is closed (failure.ts `startConflictFailure`). + * `StartRefused`: Platform refused a start without a reason and no other start was made (`startRefusedFailure`). + */ + reasonCode?: 'PublishURLConflict' | 'ProposalRunBlocked' | 'StartRefused' raw?: string /** Support correlation only; diagnostics stay in the advanced disclosure. */ reference?: { draftId: string; executionId?: string; at: string }