Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 12 additions & 1 deletion web/src/api/build.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { afterEach, beforeEach, expect, mock, test } from 'bun:test'
import { QueryClient, QueryObserver, skipToken } from '@tanstack/react-query'
import * as api from './build'
import { BUILD_POLL_MS, buildDraftOptions, buildKeys, draftsOptions } from './queries/build'
import { draftOf, runOf } from './testing/build-domain'
import { draftOf, generationOf, runOf, turnOf } from './testing/build-domain'
import { POLL_INTERVAL_MS, readRetryDelay, retryReadQuery } from './queries/shared'
import { isPublishPreparationPending } from './publish-retry'

Expand Down Expand Up @@ -44,6 +44,17 @@ afterEach(() => {
else Reflect.deleteProperty(globalThis, 'sessionStorage')
})

test('turn and plan generation readers keep the workspace they replaced, and read answers without it (APT-1264)', () => {
expect(turnOf({ ...turn, replacedDevWorkspaceId: 'workspace-0' }).replacedDevWorkspaceId).toBe('workspace-0')
expect(generationOf({ ...generation, replacedDevWorkspaceId: 'workspace-0' }).replacedDevWorkspaceId).toBe('workspace-0')
// An older Platform never sends the field: the same answers read unchanged.
expect(turnOf(turn).replacedDevWorkspaceId).toBeUndefined()
expect(generationOf(generation).replacedDevWorkspaceId).toBeUndefined()
const read = draftOf({ ...draft, conversationTurns: [{ ...turn, replacedDevWorkspaceId: 'workspace-0' }, { ...turn, id: 'turn-2' }], creationPlanGenerations: [{ ...generation, replacedDevWorkspaceId: 'workspace-0' }] })
expect(read.conversationTurns.map((item) => item.replacedDevWorkspaceId)).toEqual(['workspace-0', undefined])
expect(read.creationPlanGenerations[0]?.replacedDevWorkspaceId).toBe('workspace-0')
})

test('all build API adapters use contract routes, payloads and idempotency keys per mutation attempt', async () => {
await api.createDraft('project-1', { intent: '見積を作る', title: '見積' })
await api.updateDraft('project-1', 'draft-1', { specMarkdown: '---\nspec: {}\n---\n', intent: '新しい内容', title: '新しい名前' })
Expand Down
6 changes: 6 additions & 0 deletions web/src/api/contracts/platform/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,17 +67,23 @@ export function openCanonical<K extends string>(canonical: { options: readonly K

const DRAFT_OMITS = 'platform-api internal/api/dto_application_draft.go'

// The retired workspace a turn or plan generation replaced (APT-1264): present only on the record that switched to a new
// workspace. Restated here until the published api-schema carries it; an older Platform never sends it.
const replacedDevWorkspaceId = z.string().optional()

export const turnReader: z.ZodType<BuildTurn> = ApplicationDraftConversationTurn.extend({
// A turn without `kind` predates the field and is a conversation turn (canonical default).
kind: openCanonical(ApplicationDraftConversationTurnKind).default({ kind: 'known', value: 'conversation' }),
status: openCanonical(ApplicationDraftConversationTurnStatus),
excelProgress: excelProgressReader.optional(),
uiDesign: uiDesignReader.optional(),
replacedDevWorkspaceId,
})

export const generationReader: z.ZodType<BuildGeneration> = ApplicationDraftCreationPlanGeneration.extend({
status: openCanonical(ApplicationDraftCreationPlanGenerationStatus),
stage: openCanonical(ApplicationDraftCreationPlanGeneration.shape.stage.unwrap()).optional(),
replacedDevWorkspaceId,
})

const stepReader: z.ZodType<BuildExecutionStep> = ApplicationDraftCreationExecutionStep.extend({
Expand Down
25 changes: 25 additions & 0 deletions web/src/features/build/build-page-wire.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -987,6 +987,31 @@ describe('a plan Platform\'s validation rejects is an answer about the plan (APT
expect(proposalButtons()).toEqual([buildCopy.primary.prepare])
})

test('at the generation limit, a recreated-workspace notice sorted after the limit notice (device clock behind the server) brings back no new plan (APT-1264)', async () => {
const { draftId, key } = await rejected(fieldErrorAnswer)
refusals.push({ method: 'POST', path: generations(draftId), status: 412, body: { error: { code: 'failed_precondition', message: 'application draft has reached 20 plan generation attempts' } } })
await click(action(buildCopy.failure.plan.incomplete.title, makeAgain))
await settle(10)
expect(notices(buildCopy.failure.limit.title, '#build-conversation')).toHaveLength(1)
expect(proposalButtons()).toEqual([])
// Platform marks the plan's generation as the switch from a retired workspace. Its start (server time) reads later
// than the limit notice's (this device's time), so the display-only notice is the conversation's last message.
const ahead = new Date(Date.now() + 60 * 60_000).toISOString()
rewrites.push({
method: 'GET', path: new RegExp(`${draftPath(draftId)}$`), once: false,
body: (wire) => rewriteDraftWire(wire, draftId, (draft) => ({ ...draft, creationPlanGenerations: (draft.creationPlanGenerations as Json[]).map((generation) => ({ ...generation, startedAt: ahead, replacedDevWorkspaceId: 'ws-retired' })) })),
})
await tick(key)
await settle(10)
expect(notices(buildCopy.workspaceRecreated, '#build-conversation')).toHaveLength(1)
expect(conversation().lastIndexOf(buildCopy.workspaceRecreated)).toBeGreaterThan(conversation().lastIndexOf(buildCopy.failure.limit.title))
// The limit is still what the page decides on: 「計画を作り直す」 is not offered again, and nothing is generated.
expect(labels(buildCopy.failure.limit.title)).toEqual([])
expect(labels(buildCopy.workspaceRecreated)).toEqual([])
expect(proposalButtons()).toEqual([])
expect(count('POST', generations(draftId))).toBe(1)
})

// A failed request is not an answer about the plan: preparing asks no AI, so a 500 and a gateway 503 alike are the
// platform failure with its reference, and the same approval may be tried again.
test.each([500, 503])('a failed validation request (%i) is the platform failure with its reference, never a plan rejection', async (status) => {
Expand Down
4 changes: 3 additions & 1 deletion web/src/features/build/build-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { useEffect, useState, type ReactNode } from 'react'
import { buildKeys, useBuildDraft } from '../../api/queries/build'
import { useGroups } from '../../api/queries/console'
import { buildCopy } from '../../model/build/copy'
import { lastActionable } from '../../model/build/messages'
import { isBuildPending } from '../../model/build/progress'
import { paths } from '../../routes/paths'
import { setArtifactCollapsed, shellStore } from '../../shell/store'
Expand Down Expand Up @@ -79,7 +80,8 @@ function Session({ draft, groupId, stale }: { draft: BuildDraft; groupId: string
const primary = { ...build.result.primary, enabled: build.result.primary.enabled && !build.busy && !sharing && !updatingPlan && (build.result.primary.action !== 'publish' || !appReadOnly) }
// 決める: the prepare action is attached to the AI's proposal, labelled by what pressing it will do. After the
// destination moved, the notice right below the proposal carries the same action (once, beside its explanation).
const lastMessage = build.messages.at(-1)
// A recreated-workspace notice is display only: what follows is decided on the newest message before it.
const lastMessage = lastActionable(build.messages)
const reapproveNotice = lastMessage?.role === 'notice' && lastMessage.retry === 'prepare' && lastMessage.title === buildCopy.failure.destination.changed.title
// A plan Platform's validation rejected is never approved again. Its actions (「もう一度確かめる」 when the cause may lie
// outside the plan, 「計画を作り直す」) are on the notice that explains the rejection, or on the proposal when that notice
Expand Down
8 changes: 8 additions & 0 deletions web/src/features/build/conversation-pane.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,14 @@ export function UserMessage({ text }: { text: string }) {
</article>
}

/**
* The workspace was recreated (APT-1264), where a conversation keeps its own records (improve, Excel → app):
* information only, the same as the build conversation's derived notice (messages.ts#workspaceRecreatedNotice).
*/
export function WorkspaceRecreatedNotice({ className }: { className?: string }) {
return <Notice tone="info" title={buildCopy.workspaceRecreated} className={className} />
}

/** A failure's support reference, with its copy button. */
export function FailureReference({ reference }: { reference: NonNullable<BuildFailure['reference']> }) {
const value = buildFailureReference(reference)
Expand Down
29 changes: 29 additions & 0 deletions web/src/features/build/copy.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { isPlatformNotFound } from '../../api/platform-error'
import { draftOf, runOf, taskOf } from '../../api/testing/build-domain'
import { buildCopy } from '../../model/build/copy'
import { buildFailureReference, classifyBuildFailure, destinationFailure } from '../../model/build/failure'
import { messagesFromDraft } from '../../model/build/messages'
import { deriveStage, draftPublished } from '../../model/build/stage'
import type { BuildProposal, BuildSpec } from '../../model/build/types'
import type { BuildDraft } from '../../model/contracts/build'
Expand Down Expand Up @@ -126,6 +127,34 @@ test.each(['ja', 'en'] as const)('a moved destination is approved again with the
expect(render('blocked')).toContain(`>${text.conversation.retry}</button>`)
})

test.each(['ja', 'en'] as const)('a recreated workspace is announced once, on the turn that replaced it, as information only (%s)', (language) => {
setLanguage(language)
const at = (minute: number, second = 0) => `2026-11-18T00:0${minute}:${String(second).padStart(2, '0')}Z`
const turn = (id: string, minute: number, fields: Record<string, unknown> = {}) => ({
id, kind: 'conversation', status: 'succeeded', startedAt: at(minute), finishedAt: at(minute, 10), devWorkspaceId: 'ws-new', userMessage: `request ${id}`, assistantMessage: `answer ${id}`, ...fields,
})
const draft = draftOf({
id: 'draft-1', projectId: 'project-1', title: 'Contacts', intent: 'Keep contacts', phase: 'specifying', specMarkdown: '', architectureMarkdown: '', ownerUserId: 'user-1', createdAt: at(0), updatedAt: at(4),
conversationTurns: [turn('turn-1', 1, { devWorkspaceId: 'ws-old' }), turn('turn-2', 2, { replacedDevWorkspaceId: 'ws-old' }), turn('turn-3', 3)],
creationPlanGenerations: [{ id: 'gen-1', status: 'succeeded', startedAt: at(4), finishedAt: at(4, 30), devWorkspaceId: 'ws-new' }],
})
const markup = renderToStaticMarkup(<ConversationPane
messages={messagesFromDraft(draft, [])} stage="ask" answering={false} thinking={false} queued={false}
onSend={() => {}} onRetry={() => {}} onUseName={() => {}}
/>)
const notice = buildCopy.workspaceRecreated
expect(notice).toBe(language === 'ja' ? '作業環境を作り直しました。会話と計画は引き継いでいます' : 'Your workspace was recreated. The conversation and plan are kept.')
expect(markup.split(notice)).toHaveLength(2)
// Below the request that switched workspaces and above its answer; the later turn carries none.
expect(markup.indexOf('request turn-2')).toBeLessThan(markup.indexOf(notice))
expect(markup.indexOf(notice)).toBeLessThan(markup.indexOf('answer turn-2'))
// A calm status, not an alert: no retry, no support reference.
expect(markup).toContain('role="status"')
expect(markup).not.toContain('role="alert"')
expect(markup).not.toContain(`>${text.conversation.retry}</button>`)
expect(markup).not.toContain(buildCopy.failure.copyReference)
})

// The rendered state needs the router (LinkButton); app-build-ai.mock.spec.ts covers it. Here: the
// classifier that routes a 404 away from 「しばらくしてから再読み込み」, and the wording.
test('a 404 draft is an answer, not a transient failure, and the copy names the signed-in account', () => {
Expand Down
78 changes: 78 additions & 0 deletions web/src/features/excel2app/excel2app-page-wire.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -375,3 +375,81 @@ describe('X5: a 2xx Excel write whose answer cannot be read', () => {
expect(stepTitle()).toBe(text.preview.title)
})
})

describe('APT-1264: a turn that replaced a retired workspace', () => {
/** Platform marks the draft's turns of `kind` as the switch from a retired workspace (every read of the draft). */
function replaced(kind: 'excel-analysis' | 'ui-design') {
rewrites.push({
method: 'GET', path: /\/application-drafts\/[^/]+$/, once: false,
body: (wire) => Array.isArray(wire.conversationTurns)
? { ...wire, conversationTurns: (wire.conversationTurns as Json[]).map((turn) => turn.kind === kind ? { ...turn, replacedDevWorkspaceId: 'ws-retired' } : turn) }
: wire,
})
}
const recreated = () => [...container.querySelectorAll('[role="status"]')].filter((item) => item.querySelector('p')?.textContent === buildCopy.workspaceRecreated)
async function reopen(draftId: string) {
await act(async () => { root?.unmount() })
container.remove()
await renderExcel(draftId)
}

test('the analysis step says so once, also after the same draft is opened again', async () => {
const draftId = await storedDraft()
// Started but not advanced: the analysis runs, so the page opens on its step.
await call('POST', `${draftPath(draftId)}/conversation-turns`, { kind: 'excel-analysis', message: '' })
replaced('excel-analysis')
await renderExcel(draftId)
await until(() => Boolean(byTestId('excel2app-workspace-recreated')))
expect(recreated()).toHaveLength(1)
expect(buttonsIn(byTestId('excel2app-workspace-recreated')!)).toEqual([])
await reopen(draftId)
await until(() => Boolean(byTestId('excel2app-workspace-recreated')))
expect(recreated()).toHaveLength(1)
})

test('an earlier analysis that replaced the workspace and failed says nothing on the analysis shown after it; the shown one that replaced does', async () => {
const draftId = await storedDraft()
const startAnalysis = async () => ((await call('POST', `${draftPath(draftId)}/conversation-turns`, { kind: 'excel-analysis', message: '' })).resource as Json).id as string
const first = await startAnalysis()
await call('POST', '/api/v1/__mock/advance')
// Started but not advanced: the second analysis (reusing what the first read) runs, so the page opens on its step.
const second = await startAnalysis()
/** The first analysis failed after replacing a retired workspace; `marked` carries the switch (only it). */
const reads = (marked: string) => rewrites.push({
method: 'GET', path: new RegExp(`${draftPath(draftId)}$`), once: false,
body: (wire) => ({
...Object.fromEntries(Object.entries(wire).filter(([key]) => key !== 'excelAnalysis')),
conversationTurns: (wire.conversationTurns as Json[]).map((turn) => ({
...turn,
...(turn.id === first ? { status: 'failed', error: 'codex exited' } : {}),
...(turn.id === marked ? { replacedDevWorkspaceId: 'ws-retired' } : {}),
})),
}),
})
reads(first)
await renderExcel(draftId)
await until(() => stepTitle() === text.analysis.running)
await settle(10)
expect(byTestId('excel2app-workspace-recreated')).toBeNull()
expect(recreated()).toHaveLength(0)
rewrites = []
reads(second)
await reopen(draftId)
await until(() => Boolean(byTestId('excel2app-workspace-recreated')))
expect(recreated()).toHaveLength(1)
})

test('the preview chat says so once, at the design turn, also after the same draft is opened again', async () => {
const draftId = await storedDraft({ analysed: true, designed: true })
replaced('ui-design')
await renderExcel(draftId)
await until(() => Boolean(byTestId('excel2app-chat-input')))
expect(recreated()).toHaveLength(1)
expect(container.querySelectorAll('[data-testid="excel2app-chat-message"][data-role="notice"]')).toHaveLength(1)
// The analysis turn did not switch: its step has nothing to say.
expect(byTestId('excel2app-workspace-recreated')).toBeNull()
await reopen(draftId)
await until(() => Boolean(byTestId('excel2app-chat-input')))
expect(recreated()).toHaveLength(1)
})
})
3 changes: 3 additions & 0 deletions web/src/features/excel2app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { Button, Card, CardBody, cn, CopyButton, EmptyState, Field, focusHeading
import { ResourceBoundary, type ResourceQuery } from '../../ui/resource-boundary'
import { text as buildText } from '../build/copy'
import { resolveBuildGroup } from '../build/entry'
import { WorkspaceRecreatedNotice } from '../build/conversation-pane'
import { UnconfirmedNotice } from '../build/unconfirmed-notice'
import { filesFromDrop, filesFromList, type CollectedWorkbook } from './collect'
import { text } from './copy'
Expand Down Expand Up @@ -274,6 +275,8 @@ function Excel2AppFlow({ draftId, onCreatedDraft }: { draftId?: string; onCreate
{flow.unconfirmed ? <div className="mb-5" data-testid="excel2app-unconfirmed"><UnconfirmedNotice onConfirm={() => void flow.confirm()} /></div> : null}

{step === 0 && !readOnly ? <PickStep busy={flow.collecting || flow.starting || flow.turnRunning} closed={flow.unconfirmed} error={pickError} files={flow.files} budget={flow.budget} hint={flow.hint} onHint={flow.setHint} onFiles={(files) => void collected(files)} onSample={(grids) => void collected(grids, true)} onRemove={(file) => void remove(file)} onRetry={(file) => void flow.retryFile(file.key)} onStart={() => { setStep(ANALYSIS_STEP); void flow.startAnalysis() }} /> : null}
{/* The analysis switched from a retired workspace (APT-1264): told once on its step, above what it read. */}
{step === ANALYSIS_STEP && draft && flow.analysis.recreated ? <div className="mb-5" data-testid="excel2app-workspace-recreated"><WorkspaceRecreatedNotice /></div> : null}
{step === ANALYSIS_STEP && draft ? (
reading ? (
<AnalysisStep reading={reading} workbooks={draft.source?.workbooks ?? []} entries={flow.offlineEntries} readings={flow.workbooksQuery} resetKey={draft.id} offline={flow.offline} />
Expand Down
15 changes: 15 additions & 0 deletions web/src/features/excel2app/ui-preview-step.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,21 @@ test('a failed turn renders as a notice with retry on the last message only', ()
expect(render({ messages: [failed], onRetry: () => {}, busy: true })).not.toContain('excel2app-chat-retry')
})

test.each(['ja', 'en'] as const)('a recreated workspace is one calm notice between the instruction and its reply, never a bubble or a retry (APT-1264, %s)', (language) => {
setLanguage(language)
const messages: UiPreviewChatMessage[] = [
{ role: 'user', text: '一覧をカード表示に' },
{ role: 'notice', text: buildCopy.workspaceRecreated },
{ role: 'assistant', text: '一覧をカード表示にしました。' },
]
const html = render({ messages, onRetry: () => {} })
expect(html.split(buildCopy.workspaceRecreated)).toHaveLength(2)
expect(html.split('data-role="notice"')).toHaveLength(2)
expect(html.indexOf('data-role="user"')).toBeLessThan(html.indexOf(buildCopy.workspaceRecreated))
expect(html.indexOf(buildCopy.workspaceRecreated)).toBeLessThan(html.indexOf('data-role="assistant"'))
expect(html).not.toContain('excel2app-chat-retry')
})

test.each(['ja', 'en'] as const)('quota failure in UI chat explains the account problem and retains manual retry in %s', (language) => {
setLanguage(language)
for (const error of [
Expand Down
3 changes: 3 additions & 0 deletions web/src/features/excel2app/ui-preview-step.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,9 @@ function ChatPanel({ messages, busy, readOnly, activity, ready, onSend, onUndo,
{/* biome-ignore lint/a11y/noNoninteractiveTabindex: a scrollable region must be reachable by keyboard. */}
<ol ref={log} aria-label={text.chat.messages} aria-live="polite" aria-busy={busy} tabIndex={0} className="max-h-80 min-h-40 flex-1 space-y-3 overflow-y-auto px-4 py-4 focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-accent @2xl:max-h-none @2xl:min-h-0">
{messages.map((message, index) => {
// The workspace was recreated (APT-1264): information between an instruction and its reply, not a chat bubble.
// biome-ignore lint/suspicious/noArrayIndexKey: the conversation only grows; an index is its identity.
if (message.role === 'notice') return <li key={index} data-testid="excel2app-chat-message" data-role="notice"><Notice tone="info" title={message.text} /></li>
const state = message.failed ? 'failed' : message.pending ? 'pending' : undefined
const quota = message.failed && isAIQuotaExhausted(message.text)
const failure = message.failed ? message.failure ?? classifyBuildFailure(message.text, undefined, 'turn') : undefined
Expand Down
Loading