From a608312d4f186fb2ac46b4d0b40a5e1e45a9b0d0 Mon Sep 17 00:00:00 2001 From: reoring Date: Tue, 17 Nov 2026 23:11:27 +0900 Subject: [PATCH 1/4] Show refused improvement starts and app deletion refusals in the user's words (APT-1232, APT-1234) APT-1232: a start Platform refuses with a typed code (for example source_change_proposal_run_blocked while the proposal awaits review) is a visible refusal without retry instead of being taken for another tab's start; the genuine concurrent-start 409 still re-reads the draft. While a proposal waits for review or is closed, the change card explains instead of offering the start, and the proposal is read again after a refusal. APT-1234: deleting an app no longer shows Platform's English message. A 412 branch_has_active_delivery names the app's AI work areas still running and what to do; dependents_deleting and other retryable refusals are waited on (retryAfterSeconds, up to 120 s) and then explained. --- web/e2e/stories/app-delete.mock.spec.ts | 46 +++++++ .../improve-start-refused.mock.spec.ts | 89 ++++++++++++++ web/src/copy/apps.en.ts | 13 ++ web/src/copy/apps.ts | 18 +++ web/src/dev/mock-improve.test.ts | 3 +- web/src/dev/mock-platform.ts | 3 +- web/src/features/app/delete-dialog.test.ts | 57 +++++++++ web/src/features/app/delete-dialog.tsx | 53 +++++++- web/src/features/app/mutations.test.ts | 34 +++++ web/src/features/app/mutations.ts | 32 ++++- .../build/implement/start-refusal.test.tsx | 116 ++++++++++++++++++ .../build/implement/use-implementation.ts | 9 +- .../features/build/use-build-session.test.tsx | 2 +- web/src/features/improve/conversation.tsx | 28 +++-- web/src/features/improve/copy.test.tsx | 27 +++- web/src/features/improve/improve-page.tsx | 3 +- .../features/improve/use-improve-session.ts | 23 +++- web/src/model/build/failure.ts | 23 ++++ web/src/model/build/types.ts | 6 +- 19 files changed, 557 insertions(+), 28 deletions(-) create mode 100644 web/e2e/stories/improve-start-refused.mock.spec.ts create mode 100644 web/src/features/app/delete-dialog.test.ts create mode 100644 web/src/features/build/implement/start-refusal.test.tsx diff --git a/web/e2e/stories/app-delete.mock.spec.ts b/web/e2e/stories/app-delete.mock.spec.ts index 8ea5730..98f2148 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 whose AI work areas (from its build and its improvement sessions) are + // still running (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 AI 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\'s AI work areas are still running' }], async () => { + await confirm.click() + const refusal = dialog.getByRole('alert') + await expect(refusal).toContainText('このアプリはまだ使われているため、削除できませんでした') + await expect(refusal).toContainText('このアプリを AI で作ったときや直したときの作業場所が 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..cf757bf 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: 'This app is still in use, so it was not deleted', + workAreas: (count: number) => `${count === 1 ? '1 AI work area' : `${count} AI work areas`} from building or improving this app ${count === 1 ? 'is' : 'are'} still running.`, + workAreasNext: 'They cannot be stopped from this screen. Ask your administrator to clear them, then choose “Delete permanently” again.', + others: 'Something else connected to this app is still running.', + 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 AI work area' : `${count} AI 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..ce17b3b 100644 --- a/web/src/copy/apps.ts +++ b/web/src/copy/apps.ts @@ -296,6 +296,24 @@ export const apps = { deleteKeepsRepository: (repository?: string) => repository ? `GitHub の置き場(${repository})は消さずに残ります。` : 'GitHub の置き場は消さずに残ります。', deleteSourceBusy: 'アプリは止めましたが、置き場とのつながりをまだ外せていません。少し待ってから、もう一度「完全に削除する」を押してください。', + /** + * Platform refused the deletion: something of the app is still running (`inUse`; the AI work areas of its build + * and improvement sessions are named and counted, nothing in the console removes them) or is still being removed + * (`waiting`, after the console waited for it). Never Platform's own message. + */ + deleteRefused: { + inUse: 'このアプリはまだ使われているため、削除できませんでした', + workAreas: (count: number) => `このアプリを AI で作ったときや直したときの作業場所が ${count} か所、まだ動いています。`, + workAreasNext: 'この画面からは止められません。基盤の担当者に片づけてもらってから、もう一度「完全に削除する」を押してください。', + others: 'このアプリにつながっている、ほかの動いているものがまだ残っています。', + othersNext: '少し待ってから、もう一度「完全に削除する」を押してください。続くときは基盤の担当者に相談してください。', + waiting: '削除の準備がまだ終わっていません', + waitingWorkAreas: (count: number) => `このアプリの AI の作業場所 ${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..398cf37 100644 --- a/web/src/dev/mock-platform.ts +++ b/web/src/dev/mock-platform.ts @@ -2306,7 +2306,8 @@ 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): its own code, not `conflict`. + if (proposal && (proposalWaiting(proposal.phase) || proposalTerminal(proposal.phase))) 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..edaac6d --- /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 AI 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 wait that outlasted the deletion says what is being cleared and to try again, 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..5baf6f5 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 the AI work areas of an app's build and improvement sessions; 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: + * - 412 `branch_has_active_delivery` (platform-api application_branch.go `applicationBranchActiveDeliveryError`): + * what still runs, from `activeConsumers` (kind and count); AI work areas are named and counted, and since nothing + * here removes them, the user is told who can; + * - a refusal that only waits for something already being removed, still holding after the deletion waited for it + * (409 `dependents_deleting` with its `dependents`, or a `retryable` refusal): what is being cleared, and to try + * 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/app/mutations.test.ts b/web/src/features/app/mutations.test.ts index 506bbea..97b2c35 100644 --- a/web/src/features/app/mutations.test.ts +++ b/web/src/features/app/mutations.test.ts @@ -77,6 +77,40 @@ describe('deleteAppResources', () => { await deleteAppResources('commerce', progress, retry.value) expect(retry.calls).toEqual(['source:keihi-src', 'console:a-keihi']) }) + + // APT-1234: Platform's typed answers to the stack delete (platform-api application.go / writer_application_stack_selection.go). + const dependentsDeleting = (retryAfterSeconds?: number) => new ORPCError('CONFLICT', { status: 409, data: { body: { error: { + code: 'conflict', message: 'application "keihi" is waiting for dependents to finish deleting: devws-1', + details: { reason: 'dependents_deleting', dependents: [{ kind: 'DevWorkspace', id: 'devws-1', name: '経費精算' }], ...(retryAfterSeconds === undefined ? {} : { retryAfterSeconds }) }, + } } } }) + const activeDelivery = () => new ORPCError('PRECONDITION_FAILED', { status: 412, data: { body: { error: { + code: 'failed_precondition', message: 'application branch still has active delivery consumers', + details: { reason: 'branch_has_active_delivery', activeConsumers: [{ kind: 'DevWorkspace', count: 2 }] }, + } } } }) + + test('a stack delete waiting for what Platform is already removing is sent again after its retry time, then goes on', async () => { + let answers = [() => { throw dependentsDeleting(5) }, () => { throw dependentsDeleting() }, () => ({})] + const { value, calls } = deps([], () => { const [next, ...rest] = answers; answers = rest; return next!() }) + const waits: number[] = [] + const wait = value.wait! + value.wait = async (ms) => { waits.push(ms); await wait(ms) } + await deleteAppResources('commerce', deletion(), value) + expect(calls).toEqual(['stack:keihi', 'wait', 'stack:keihi', 'wait', 'stack:keihi', 'source:keihi-src', 'console:a-keihi']) + expect(waits).toEqual([5_000, 5_000]) + }) + + test('a stack delete still waiting after the bound fails with Platform\'s answer; a running blocker is never waited for', async () => { + const waiting = deps([], () => { throw dependentsDeleting(5) }) + const progress = deletion() + await expect(deleteAppResources('commerce', progress, waiting.value)).rejects.toBeInstanceOf(ORPCError) + expect(waiting.calls.filter((call) => call === 'wait').length).toBeGreaterThan(0) + expect(waiting.calls).not.toContain('source:keihi-src') + expect(progress.stackDeleted).toBeUndefined() + + const blocked = deps([], () => { throw activeDelivery() }) + await expect(deleteAppResources('commerce', deletion(), blocked.value)).rejects.toBeInstanceOf(ORPCError) + expect(blocked.calls).toEqual(['stack:keihi']) + }) }) describe('forgetDeletedApp', () => { diff --git a/web/src/features/app/mutations.ts b/web/src/features/app/mutations.ts index 70abff2..b79abb2 100644 --- a/web/src/features/app/mutations.ts +++ b/web/src/features/app/mutations.ts @@ -172,6 +172,23 @@ export class SourceStillReferencedError extends Error { const SOURCE_RELEASE_WAIT_MS = 120_000 const SOURCE_RELEASE_POLL_MS = 3_000 +/** How long the stack delete waits for what Platform is still removing (`dependents_deleting`) before saying so. */ +const STACK_RELEASE_WAIT_MS = 120_000 +const STACK_RELEASE_POLL_MS = 5_000 + +/** + * How long to wait before deleting the stack again, when Platform refused it only until something it is already + * removing is gone: 409 `dependents_deleting` (platform-api writer_application_stack_selection.go + * `applicationDependentsDeletingError`, with `retryAfterSeconds`) or any refusal marked `retryable`. Otherwise + * undefined: the refusal stands. + */ +function stackDeleteRetryAfterMs(error: unknown): number | undefined { + const details = platformErrorEnvelope(error)?.details + if (details?.reason !== 'dependents_deleting' && details?.retryable !== true) return undefined + const seconds = details.retryAfterSeconds + return typeof seconds === 'number' && seconds > 0 ? Math.min(seconds * 1000, 30_000) : STACK_RELEASE_POLL_MS +} + /** * Stack → its source repository binding → console record. The console record * is the index, so it goes last: a running app or a stray binding never loses @@ -181,10 +198,17 @@ export async function deleteAppResources(projectId: string, deletion: AppDeletio const wait = deps.wait ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))) const now = deps.now ?? Date.now if (deletion.stackId && !deletion.stackDeleted) { - try { - await deps.deleteStack(projectId, deletion.stackId) - } catch (error) { - if (!(error instanceof ORPCError && error.status === 404)) throw error + const deadline = now() + STACK_RELEASE_WAIT_MS + for (;;) { + try { + await deps.deleteStack(projectId, deletion.stackId) + break + } catch (error) { + if (error instanceof ORPCError && error.status === 404) break + const retryAfter = stackDeleteRetryAfterMs(error) + if (retryAfter === undefined || now() + retryAfter > deadline) throw error + await wait(retryAfter) + } } deletion.stackDeleted = true } 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..a6ef50d --- /dev/null +++ b/web/src/features/build/implement/start-refusal.test.tsx @@ -0,0 +1,116 @@ +// APT-1232: a 409 to an implementation start is either another tab's start (read back, never reported) or Platform's +// typed refusal of this start (said once, never retried). +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 +/** What the tests read from the hook: the start, its request failure, and taking a refusal back. */ +let implementation: { requestFailure?: BuildFailure; startPending(): 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') + 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() + restoreLanguage() +}) + +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 { code, details } of cases) { + created.mockRejectedValueOnce(conflict(code, 'implementation run is running', details)) + await startOnce() + expect(implementation.requestFailure).toBeUndefined() + } + expect(created).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..146d69a 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, 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' @@ -115,8 +115,11 @@ 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. + const refusal = startConflictFailure(envelope?.code, envelope?.message ?? '', reference, envelope?.details) + // Another tab won the start: observe its run; do not create a second workspace. A refusal (Platform's typed + // reason or code) is said once and never retried; the draft read back shows nothing started. await queryClient.invalidateQueries({ queryKey: options.queryKey }) + if (refusal) setRequestFailure({ draftId: draft.id, failure: refusal }) return false } const failedRun = queryClient.getQueryData(options.queryKey)?.implementationRuns.at(-1) ?? run @@ -147,6 +150,8 @@ export function useImplementation({ projectId, draft, handoff, enabled }: Implem 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 }) }, + /** Takes back a start Platform refused because of the proposal, once the proposal moved on: the start is offered again. */ + dismissRefusal: () => setRequestFailure((current) => current?.failure.reasonCode === 'ProposalRunBlocked' ? 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..d2f8e49 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 + /** The session's proposal awaits review or apply, or is closed: no change can be started, the change card says why. */ + review?: 'waiting' | 'closed' 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,23 @@ 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 }) { +/** + * The change the next run will make, with 「この内容で直す」 attached where it is read. While the proposal awaits review + * or is closed, Platform starts no run: 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?: 'waiting' | 'closed'; failure?: BuildFailure; onStart(): void; onConfirm(): void }) { const readable = tasks.filter((task) => isProductLanguage(task.title)) + const held = review ? buildCopy.failure.run[review === 'waiting' ? 'proposalPending' : 'proposalClosed'] : 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..f1c11e2 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]] 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..19cb81b 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={implementation.startPending} onConfirmSend={session.confirmSend} onConfirmStart={implementation.confirm} /> {session.proposal.error ? void session.proposal.refetch()} /> : null}
diff --git a/web/src/features/improve/use-improve-session.ts b/web/src/features/improve/use-improve-session.ts index 08b0f31..0a4daaf 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 { improvementLocked, proposalTerminal, proposalWaiting } from '../proposals/model' /** * Turns and runs are server-owned: sending a message only POSTs the turn and @@ -26,6 +26,22 @@ export function useImproveSession(projectId: string, draft: BuildDraft) { const proposal = useQuery(proposalOptions(projectId, draft.proposalId)) const phase = proposal.data?.phase const reviewLocked = !!draft.proposalId && improvementLocked(phase) + /** Why the session takes no new change: its proposal awaits review or apply, or is closed. */ + const review = !draft.proposalId || !phase ? undefined : proposalWaiting(phase) ? 'waiting' as const : proposalTerminal(phase) ? 'closed' as const : undefined + // Platform refused a start because of the proposal: read the proposal again, so the page says which holds. + const refused = implementation.requestFailure?.reasonCode === 'ProposalRunBlocked' + useEffect(() => { + if (refused) void queryClient.invalidateQueries({ queryKey: proposalKeys.detail(projectId, draft.proposalId) }) + }, [refused, queryClient, projectId, draft.proposalId]) + // Once the proposal moves on, that refusal no longer holds: sent back for changes, the change can be started again. + const phaseWord = phase ? knownValue(phase) ?? 'unknown' : undefined + const seenPhase = useRef(phaseWord) + const { dismissRefusal } = implementation + useEffect(() => { + if (seenPhase.current === phaseWord) return + seenPhase.current = phaseWord + dismissRefusal() + }, [phaseWord, dismissRefusal]) const applied = isOneOf(phase, 'Applied') // The controller applies first; release correlation updates the private draft later. useQuery({ @@ -76,6 +92,7 @@ export function useImproveSession(projectId: string, draft: BuildDraft) { state, proposal, reviewLocked, + review, implementation, sending, sendFailure: sendFailure?.failure, diff --git a/web/src/model/build/failure.ts b/web/src/model/build/failure.ts index 989031e..7350d8a 100644 --- a/web/src/model/build/failure.ts +++ b/web/src/model/build/failure.ts @@ -17,6 +17,29 @@ 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 } +} + /** * 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..e2cf403 100644 --- a/web/src/model/build/types.ts +++ b/web/src/model/build/types.ts @@ -117,7 +117,11 @@ 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`). + */ + reasonCode?: 'PublishURLConflict' | 'ProposalRunBlocked' raw?: string /** Support correlation only; diagnostics stay in the advanced disclosure. */ reference?: { draftId: string; executionId?: string; at: string } From a295b51fa79b124ea58d5d478a02025ae12c0814 Mon Sep 17 00:00:00 2001 From: reoring Date: Wed, 18 Nov 2026 06:32:22 +0900 Subject: [PATCH 2/4] Make app deletion one cancellable operation and align start refusals with Platform (APT-1232, APT-1234) Review follow-up (probe-astra round 1): - App deletion (stack DELETE, waits, source binding DELETE, console record) runs under one AbortSignal; deleting again aborts the earlier run, leaving the page aborts it, and the dialog can be closed while deleting. - One Idempotency-Key per deletion, sent on every retry of the stack DELETE. - The 120 s deadline is checked before every send and each DELETE is aborted when time runs out. - Improvement starts are admitted only in Drafting and ChangesRequested, as Platform does; ApplyFailed explains that the proposal could not be applied and keeps polling. - A plain 409 conflict on start re-reads the draft and shows a refusal unless another tab's run appeared; a refusal clears only when a fresh read after it shows a different proposal that admits a run. - Deletion copy says the app still has work areas left (no 'running'). --- web/e2e/stories/app-delete.mock.spec.ts | 55 ++++++-- web/src/api/queries/app.ts | 11 +- web/src/copy/apps.en.ts | 10 +- web/src/copy/apps.ts | 16 +-- web/src/dev/mock-platform.ts | 5 +- web/src/features/app/app-page-wire.test.tsx | 18 +++ web/src/features/app/delete-dialog.test.ts | 6 +- web/src/features/app/delete-dialog.tsx | 41 +++--- web/src/features/app/mutations.test.ts | 93 ++++++++++---- web/src/features/app/mutations.ts | 109 +++++++++++++--- .../build/implement/start-refusal.test.tsx | 25 +++- .../build/implement/use-implementation.ts | 26 ++-- web/src/features/improve/conversation.tsx | 19 ++- web/src/features/improve/copy.test.tsx | 2 +- .../features/improve/refusal-session.test.tsx | 120 ++++++++++++++++++ web/src/features/improve/review-lock.test.ts | 21 +-- .../features/improve/use-improve-session.ts | 44 ++++--- web/src/features/proposals/model.ts | 11 +- web/src/model/build/copy.en.ts | 1 + web/src/model/build/copy.ts | 5 + web/src/model/build/failure.ts | 10 ++ web/src/model/build/types.ts | 3 +- web/src/ui/overlay.tsx | 7 +- 23 files changed, 516 insertions(+), 142 deletions(-) create mode 100644 web/src/features/improve/refusal-session.test.tsx diff --git a/web/e2e/stories/app-delete.mock.spec.ts b/web/e2e/stories/app-delete.mock.spec.ts index 98f2148..1e081fe 100644 --- a/web/e2e/stories/app-delete.mock.spec.ts +++ b/web/e2e/stories/app-delete.mock.spec.ts @@ -71,10 +71,10 @@ test.describe('App delete @app', () => { await expect(page.getByRole('heading', { level: 1, name: app.name, exact: true })).toHaveCount(0) }) - // APT-1234: Platform refuses to delete an app whose AI work areas (from its build and its improvement sessions) are - // still running (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 AI work areas says what blocks it and what to do, never the platform\'s message @mock @story', async ({ page, mock }, testInfo) => { + // 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}` @@ -97,12 +97,12 @@ test.describe('App delete @app', () => { 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\'s AI work areas are still running' }], async () => { + 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('このアプリを AI で作ったときや直したときの作業場所が 2 か所、まだ動いています。') - await expect(refusal).toContainText('この画面からは止められません。基盤の担当者に片づけてもらってから、もう一度「完全に削除する」を押してください。') + 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]) @@ -115,4 +115,43 @@ test.describe('App delete @app', () => { await expect(page).toHaveURL(`/${app.groupPath}`) await expect(page.getByRole('main').getByRole('link', { name: new RegExp(app.name) })).toHaveCount(0) }) + + // APT-1234: while Platform only waits for what it is already removing (409 `dependents_deleting`), the deletion + // sends the same stack delete again, with the same Idempotency-Key, after the retry time. Closing the dialog stops + // it: nothing more is sent and the app stays. + test('a deletion waiting for what Platform is removing resends with the same key, and closing the dialog stops it @mock @story', async ({ page, mock }) => { + void mock + const app = seed.apps.keihi + const stackPath = `/api/v1/projects/${seed.projectId}/application-stacks/${app.slug}` + const keys: (string | null)[] = [] + await page.route(`**${stackPath}`, async (route: Route) => { + if (route.request().method() !== 'DELETE') return route.continue() + keys.push(await route.request().headerValue('idempotency-key')) + return route.fulfill({ status: 409, json: { error: { code: 'conflict', message: 'application "keihi" is waiting for dependents to finish deleting: devws-1', details: { + reason: 'dependents_deleting', retryAfterSeconds: 2, dependents: [{ kind: 'DevWorkspace', id: 'devws-1', name: app.name }], + } } } }) + }) + + 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) + + await withExpectedFailures([{ method: 'DELETE', path: stackPath, status: 409, count: 2, reason: 'Platform waits for the app\'s work areas to finish deleting' }], async () => { + await dialog.getByRole('button', { name: '完全に削除する', exact: true }).click() + await expect(dialog.getByRole('button', { name: '削除しています…', exact: true })).toBeVisible() + await expect.poll(() => keys.length, { timeout: 10_000 }).toBe(2) + // Still waiting: the dialog can be closed, and closing stops the deletion. + await dialog.getByRole('button', { name: 'キャンセル', exact: true }).click() + await expect(dialog).toHaveCount(0) + }) + expect(keys[0]).toBeTruthy() + expect(keys[1]).toBe(keys[0]) + // Past the next retry time: nothing more was sent, and the app is still there. + await page.waitForTimeout(3_000) + expect(keys).toHaveLength(2) + await expect(page.getByRole('heading', { level: 1, name: app.name, exact: true })).toBeVisible() + }) }) diff --git a/web/src/api/queries/app.ts b/web/src/api/queries/app.ts index 8675ea9..422947a 100644 --- a/web/src/api/queries/app.ts +++ b/web/src/api/queries/app.ts @@ -18,7 +18,7 @@ import { rollbackComponentContract, updateComponentConfigContract, } from '../contracts/platform/app' -import { apiGateway, type ApiGateway } from '../gateway' +import { apiGateway, type ApiGateway, type PlatformCallOptions } from '../gateway' import { keys, POLL_INTERVAL_MS } from './shared' async function listAllComponentSummaries(projectId: string, signal?: AbortSignal): Promise { @@ -118,12 +118,13 @@ export function updateEnvVars(scope: ComponentScope, variables: EnvVariable[]): return apiGateway.platform(updateComponentConfigContract, { params: scope, body: { variables } }) } -export function deleteApplicationStack(projectId: string, id: string): Promise { - return apiGateway.platform(deleteApplicationStackContract, { params: { projectId, id } }) +/** A stack delete; a caller retrying the same deletion sends the same `idempotencyKey`, and `signal` cancels it. */ +export function deleteApplicationStack(projectId: string, id: string, options?: PlatformCallOptions): Promise { + return apiGateway.platform(deleteApplicationStackContract, { params: { projectId, id } }, options) } -export function deleteApplicationSourceRepository(projectId: string, id: string): Promise { - return apiGateway.platform(deleteApplicationSourceRepositoryContract, { params: { projectId, id } }) +export function deleteApplicationSourceRepository(projectId: string, id: string, options?: PlatformCallOptions): Promise { + return apiGateway.platform(deleteApplicationSourceRepositoryContract, { params: { projectId, id } }, options) } export function isLogsForbidden(error: unknown): boolean { diff --git a/web/src/copy/apps.en.ts b/web/src/copy/apps.en.ts index cf757bf..185fe4a 100644 --- a/web/src/copy/apps.en.ts +++ b/web/src/copy/apps.en.ts @@ -283,13 +283,13 @@ export const appsEn: typeof apps = { 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: 'This app is still in use, so it was not deleted', - workAreas: (count: number) => `${count === 1 ? '1 AI work area' : `${count} AI work areas`} from building or improving this app ${count === 1 ? 'is' : 'are'} still running.`, - workAreasNext: 'They cannot be stopped from this screen. Ask your administrator to clear them, then choose “Delete permanently” again.', - others: 'Something else connected to this app is still running.', + 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 AI work area' : `${count} AI work areas`} of this app ${count === 1 ? 'is' : 'are'} being cleared.`, + 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', diff --git a/web/src/copy/apps.ts b/web/src/copy/apps.ts index ce17b3b..7810f89 100644 --- a/web/src/copy/apps.ts +++ b/web/src/copy/apps.ts @@ -297,18 +297,18 @@ export const apps = { repository ? `GitHub の置き場(${repository})は消さずに残ります。` : 'GitHub の置き場は消さずに残ります。', deleteSourceBusy: 'アプリは止めましたが、置き場とのつながりをまだ外せていません。少し待ってから、もう一度「完全に削除する」を押してください。', /** - * Platform refused the deletion: something of the app is still running (`inUse`; the AI work areas of its build - * and improvement sessions are named and counted, nothing in the console removes them) or is still being removed - * (`waiting`, after the console waited for it). Never Platform's own message. + * 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`, after the console waited for it). Never Platform's own message. */ deleteRefused: { - inUse: 'このアプリはまだ使われているため、削除できませんでした', - workAreas: (count: number) => `このアプリを AI で作ったときや直したときの作業場所が ${count} か所、まだ動いています。`, - workAreasNext: 'この画面からは止められません。基盤の担当者に片づけてもらってから、もう一度「完全に削除する」を押してください。', - others: 'このアプリにつながっている、ほかの動いているものがまだ残っています。', + inUse: 'このアプリにはまだ残っているものがあるため、削除できませんでした', + workAreas: (count: number) => `このアプリの作業場所が ${count} か所残っています。`, + workAreasNext: 'この画面からは片づけられません。基盤の担当者に片づけてもらってから、もう一度「完全に削除する」を押してください。', + others: 'このアプリにつながっている、ほかのものがまだ残っています。', othersNext: '少し待ってから、もう一度「完全に削除する」を押してください。続くときは基盤の担当者に相談してください。', waiting: '削除の準備がまだ終わっていません', - waitingWorkAreas: (count: number) => `このアプリの AI の作業場所 ${count} か所を片づけています。`, + waitingWorkAreas: (count: number) => `このアプリの作業場所 ${count} か所を片づけています。`, waitingOthers: 'このアプリにつながっているものを片づけています。', waitingNext: '少し待ってから、もう一度「完全に削除する」を押してください。', failed: '削除できませんでした', diff --git a/web/src/dev/mock-platform.ts b/web/src/dev/mock-platform.ts index 398cf37..12aa22f 100644 --- a/web/src/dev/mock-platform.ts +++ b/web/src/dev/mock-platform.ts @@ -2306,8 +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 - // Like platform-api (application_draft_proposal.go admitImprovementImplementation): its own code, not `conflict`. - if (proposal && (proposalWaiting(proposal.phase) || proposalTerminal(proposal.phase))) return error(409, 'source_change_proposal_run_blocked', 'source change proposal is awaiting review, applying, or 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/app-page-wire.test.tsx b/web/src/features/app/app-page-wire.test.tsx index dd47cbe..33c73f2 100644 --- a/web/src/features/app/app-page-wire.test.tsx +++ b/web/src/features/app/app-page-wire.test.tsx @@ -710,6 +710,24 @@ test.each(['stack', 'build'] as const)('delete and discard hooks refuse an unrea expect(requests.filter((item) => item.method !== 'GET')).toEqual([]) }) +// APT-1234: a deletion waiting for what Platform is still removing stops when its page goes away. +test('leaving the page while the deletion waits sends no further delete', async () => { + rewrites.push({ method: 'DELETE', path: STACK, once: false, body: () => Response.json({ error: { + code: 'conflict', message: 'application "mitsumori" is waiting for dependents to finish deleting', + details: { reason: 'dependents_deleting', retryAfterSeconds: 1, dependents: [{ kind: 'DevWorkspace', id: 'devws-1', name: '見積作成' }] }, + } }, { status: 409 }) }) + await renderApp('overview', 'deletion-probe') + await click(button('Attempt delete')) + await settle() + expect(count('DELETE', STACK)).toBe(1) + await act(async () => { root!.unmount() }) + root = undefined + // Past the retry time: an orphaned wait would have sent the delete again by now. + await Bun.sleep(1_500) + expect(count('DELETE', STACK)).toBe(1) + expect(requests.filter((item) => item.method === 'DELETE' && !STACK.test(item.path))).toEqual([]) +}) + test.each(['improve', 'repair'] as const)('an unreadable draft row does not block a new %s', async (entry) => { await mockFetch('/api/v1/__mock/codex', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ available: true }) }) rewrites.push({ method: 'GET', path: new RegExp(`^${PROJECT}/application-drafts$`), once: false, body: () => ({ data: [{ ...storedDraftWire, id: 'unreadable-row', createdAt: 'not-a-date' }] }) }) diff --git a/web/src/features/app/delete-dialog.test.ts b/web/src/features/app/delete-dialog.test.ts index edaac6d..f7f2d15 100644 --- a/web/src/features/app/delete-dialog.test.ts +++ b/web/src/features/app/delete-dialog.test.ts @@ -6,6 +6,7 @@ import { ResponseContractError } from '../../api/boundary' import { copy } from '../../copy' import { setLanguage } from '../../shell/language' import { deletionRefusal } from './delete-dialog' +import { DeletionWaitExpiredError } from './mutations' let restoreLanguage: () => void beforeEach(() => { restoreLanguage = preserveLanguage() }) @@ -20,7 +21,7 @@ const said = (error: unknown) => { return refusal ? [refusal.title, ...refusal.lines].join(' ') : '' } -test.each(['ja', 'en'] as const)('remaining AI work areas are named and counted, with who can clear them, in %s', (language) => { +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] }) @@ -42,6 +43,9 @@ test.each(['ja', 'en'] as const)('a wait that outlasted the deletion says what i 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') + // The deletion's own time ran out: Platform's last answer names what is being cleared; without one, the general words. + expect(deletionRefusal(new DeletionWaitExpiredError(deleting([{ kind: 'DevWorkspace', id: 'devws-1', name: '経費精算' }])))).toEqual({ title: words.waiting, lines: [words.waitingWorkAreas(1), words.waitingNext] }) + expect(deletionRefusal(new DeletionWaitExpiredError())).toEqual({ title: words.waiting, lines: [words.waitingOthers, words.waitingNext] }) }) test('any other Platform refusal says it was not deleted without Platform\'s message; what ActionError owns is left to it', () => { diff --git a/web/src/features/app/delete-dialog.tsx b/web/src/features/app/delete-dialog.tsx index 5baf6f5..fcb0901 100644 --- a/web/src/features/app/delete-dialog.tsx +++ b/web/src/features/app/delete-dialog.tsx @@ -8,7 +8,7 @@ import type { AppView } from '../../model/app' import type { BusinessApp } from '../../model/contracts/console' import { ConfirmDialog, Notice } from '../../ui' import { text } from './copy' -import { SourceStillReferencedError, useDeleteApp } from './mutations' +import { DeletionCancelledError, DeletionWaitExpiredError, SourceStillReferencedError, useDeleteApp } from './mutations' import { UnconfirmedNotice, useWriteConfirmation } from './notices' import { repositoryNameOf, sourceRepositoryIdFor, type SourceRepositoryRef } from './platform' @@ -24,7 +24,7 @@ export interface DeletionRefusal { lines: string[] } -/** Platform's kind for the AI work areas of an app's build and improvement sessions; other kinds are not named. */ +/** 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[] { @@ -34,19 +34,25 @@ function entries(value: unknown): Record[] { /** * A deletion Platform refused, in the user's words: * - 412 `branch_has_active_delivery` (platform-api application_branch.go `applicationBranchActiveDeliveryError`): - * what still runs, from `activeConsumers` (kind and count); AI work areas are named and counted, and since nothing - * here removes them, the user is told who can; - * - a refusal that only waits for something already being removed, still holding after the deletion waited for it - * (409 `dependents_deleting` with its `dependents`, or a `retryable` refusal): what is being cleared, and to try - * again shortly; + * 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; + * - a deletion whose time ran out while Platform only waited for what it is already removing (409 + * `dependents_deleting` with its `dependents`, or a `retryable` refusal; DeletionWaitExpiredError): what is being + * cleared, and to try 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 { + const words = copy.app.settings.deleteRefused + const waiting = (details: Record | undefined): DeletionRefusal => { + 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] } + } + if (error instanceof DeletionWaitExpiredError) return waiting(platformErrorEnvelope(error.refusal)?.details) 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) @@ -57,11 +63,7 @@ export function deletionRefusal(error: unknown): DeletionRefusal | undefined { 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] } - } + if (details?.reason === 'dependents_deleting' || details?.retryable === true) return waiting(details) return { title: words.failed, lines: [envelope.status === 403 ? copy.errors.forbidden : words.failedNext] } } @@ -83,10 +85,12 @@ 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) + // Closing the dialog stopped the deletion: nothing to report. + const error = mutation.error instanceof DeletionCancelledError ? null : mutation.error + const busy = error instanceof SourceStillReferencedError + const refusal = busy ? undefined : deletionRefusal(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([ + const confirmation = useWriteConfirmation([error], mutation.reset, () => Promise.all([ queryClient.refetchQueries({ queryKey: consoleKeys.app(app.id) }), ...[keys.stacks, keys.applications, keys.sourceRepositories].map((key) => queryClient.refetchQueries({ queryKey: key(projectId) })), ])) @@ -95,6 +99,8 @@ export function DeleteAppDialog({ { + // Closing stops a deletion still sending or waiting; what it already deleted stays deleted. + if (!next) mutation.cancel() if (!next && !confirmation.unconfirmed) mutation.reset() onOpenChange(next) }} @@ -112,8 +118,9 @@ export function DeleteAppDialog({ confirmText={app.displayName} onConfirm={() => mutation.mutate()} pending={mutation.isPending} + closableWhilePending disabled={confirmation.unconfirmed} - error={busy || refusal || confirmation.unconfirmed ? undefined : mutation.error ?? undefined} + error={busy || refusal || confirmation.unconfirmed ? undefined : error ?? undefined} /> ) } diff --git a/web/src/features/app/mutations.test.ts b/web/src/features/app/mutations.test.ts index 97b2c35..1e93907 100644 --- a/web/src/features/app/mutations.test.ts +++ b/web/src/features/app/mutations.test.ts @@ -3,18 +3,24 @@ import { ORPCError } from '@orpc/client' import { QueryClient } from '@tanstack/react-query' import { consoleKeys } from '../../api/queries/console' import { keys } from '../../api/queries/shared' -import { deleteAppResources, forgetDeletedApp, readsDeletedApp, SourceStillReferencedError, type AppDeletion, type AppDeletionDeps } from './mutations' +import { deleteAppResources, DeletionWaitExpiredError, forgetDeletedApp, readsDeletedApp, SourceStillReferencedError, type AppDeletion, type AppDeletionDeps } from './mutations' const notFound = () => new ORPCError('NOT_FOUND', { status: 404 }) const referenced = (stackIds: string[]) => new ORPCError('CONFLICT', { status: 409, data: { body: { error: { code: 'conflict', message: 'referenced', details: { reason: 'referenced_by_stack', stackIds } } } } }) -function deps(source: Array<() => unknown> = [], stack: () => unknown = () => ({})) { +/** Fake Platform and clock: every send, wait and request timeout is recorded; `onWait` runs inside a wait. */ +function deps(source: Array<() => unknown> = [], stack: () => unknown = () => ({}), onWait?: () => void) { const calls: string[] = [] + const keys: string[] = [] + const timeouts: number[] = [] + const waits: number[] = [] let clock = 0 + let minted = 0 const value: AppDeletionDeps = { - deleteStack: async (_projectId, id) => { + deleteStack: async (_projectId, id, options) => { calls.push(`stack:${id}`) + keys.push(options.idempotencyKey) return stack() }, deleteSourceRepository: async (_projectId, id) => { @@ -23,58 +29,69 @@ function deps(source: Array<() => unknown> = [], stack: () => unknown = () => ({ return next ? next() : {} }, removeApp: async (appId) => void calls.push(`console:${appId}`), - wait: async (ms) => { + wait: async (ms, signal) => { calls.push('wait') + waits.push(ms) clock += ms + onWait?.() + signal.throwIfAborted() }, now: () => clock, + timeout: (ms) => { + timeouts.push(ms) + return new AbortController().signal + }, + newKey: () => `key-${++minted}`, } - return { value, calls } + return { value, calls, keys, timeouts, waits, advance: (ms: number) => { clock += ms } } } const deletion = (): AppDeletion => ({ appId: 'a-keihi', stackId: 'keihi', sourceRepositoryId: 'keihi-src' }) +const run = (value: AppDeletionDeps, item = deletion(), signal = new AbortController().signal) => deleteAppResources('commerce', item, value, signal) describe('deleteAppResources', () => { test('stack, then its source binding, then the console record', async () => { const { value, calls } = deps() - await deleteAppResources('commerce', deletion(), value) + await run(value) expect(calls).toEqual(['stack:keihi', 'source:keihi-src', 'console:a-keihi']) }) test('already-deleted stack or binding (404) does not stop the delete', async () => { const { value, calls } = deps([() => { throw notFound() }], () => { throw notFound() }) - await deleteAppResources('commerce', deletion(), value) + await run(value) expect(calls).toEqual(['stack:keihi', 'source:keihi-src', 'console:a-keihi']) }) test('image apps and drafts have no binding to delete', async () => { const { value, calls } = deps() - await deleteAppResources('commerce', { appId: 'a-nippo', stackId: 'nippo' }, value) - await deleteAppResources('commerce', { appId: 'a-draft' }, value) + await run(value, { appId: 'a-nippo', stackId: 'nippo' }) + await run(value, { appId: 'a-draft' }) expect(calls).toEqual(['stack:nippo', 'console:a-nippo', 'console:a-draft']) }) test('waits while only the deleted stack still references the binding (GitOps prune)', async () => { const { value, calls } = deps([() => { throw referenced(['keihi']) }, () => { throw referenced(['keihi']) }, () => ({})]) - await deleteAppResources('commerce', deletion(), value) + await run(value) expect(calls).toEqual(['stack:keihi', 'source:keihi-src', 'wait', 'source:keihi-src', 'wait', 'source:keihi-src', 'console:a-keihi']) }) test('a binding another stack uses fails the delete and keeps the console record', async () => { const { value, calls } = deps([() => { throw referenced(['keihi', 'other']) }]) - await expect(deleteAppResources('commerce', deletion(), value)).rejects.toBeInstanceOf(ORPCError) + await expect(run(value)).rejects.toBeInstanceOf(ORPCError) expect(calls).toEqual(['stack:keihi', 'source:keihi-src']) }) test('a binding still referenced after the wait asks for a retry, which goes on from the binding', async () => { const stuck = deps([() => { throw referenced(['keihi']) }]) const progress = deletion() - await expect(deleteAppResources('commerce', progress, stuck.value)).rejects.toBeInstanceOf(SourceStillReferencedError) + await expect(run(stuck.value, progress)).rejects.toBeInstanceOf(SourceStillReferencedError) expect(stuck.calls).not.toContain('console:a-keihi') expect(progress.stackDeleted).toBe(true) + // No send after the binding's time ran out: the last wait ended before it. + expect(stuck.waits.reduce((sum, ms) => sum + ms, 0)).toBeLessThan(120_000) const retry = deps() - await deleteAppResources('commerce', progress, retry.value) + await run(retry.value, progress) expect(retry.calls).toEqual(['source:keihi-src', 'console:a-keihi']) }) @@ -88,29 +105,57 @@ describe('deleteAppResources', () => { details: { reason: 'branch_has_active_delivery', activeConsumers: [{ kind: 'DevWorkspace', count: 2 }] }, } } } }) - test('a stack delete waiting for what Platform is already removing is sent again after its retry time, then goes on', async () => { + test('a stack delete waiting for what Platform is already removing is sent again after its retry time with the same key, then goes on', async () => { let answers = [() => { throw dependentsDeleting(5) }, () => { throw dependentsDeleting() }, () => ({})] - const { value, calls } = deps([], () => { const [next, ...rest] = answers; answers = rest; return next!() }) - const waits: number[] = [] - const wait = value.wait! - value.wait = async (ms) => { waits.push(ms); await wait(ms) } - await deleteAppResources('commerce', deletion(), value) + const { value, calls, keys, waits } = deps([], () => { const [next, ...rest] = answers; answers = rest; return next!() }) + await run(value) expect(calls).toEqual(['stack:keihi', 'wait', 'stack:keihi', 'wait', 'stack:keihi', 'source:keihi-src', 'console:a-keihi']) expect(waits).toEqual([5_000, 5_000]) + // One deletion, one Idempotency-Key for every send of its stack delete; the next deletion has its own. + expect(keys).toEqual(['key-1', 'key-1', 'key-1']) + answers = [() => ({})] + await run(value, { appId: 'a-nippo', stackId: 'nippo' }) + expect(keys.at(-1)).toBe('key-2') }) - test('a stack delete still waiting after the bound fails with Platform\'s answer; a running blocker is never waited for', async () => { - const waiting = deps([], () => { throw dependentsDeleting(5) }) + test('the stack delete ends at its deadline: each send is cut off there, no wait reaches past it, nothing is sent after it', async () => { + const waiting = deps([], () => { throw dependentsDeleting(30) }) const progress = deletion() - await expect(deleteAppResources('commerce', progress, waiting.value)).rejects.toBeInstanceOf(ORPCError) - expect(waiting.calls.filter((call) => call === 'wait').length).toBeGreaterThan(0) + const failure = await run(waiting.value, progress).catch((error: unknown) => error) + expect(failure).toBeInstanceOf(DeletionWaitExpiredError) + // Sends at 0, 30, 60 and 90 s; a fifth would wait until 120 s, the deadline itself. + expect(waiting.calls.filter((call) => call === 'stack:keihi')).toHaveLength(4) + expect(waiting.timeouts).toEqual([120_000, 90_000, 60_000, 30_000]) + expect(waiting.waits.reduce((sum, ms) => sum + ms, 0)).toBeLessThan(120_000) expect(waiting.calls).not.toContain('source:keihi-src') expect(progress.stackDeleted).toBeUndefined() + // A send whose answer outlasts the deadline is cut off and ends the deletion. + const slow = deps() + const cutoff = new AbortController() + slow.value.timeout = (ms) => { slow.timeouts.push(ms); return cutoff.signal } + slow.value.deleteStack = async () => { slow.advance(120_000); cutoff.abort(); throw new DOMException('timed out', 'TimeoutError') } + await expect(run(slow.value)).rejects.toBeInstanceOf(DeletionWaitExpiredError) + expect(slow.calls).toEqual([]) + const blocked = deps([], () => { throw activeDelivery() }) - await expect(deleteAppResources('commerce', deletion(), blocked.value)).rejects.toBeInstanceOf(ORPCError) + await expect(run(blocked.value)).rejects.toBeInstanceOf(ORPCError) expect(blocked.calls).toEqual(['stack:keihi']) }) + + test('aborting the deletion during a wait sends nothing more', async () => { + const controller = new AbortController() + const { value, calls } = deps([], () => { throw dependentsDeleting(5) }, () => controller.abort()) + await expect(run(value, deletion(), controller.signal)).rejects.toBeDefined() + expect(calls).toEqual(['stack:keihi', 'wait']) + + // Aborted while the stack delete was answering: no binding, no console record. + const later = new AbortController() + const answered = deps() + answered.value.deleteStack = async () => { answered.calls.push('stack:keihi'); later.abort() } + await expect(run(answered.value, deletion(), later.signal)).rejects.toBeDefined() + expect(answered.calls).toEqual(['stack:keihi']) + }) }) describe('forgetDeletedApp', () => { diff --git a/web/src/features/app/mutations.ts b/web/src/features/app/mutations.ts index b79abb2..a8f5ad0 100644 --- a/web/src/features/app/mutations.ts +++ b/web/src/features/app/mutations.ts @@ -1,7 +1,7 @@ import { ORPCError } from '@orpc/client' import { useMutation, useQueryClient, type Query, type QueryClient } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' -import { useRef } from 'react' +import { useEffect, useRef } from 'react' import { deleteApplicationSourceRepository, deleteApplicationStack } from '../../api/queries/app' import type { IndependentRows } from '../../api/boundary' import { keys } from '../../api/queries/shared' @@ -153,12 +153,18 @@ export interface AppDeletion { stackDeleted?: boolean } +/** How one deletion reaches Platform and the console; every Platform call takes the deletion's `signal`. */ export interface AppDeletionDeps { - deleteStack: (projectId: string, id: string) => Promise - deleteSourceRepository: (projectId: string, id: string) => Promise + /** The same `idempotencyKey` for every send of one deletion's stack delete (Platform's retry contract). */ + deleteStack: (projectId: string, id: string, options: { idempotencyKey: string; signal: AbortSignal }) => Promise + deleteSourceRepository: (projectId: string, id: string, options: { signal: AbortSignal }) => Promise removeApp: (appId: string) => Promise - wait?: (ms: number) => Promise + /** Resolves after `ms`; rejects as soon as `signal` aborts. */ + wait?: (ms: number, signal: AbortSignal) => Promise now?: () => number + /** A signal that aborts after `ms` (a send's share of the deletion's time). */ + timeout?: (ms: number) => AbortSignal + newKey?: () => string } /** The deleted stack still references the binding: GitOps has not pruned it within the wait. */ @@ -168,11 +174,28 @@ export class SourceStillReferencedError extends Error { } } +/** + * The stack delete was still waiting for what Platform is removing when the deletion's time ran out. `refusal` is + * Platform's last answer, if one came; nothing more is sent. + */ +export class DeletionWaitExpiredError extends Error { + constructor(readonly refusal?: unknown) { + super('the application stack deletion is still waiting for its dependents') + } +} + +/** The person closed the deletion (or left its page): nothing more was sent. Not a failure to show. */ +export class DeletionCancelledError extends Error { + constructor() { + super('the application deletion was cancelled') + } +} + /** GitOps prunes the deleted stack asynchronously; until then the binding answers 409 referenced_by_stack. */ const SOURCE_RELEASE_WAIT_MS = 120_000 const SOURCE_RELEASE_POLL_MS = 3_000 -/** How long the stack delete waits for what Platform is still removing (`dependents_deleting`) before saying so. */ +/** The whole stack delete, its sends and waits, ends within this; then the deletion says it is still waiting. */ const STACK_RELEASE_WAIT_MS = 120_000 const STACK_RELEASE_POLL_MS = 5_000 @@ -189,25 +212,55 @@ function stackDeleteRetryAfterMs(error: unknown): number | undefined { return typeof seconds === 'number' && seconds > 0 ? Math.min(seconds * 1000, 30_000) : STACK_RELEASE_POLL_MS } +function abortableWait(ms: number, signal: AbortSignal): Promise { + const { promise, resolve, reject } = Promise.withResolvers() + const abort = () => { + clearTimeout(timer) + reject(signal.reason) + } + const timer = setTimeout(() => { + signal.removeEventListener('abort', abort) + resolve() + }, ms) + if (signal.aborted) abort() + else signal.addEventListener('abort', abort, { once: true }) + return promise +} + /** - * Stack → its source repository binding → console record. The console record - * is the index, so it goes last: a running app or a stray binding never loses - * the row that lets someone delete it again. 404s count as already deleted. + * Stack → its source repository binding → console record, as one operation that `signal` stops: no send and no + * wait goes on once it aborts. The console record is the index, so it goes last: a running app or a stray binding + * never loses the row that lets someone delete it again. 404s count as already deleted. + * + * The stack delete is sent with one Idempotency-Key for this deletion, again after Platform's retry time while + * Platform only waits for what it is already removing, and never after STACK_RELEASE_WAIT_MS: each send is cut off + * at that deadline and no wait reaches past it. */ -export async function deleteAppResources(projectId: string, deletion: AppDeletion, deps: AppDeletionDeps): Promise { - const wait = deps.wait ?? ((ms: number) => new Promise((resolve) => setTimeout(resolve, ms))) +export async function deleteAppResources(projectId: string, deletion: AppDeletion, deps: AppDeletionDeps, signal: AbortSignal): Promise { + const wait = deps.wait ?? abortableWait const now = deps.now ?? Date.now + const timeout = deps.timeout ?? ((ms: number) => AbortSignal.timeout(ms)) if (deletion.stackId && !deletion.stackDeleted) { const deadline = now() + STACK_RELEASE_WAIT_MS + const idempotencyKey = deps.newKey?.() ?? crypto.randomUUID() + let refusal: unknown for (;;) { + signal.throwIfAborted() + const remaining = deadline - now() + if (remaining <= 0) throw new DeletionWaitExpiredError(refusal) + const cutoff = timeout(remaining) try { - await deps.deleteStack(projectId, deletion.stackId) + await deps.deleteStack(projectId, deletion.stackId, { idempotencyKey, signal: AbortSignal.any([signal, cutoff]) }) break } catch (error) { + signal.throwIfAborted() + if (cutoff.aborted) throw new DeletionWaitExpiredError(refusal) if (error instanceof ORPCError && error.status === 404) break const retryAfter = stackDeleteRetryAfterMs(error) - if (retryAfter === undefined || now() + retryAfter > deadline) throw error - await wait(retryAfter) + if (retryAfter === undefined) throw error + refusal = error + if (now() + retryAfter >= deadline) throw new DeletionWaitExpiredError(refusal) + await wait(retryAfter, signal) } } deletion.stackDeleted = true @@ -215,35 +268,54 @@ export async function deleteAppResources(projectId: string, deletion: AppDeletio if (deletion.sourceRepositoryId) { const deadline = now() + SOURCE_RELEASE_WAIT_MS for (;;) { + signal.throwIfAborted() try { - await deps.deleteSourceRepository(projectId, deletion.sourceRepositoryId) + await deps.deleteSourceRepository(projectId, deletion.sourceRepositoryId, { signal }) break } catch (error) { + signal.throwIfAborted() if (error instanceof ORPCError && error.status === 404) break const details = platformErrorEnvelope(error)?.details const blockers = details?.reason === 'referenced_by_stack' && Array.isArray(details.stackIds) ? details.stackIds : undefined // Another stack using the binding is not ours to wait for. if (!blockers || !deletion.stackId || !blockers.every((id) => id === deletion.stackId)) throw error - if (now() >= deadline) throw new SourceStillReferencedError() - await wait(SOURCE_RELEASE_POLL_MS) + if (now() + SOURCE_RELEASE_POLL_MS >= deadline) throw new SourceStillReferencedError() + await wait(SOURCE_RELEASE_POLL_MS, signal) } } } + signal.throwIfAborted() await deps.removeApp(deletion.appId) } +/** + * The app's deletion. One deletion runs at a time: deleting again, `cancel` (the dialog closed) or leaving the page + * stops the one in flight, which ends as DeletionCancelledError. + */ export function useDeleteApp(projectId: string, app: BusinessApp, view: AppView) { const queryClient = useQueryClient() const navigate = useNavigate() const deletion = useRef(undefined) - return useMutation({ + const running = useRef(undefined) + useEffect(() => () => running.current?.abort(), []) + const mutation = useMutation({ mutationFn: async () => { if (view.unreadableStack || view.unreadableBuild) throw new Error(copy.common.loadFailed) + running.current?.abort() + const controller = new AbortController() + running.current = controller // A retry after the stack delete was accepted keeps the ids: the stack has left the lists by then. if (!deletion.current?.stackDeleted) { deletion.current = { appId: app.id, stackId: view.stack?.id, sourceRepositoryId: sourceRepositoryIdFor(view) } } - await deleteAppResources(projectId, deletion.current, { deleteStack: deleteApplicationStack, deleteSourceRepository: deleteApplicationSourceRepository, removeApp }) + try { + await deleteAppResources(projectId, deletion.current, { deleteStack: deleteApplicationStack, deleteSourceRepository: deleteApplicationSourceRepository, removeApp }, controller.signal) + } catch (error) { + if (controller.signal.aborted) throw new DeletionCancelledError() + throw error + } finally { + if (running.current === controller) running.current = undefined + } }, onSuccess: async () => { const deleted = { appId: app.id, applicationId: view.platform?.id, stackId: deletion.current?.stackId, webComponentId: view.platform?.webComponentId } @@ -258,6 +330,7 @@ export function useDeleteApp(projectId: string, app: BusinessApp, view: AppView) ]) }, }) + return { ...mutation, cancel: () => running.current?.abort() } } export interface DeletedApp { diff --git a/web/src/features/build/implement/start-refusal.test.tsx b/web/src/features/build/implement/start-refusal.test.tsx index a6ef50d..9e0cefe 100644 --- a/web/src/features/build/implement/start-refusal.test.tsx +++ b/web/src/features/build/implement/start-refusal.test.tsx @@ -1,5 +1,6 @@ -// APT-1232: a 409 to an implementation start is either another tab's start (read back, never reported) or Platform's -// typed refusal of this start (said once, never retried). +// 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' @@ -33,6 +34,7 @@ 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, and taking a refusal back. */ let implementation: { requestFailure?: BuildFailure; startPending(): void; dismissRefusal(): void } @@ -50,6 +52,8 @@ 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') @@ -63,19 +67,34 @@ afterEach(async () => { 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 { code, details } of cases) { + 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 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() diff --git a/web/src/features/build/implement/use-implementation.ts b/web/src/features/build/implement/use-implementation.ts index 146d69a..8176ef6 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, startConflictFailure, 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' @@ -61,8 +61,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, @@ -116,10 +117,17 @@ export function useImplementation({ projectId, draft, handoff, enabled }: Implem const status = typeof error === 'object' && error !== null && 'status' in error && typeof error.status === 'number' ? error.status : envelope?.status if (status === 409) { const refusal = startConflictFailure(envelope?.code, envelope?.message ?? '', reference, envelope?.details) - // Another tab won the start: observe its run; do not create a second workspace. A refusal (Platform's typed - // reason or code) is said once and never retried; the draft read back shows nothing started. - await queryClient.invalidateQueries({ queryKey: options.queryKey }) - if (refusal) setRequestFailure({ draftId: draft.id, failure: refusal }) + 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. Another tab's start shows as a new run in the draft read back: observe it, do not create a + // second workspace. Without one, Platform refused this start (a proposal being withdrawn or not matching). + const latest = await queryClient.fetchQuery({ ...options, staleTime: 0 }).then((read) => read.implementationRuns.at(-1), () => undefined) + if (latest && latest.id !== current?.id) return false + setRequestFailure({ draftId: draft.id, failure: startRefusedFailure(envelope?.message ?? '', reference), runBefore: runMark(latest ?? current) }) return false } const failedRun = queryClient.getQueryData(options.queryKey)?.implementationRuns.at(-1) ?? run @@ -150,8 +158,8 @@ export function useImplementation({ projectId, draft, handoff, enabled }: Implem 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 }) }, - /** Takes back a start Platform refused because of the proposal, once the proposal moved on: the start is offered again. */ - dismissRefusal: () => setRequestFailure((current) => current?.failure.reasonCode === 'ProposalRunBlocked' ? undefined : current), + /** 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/improve/conversation.tsx b/web/src/features/improve/conversation.tsx index d2f8e49..e2c6cfc 100644 --- a/web/src/features/improve/conversation.tsx +++ b/web/src/features/improve/conversation.tsx @@ -26,8 +26,8 @@ export interface ImproveConversationProps { appUrl?: string locked: boolean starting: boolean - /** The session's proposal awaits review or apply, or is closed: no change can be started, the change card says why. */ - review?: 'waiting' | 'closed' + /** 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 @@ -159,14 +159,19 @@ function FailureNotice({ failure, onRetry, onConfirm }: { failure: BuildFailure; } +/** 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 the proposal awaits review - * or is closed, Platform starts no run: 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. + * 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?: 'waiting' | 'closed'; failure?: BuildFailure; onStart(): void; onConfirm(): void }) { +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[review === 'waiting' ? 'proposalPending' : 'proposalClosed'] : undefined + const held = review ? buildCopy.failure.run[HOLD_COPY[review]] : undefined return

{text.proposal.label}

{text.proposal.lead}

diff --git a/web/src/features/improve/copy.test.tsx b/web/src/features/improve/copy.test.tsx index f1c11e2..278e33e 100644 --- a/web/src/features/improve/copy.test.tsx +++ b/web/src/features/improve/copy.test.tsx @@ -84,7 +84,7 @@ test.each(['ja', 'en'] as const)('a refused start is said once with no retry, an 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]] as const) { + 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) 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..622b707 --- /dev/null +++ b/web/src/features/improve/refusal-session.test.tsx @@ -0,0 +1,120 @@ +// 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; startPending(): void } + +function Harness() { + const value = useImproveSession('p1', draft) + session = { review: value.review, reviewLocked: value.reviewLocked, requestFailure: value.implementation.requestFailure, startPending: value.implementation.startPending } + 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.startPending() }) + 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('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 0a4daaf..3e70beb 100644 --- a/web/src/features/improve/use-improve-session.ts +++ b/web/src/features/improve/use-improve-session.ts @@ -9,7 +9,7 @@ import { isOneOf, knownValue, type BuildDraft } from '../../model/contracts/buil import { deriveImprove } from '../../model/improve' import { useImplementation } from '../build/implement' import { proposalKeys, proposalOptions } from '../../api/queries/proposal' -import { improvementLocked, proposalTerminal, proposalWaiting } from '../proposals/model' +import { improvementAdmitted, proposalTerminal, proposalWaiting } from '../proposals/model' /** * Turns and runs are server-owned: sending a message only POSTs the turn and @@ -25,23 +25,35 @@ 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) - /** Why the session takes no new change: its proposal awaits review or apply, or is closed. */ - const review = !draft.proposalId || !phase ? undefined : proposalWaiting(phase) ? 'waiting' as const : proposalTerminal(phase) ? 'closed' as const : undefined - // Platform refused a start because of the proposal: read the proposal again, so the page says which holds. - const refused = implementation.requestFailure?.reasonCode === 'ProposalRunBlocked' - useEffect(() => { - if (refused) void queryClient.invalidateQueries({ queryKey: proposalKeys.detail(projectId, draft.proposalId) }) - }, [refused, queryClient, projectId, draft.proposalId]) - // Once the proposal moves on, that refusal no longer holds: sent back for changes, the change can be started again. - const phaseWord = phase ? knownValue(phase) ?? 'unknown' : undefined - const seenPhase = useRef(phaseWord) + 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 it shows the proposal changed and admitting a run again; a read of the same proposal + // (still drafting with its submission pending, say) keeps it. + 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 refusedWith = useRef<{ failure: BuildFailure; mark?: string; at: number }>(undefined) const { dismissRefusal } = implementation useEffect(() => { - if (seenPhase.current === phaseWord) return - seenPhase.current = phaseWord - dismissRefusal() - }, [phaseWord, dismissRefusal]) + if (!refusal || !draft.proposalId) { + refusedWith.current = undefined + return + } + if (refusedWith.current?.failure !== refusal) { + refusedWith.current = { failure: refusal, mark: proposalMark, at: Date.now() } + void queryClient.invalidateQueries({ queryKey: proposalKeys.detail(projectId, draft.proposalId) }) + return + } + 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({ 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 7350d8a..7edfb74 100644 --- a/web/src/model/build/failure.ts +++ b/web/src/model/build/failure.ts @@ -40,6 +40,16 @@ export function startConflictFailure(code: string | undefined, text: string, ref 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 e2cf403..4320b0c 100644 --- a/web/src/model/build/types.ts +++ b/web/src/model/build/types.ts @@ -120,8 +120,9 @@ export interface BuildFailure { /** * `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' + reasonCode?: 'PublishURLConflict' | 'ProposalRunBlocked' | 'StartRefused' raw?: string /** Support correlation only; diagnostics stay in the advanced disclosure. */ reference?: { draftId: string; executionId?: string; at: string } diff --git a/web/src/ui/overlay.tsx b/web/src/ui/overlay.tsx index f0a89d2..df31758 100644 --- a/web/src/ui/overlay.tsx +++ b/web/src/ui/overlay.tsx @@ -81,6 +81,7 @@ export function ConfirmDialog({ pending = false, error, disabled = false, + closableWhilePending = false, returnFocusRef, }: { open: boolean @@ -95,13 +96,15 @@ export function ConfirmDialog({ pending?: boolean error?: unknown disabled?: boolean + /** The pending action stops when the dialog closes (its owner cancels it in `onOpenChange`), so it may be closed. */ + closableWhilePending?: boolean returnFocusRef?: RefObject }) { const [typed, setTyped] = useState('') const inputId = useId() const ready = !disabled && (!confirmText || typed.trim() === confirmText) const change = (next: boolean) => { - if (pending) return + if (pending && !closableWhilePending) return if (!next) setTyped('') onOpenChange(next) } @@ -113,7 +116,7 @@ export function ConfirmDialog({ returnFocusRef={returnFocusRef} footer={ <> -
- : 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 index 622b707..d3f2bc0 100644 --- a/web/src/features/improve/refusal-session.test.tsx +++ b/web/src/features/improve/refusal-session.test.tsx @@ -43,11 +43,11 @@ 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; startPending(): void } +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, startPending: value.implementation.startPending } + session = { review: value.review, reviewLocked: value.reviewLocked, requestFailure: value.implementation.requestFailure, start: value.start } return null } @@ -96,7 +96,7 @@ afterEach(async () => { 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.startPending() }) + 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). @@ -109,6 +109,22 @@ test('a refusal is kept while reads show the same proposal, and taken back when 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') diff --git a/web/src/features/improve/use-improve-session.ts b/web/src/features/improve/use-improve-session.ts index 3e70beb..abb2abf 100644 --- a/web/src/features/improve/use-improve-session.ts +++ b/web/src/features/improve/use-improve-session.ts @@ -35,22 +35,23 @@ export function useImproveSession(projectId: string, draft: BuildDraft) { : 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 it shows the proposal changed and admitting a run again; a read of the same proposal - // (still drafting with its submission pending, say) keeps it. + // 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 } = implementation + const { dismissRefusal, startPending } = implementation useEffect(() => { if (!refusal || !draft.proposalId) { refusedWith.current = undefined return } if (refusedWith.current?.failure !== refusal) { - refusedWith.current = { failure: refusal, mark: proposalMark, at: Date.now() } + refusedWith.current = { failure: refusal, ...(requested.current ?? { mark: proposalMark, at: Date.now() }) } void queryClient.invalidateQueries({ queryKey: proposalKeys.detail(projectId, draft.proposalId) }) - return } if (proposal.dataUpdatedAt > refusedWith.current.at && proposalMark !== refusedWith.current.mark && improvementAdmitted(phase)) dismissRefusal() }) @@ -106,6 +107,11 @@ export function useImproveSession(projectId: string, draft: BuildDraft) { 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/ui/overlay.tsx b/web/src/ui/overlay.tsx index df31758..f0a89d2 100644 --- a/web/src/ui/overlay.tsx +++ b/web/src/ui/overlay.tsx @@ -81,7 +81,6 @@ export function ConfirmDialog({ pending = false, error, disabled = false, - closableWhilePending = false, returnFocusRef, }: { open: boolean @@ -96,15 +95,13 @@ export function ConfirmDialog({ pending?: boolean error?: unknown disabled?: boolean - /** The pending action stops when the dialog closes (its owner cancels it in `onOpenChange`), so it may be closed. */ - closableWhilePending?: boolean returnFocusRef?: RefObject }) { const [typed, setTyped] = useState('') const inputId = useId() const ready = !disabled && (!confirmText || typed.trim() === confirmText) const change = (next: boolean) => { - if (pending && !closableWhilePending) return + if (pending) return if (!next) setTyped('') onOpenChange(next) } @@ -116,7 +113,7 @@ export function ConfirmDialog({ returnFocusRef={returnFocusRef} footer={ <> -