Repository navigation
feat(session): add POST /sessions/{id}:continue and desktop/web continue UI - #5048
Conversation
🦋 Changeset detectedLatest commit: 54d062c The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 5c9de4207d
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const assertIdle = (): void => { | ||
| const snap = loop.snapshot(); | ||
| const compacting = agent.accessor.get(IAgentFullCompactionService).compacting !== null; | ||
| if (snap.state === 'running' || snap.paused || snap.hasPendingRequests || compacting) { |
There was a problem hiding this comment.
Allow crash-interrupted loops through the busy checks
When a session is cold-restored after a process crash, the core loop has state.status === 'interrupted'; hasPendingRequests() consequently returns true for that non-idle status. This condition therefore returns 40901 SESSION_BUSY before checking whether the orphaned turn is continuable, and AgentLoopService.continueTurn() repeats the same check even if this guard is bypassed. As a result, the advertised crash-recovery case can never reach loop.continue({ force: true }); distinguish an interrupted unfinished loop from genuinely active pending work in both gates.
Useful? React with 👍 / 👎.
| switch (record.type) { | ||
| case 'turn.prompt': | ||
| case 'turn.prompt': { | ||
| if (typeof record['trigger'] === 'string') state.recordsTurnEnds = true; |
There was a problem hiding this comment.
Reopen the orphaned turn when resuming it
Once a cold-restored crash continuation passes the busy checks, this new classification makes settleOrphanTurns() mark the orphan as ended/interrupted, but it does not add the turn to implicitlyEnded. When the core resumes the same turn number, the next step.begin therefore cannot reopen the known turn in turnForNumber() and instead creates a second conversation turn with the same turn_number; KAP clients retain the original as interrupted and receive the resumed output in a separate, user-message-less turn. Mark crash-settled turns as implicitly ended (or otherwise explicitly reopen them) so the WS/REST projection matches the core's same-turn resume.
Useful? React with 👍 / 👎.
| undo: { body: undoSessionRequestSchema, handle: undoSessionAction }, | ||
| cancel: { body: cancelSessionRequestSchema, handle: cancelSessionAction }, | ||
| wait: { body: waitSessionRequestSchema, handle: waitSessionAction }, | ||
| continue: { handle: continueSessionAction }, |
There was a problem hiding this comment.
Add a changeset for the public continue action
This adds an externally advertised core KAP capability and endpoint, but the commit contains no .changeset entry. The repository's changeset rules explicitly require public KAP conversation/session capabilities to produce a user-facing CLI changeset, so otherwise this new action will be absent from the generated release versioning and changelog; add a minor changeset for @moonshot-ai/kimi-code.
AGENTS.md reference: AGENTS.md:L109-L109
Useful? React with 👍 / 👎.
5c9de42 to
7acf8db
Compare
f8dc1f6 to
93ceab0
Compare
7acf8db to
4ac723d
Compare
93ceab0 to
e3eaf6d
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4ac723df68
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| const retry = active?.retry; | ||
| return { | ||
| state: loop?.state.turn === undefined && active === undefined ? 'idle' : 'running', | ||
| state: loop?.state.status === 'running' || active !== undefined ? 'running' : 'idle', |
There was a problem hiding this comment.
Keep interrupted turns unavailable to cron scheduling
When a cron-enabled session is cold-restored with durable.unfinished, the loop has status === 'interrupted' and no active projection, so this change reports it as idle. tickCron() skips delivery only when snapshot().state === 'running'; a due persisted job can therefore call notify(), whose core scheduler invokes closeUnfinished() before starting the cron turn. This silently discards the resumable foreground turn before the user can call :continue, whereas the previous snapshot kept cron delivery blocked while that unfinished turn existed. Treat interrupted work as non-idle to existing schedulers, or update those schedulers to honor hasPendingRequests.
AGENTS.md reference: AGENTS.md:L115-L117
Useful? React with 👍 / 👎.
4ac723d to
24a1422
Compare
e3eaf6d to
7ea55aa
Compare
24a1422 to
69c7eab
Compare
7ea55aa to
eae5840
Compare
69c7eab to
edda32a
Compare
1c858f4 to
030a71d
Compare
edda32a to
54d062c
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 54d062ca25
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| () => inFlight.value || turnActive.value || promptPending.value || continuePending.value, | ||
| ); | ||
|
|
||
| const canContinue = computed<boolean>(() => { |
There was a problem hiding this comment.
Gate Continue on the target host capability
For an interrupted session routed to an older registered SSH host, this exposes Continue solely from turn state, even though HostRouter routes continueSession to that host while getMeta remains local and HOST_API_LEVEL was not bumped. Clicking Continue therefore calls an unsupported action on an otherwise accepted older host. Track session_continue for the target host or raise the required host API level before showing this action.
Useful? React with 👍 / 👎.
|
|
||
| settled(): Promise<TurnResult | undefined>; | ||
|
|
||
| continueTurn(reminders?: readonly Message[]): void; |
There was a problem hiding this comment.
Add an agent-core-v2 changeset
This adds a public IAgentLoopService method and changes loop snapshot/error behavior in @moonshot-ai/agent-core-v2, but the two new changesets list only kap-server and the products. The repository changeset workflow requires changed library source to receive its own entry, so otherwise the agent-core package version and changelog will not record this API change.
AGENTS.md reference: AGENTS.md:L169-L170
Useful? React with 👍 / 👎.
main added POST /api/v1/sessions/{session_id}:continue, advertised as
the session_continue capability, with error code 40940
TURN_NOT_CONTINUABLE (#5048). Continuing starts model work, so the
action can also answer with the sign-in errors 40110, 40111 and 40113;
the session actions share one OpenAPI projection, so the six existing
actions list those four responses as well. The refreshed OpenAPI
document and contract summary record 146 changes, all non-breaking, and
the contract digest is updated with the host API level kept at 1, as
#5048 kept it. The capability ledger lists session_continue as KAP-only,
since ACP has no request to continue a turn.
After main's #5048 came in, the journey failed once on CI, while it passed in the two runs before and twice locally. The trace shows the app itself presenting the model menu again: after choosing Off and pressing Escape the menu starts closing, then shows again with no further input and stays open past the 15-second timeout. That is a race in the product rather than in the test, so the journey is quarantined with an owner and an expiry while its cause is investigated, and the nightly run keeps running it without retries.
…5138) * test: enforce protected first-turn smoke across four layers * test: demonstrate a missing protected KAP smoke in CI * test: restore the protected KAP smoke after the gate experiment * test: record KAP checkpoints and replay them in the client * test: recover a released conversation across KAP process boundaries * test: verify protocol contracts and history performance budgets * test: consolidate layered test infrastructure into testkit Move the pieces that the TUI, KAP subprocess, recording and schema tests each built for themselves into @moonshot-ai/testkit: - TestProcess starts child processes, drains their output, waits for a ready line and kills the process tree. Every child preloads the network guard, which appends violations to a log that survives a forced kill and also covers Node grandchildren. - kimiCliCommand, kimiCliEnv and osHomeEnv give the CLI one offline environment: Kimi services point at a .test host the guard blocks, with stubs for the two optional config endpoints. - KapClient holds the session operations that the in-process KapHarness and the new KapProcess subprocess driver share. - KapRecorder, readKapRecording and replayKapRecording give producers and consumers one recording format. The normalizer keeps one token per value across keys and can keep time fields parseable. - expectGolden and expectTextGolden list every difference, accept CRLF checkouts and refuse to write in CI. - The contract summary turns the KAP OpenAPI and AsyncAPI documents into one reviewable line per field, including constraints, and classifies changes as breaking, non-breaking or unclassified. The schema JSON is no longer hidden as generated in diffs. - The fake model can split responses at random byte boundaries, with a seed per lane, to catch clients that depend on tidy chunks. - testkitAgentFixtures lets engine tests drive the real provider request path through the testkit model; the built-in mock API refuses to run on such an agent. * ci: enforce every L0 kind and keep new tests on the testkit - tests/protected.yaml declares smoke, regression and contract L0 entries with their runner, and the projects that need a smoke. A PR still has to satisfy the IDs and smoke projects of its base revision, and Playwright entries must be smoke. - The test shards upload Vitest blob reports. The new "L0 protected tests" job merges them, checks every Vitest L0 entry, and decides its exit code from L0 results only. - scripts/checks/test-doubles.mjs freezes the legacy model doubles at their current use per file, so new tests script models through the testkit. - An optional Desktop E2E workflow runs the selected journeys on pull requests, all journeys on main, and the quarantined ones nightly. - CODEOWNERS lists three owners for the gate files. * test: check the KAP contract in one place The route snapshot, the HOST_API_LEVEL digest and the scenario schema golden all described the same REST and WebSocket surface, each with its own refresh step. packages/kap-server/test/apiSurface.test.ts now runs all three against the committed documents in packages/kap-server/schema: - openapi.json, asyncapi.json and contract.txt are the reviewed contract. The test compares them with the live server and lists each change as breaking, non-breaking or unclassified; `pnpm qa:refresh schema` rewrites them. The route table is part of these documents, so the separate snapshot is gone, and contract.txt replaces it as the contract tripwire. - The HOST_API_LEVEL pin hashes the same documents through the testkit's canonical form, so the golden and the pin agree on what is wording. Message titles now count as wording, like descriptions. That changes the pinned digest once; the API level stays 1. - Debug routes stay outside the contract and are listed explicitly, and GET / still answers 404. The canonical form now treats patternProperties keys as names, as the old digest did. * ci: record L0 results per shard instead of merging blob reports The "L0 protected tests" job failed on its first CI run. Vitest 4.1.4's --mergeReports crashed while restoring the module graph of the full run (TypeError: Cannot read properties of undefined (reading 'importers')), before any reporter saw a result. The gate needs test results, not the module graph. Each test shard now records its results through scripts/vitest-l0-gate.mjs, and the gate job checks the recorded files with Node, so Vitest no longer merges anything. Paths are recorded relative to the repository and resolved against it, so the check no longer depends on the working directory. A shard that leaves no result file still makes its protected tests count as missing. * test: run mutation testing on the changed lines of a pull request pnpm qa:mutation mutates the committed changes since the fork point with origin/main (or --base) in each package's src directory, and runs the related Vitest tests of that package through Stryker. It works in a throwaway git worktree with dependencies installed offline, so the working tree is never touched. Surviving and uncovered mutants go to .tmp/mutation/summary.md, with an HTML report per package. Static mutants rerun a whole package suite, so they are skipped unless --include-static is given. The Mutation testing workflow runs it on pull requests that change package sources and adds the summary to the job summary. It is informational, not a required check. A package whose related tests already fail under Stryker's single worker thread is listed with those tests instead of being mutated. Its first runs showed that the contract tests did not cover a change to WebSocket operations or messages alone, the "example" keyword, or shapes that differ only in wording; the tests now cover them. Stryker 9.6.1 keeps Babel 7, which the workspace already uses. Adding it to the root importer also makes pnpm re-resolve two optional peers of the root's own dependencies in the lockfile. * test: run the subprocess journeys on the built CLI as well TESTKIT_CLI_BUILD=dist makes kimiCliCommand run the published bundle, apps/kimi-code/dist/main.mjs, with plain Node: no tsx and no dev-server switch. The TUI and KAP subprocess fixtures pick it up unchanged. The CI build job, which already builds everything, now runs the TUI journeys and the cold-recovery scenario on the bundle after its smoke test, so a packaging mistake fails there rather than after a release. TestProcess.start refuses an entry file that does not exist, so a missing build fails at once instead of as a timeout. * test: keep Desktop E2E runs offline and free of host settings The Desktop fixture copied the whole host environment except KIMI_* variables, so model keys and proxy settings reached the app, and nothing noticed when the app went online. It now starts from the testkit's testEnv(), keeping the production defaults for the search worker and the read model, and points Kimi services at the test host. The Electron main process, including the embedded KAP server, now preloads the testkit network guard. A connection to anything but loopback is blocked and fails the test at teardown. The first run showed that every launch fetched the models.dev directory, so the fixture answers that request with 404 and the app falls back to its built-in snapshot, as it does offline. Requests from the renderer are not covered. TestProcess and the Desktop fixture share networkGuardEnv() for the guard's environment, and the testkit exports the preload path. * test: restart a KAP subprocess on its port and reconnect a live client KapProcess.restart() stops the CLI server, cleanly or with a crash, and starts a new process on the same data directory and port while keeping the client object. The origin stays the same. The --json token is ephemeral by design, so server.token becomes the new process's token. A new app-core scenario keeps the product's DaemonEventSocket open while the server is killed and restarted. The socket reconnects by itself, loads the same history again and follows the next turn to its end. It runs in qa:layers, so Layered QA also covers it on macOS and Windows. * test: list contract defaults and harden the mutation script The contract summary now records each field's default, so a changed default shows up in contract.txt, the file reviewers check as the KAP contract tripwire. A default that appears, changes or disappears is classified as unclassified: clients that omit the field get the new behavior, and a person has to judge whether that breaks them. contract.txt gains 45 defaults; the JSON documents and the API level digest are unchanged. The mutation script: - reports a package whose Vitest tests do not import the changed files as untested instead of failing (for example pi-tui, whose tests run on node:test); - no longer mutates test files that live under src; - keeps file names with spaces, quotes or non-ASCII letters, and turns off user diff settings that could widen the changed ranges; - removes its checkout on SIGTERM and SIGHUP as well as SIGINT, writes the summary before cleaning up, and reports a failed cleanup instead of hiding the results; - installs into the checkout from the repository's own pnpm store. * test: answer terminal queries in the TUI harness and add a real PTY smoke - VirtualTerminal.onReply() passes on what the emulated terminal answers, such as device attributes and the cursor position. The TUI harness forwards it to the CLI as a real terminal would, instead of letting the CLI's queries time out. - terminalFixturesWith({ columns, rows }) sets the terminal size, press() knows the navigation and editing keys, and type() returns once the typed text is on screen. - A real pseudo-terminal smoke runs the CLI under the system script command on macOS and Linux, finishes a first turn and exits. The same shell then prints the terminal modes, so a CLI that leaves the terminal raw fails the test. * test: record several KAP streams and replay mutated recordings Recording format 2 holds named streams, one per client connection and agent, with one normalizer across them, so the same ID gets the same token in every stream. KapRecorder.watch() adds a stream, also in the middle of a turn, and checkpoint() records every stream at once. replayKapRecording() replays one stream. mutateKapRecording() changes the frames of one checkpoint with dropFrames(), duplicateFrames() or insertUnknownFrame(), and each of them fails when it matches nothing. The first-turn recording adds a second client that subscribes while the model is held. The app-core replay now filters frame types like the production socket and checks that: - the late client reaches the same final view as the first one; - repeating any recorded frame leaves every view unchanged; - an unknown frame type is ignored. * test: compare KAP and ACP through a table of shared behaviors The capability ledger now lists the behaviors both protocols share: answering a first turn, cancelling a running turn and rejecting a file write. The parity test runs each one on KAP and on ACP, translates the endings into one vocabulary (KAP "interrupted" and ACP "cancelled" both mean cancelled), and checks both against the scenario's expected outcome, so the two cannot agree on the same mistake. A known divergence goes into "divergences" with its reason; its test then asserts that the divergence is still there and fails once both protocols meet the expectation. Every capability either protocol advertises must belong to a scenario or carry a reasoned exemption, and a guard test fails when the advertised set and the table drift apart. * test: capture released session corpora and widen the history perf trigger pnpm qa:capture-released <version> downloads the published CLI from npm, checks it against the registry integrity, installs it without install scripts and runs one offline turn against a loopback testkit provider. It then writes a new tests/scenarios/fixtures/released-<version> corpus with placeholders for the temporary paths, a manifest of digests and a README. A run for 2.6.3 reproduced the committed corpus: the same files and the same sequence of wire events. Cold recovery now runs for every released corpus, and a new test checks that each corpus matches its manifest: no unlisted, missing or changed file, and a writer that matches the directory. A corpus is never rewritten; a new writer version gets its own directory. Layered QA also runs when the chat rendering it measures changes, and nightly history-performance results are kept for 90 days so that a slow drift across versions stays visible. * ci: give every quarantined Desktop journey an owner and an expiry date tests/quarantine.yaml lists the nine Desktop journeys tagged @quarantine with their reason, owner, start date and expiry date. scripts/checks/quarantine.mjs runs in pnpm lint and fails when: - a journey is tagged but not listed, or listed but not found; - an entry has expired; - an expiry date is more than 60 days after the commit date; - a protected L0 or smoke journey is quarantined. Dates are compared with the date of the commit under test rather than the day of the run, so the check gives the same result for a commit whenever it runs, while new work cannot land on an expired quarantine. * fix(kap-server): report :wait settled only after the session is on disk :wait settled as soon as the turn left the in-memory activity view, but the engine writes wire records through a batched log that flushes in a later task. A server killed right after :wait reported idle could lose the end of the finished turn, so the cold-recovery scenario had to poll wire.jsonl before it crashed the process. Before it replies with a settled session, :wait now flushes the wire of every agent in the session and drains pending metadata writes. A failed write surfaces as an error instead of an idle reply. The KAP guide states the guarantee. A new test slows down the disk write of the turn end and checks that the record is on disk when :wait returns. The cold-recovery scenario now crashes right after the idle wait and no longer polls the wire; its WebSocket and REST consistency checks before the crash are left to the protected KAP first-turn smoke. * test: register the #4950 regression and four contract tests as L0 Register as L0: - the compaction test that retries after a context overflow that follows an LLM retry (#4950), verified to fail with the fix reverted; - the KAP contract golden; - the first-turn recording on the server side and its app-core replay; - cold recovery. Cold recovery is now one test that walks every released corpus, so capturing a new corpus does not need another ID. The gate self-tests no longer assume that the manifest holds only smoke entries, and they now check that a regression entry which passed only on retry is rejected. CODEOWNERS adds the three dedicated test files. fullCompaction.test.ts and apiSurface.test.ts are left out because many authors change them often. * test: wait for the session wire before crashing and move the :wait fix out The :wait durability fix moves to its own pull request (#5162), so this branch keeps only test infrastructure. Its kap-server change, the KAP guide sentence and the slow-disk test are removed here. Until that fix lands, :wait can reply before the finished turn reaches the disk. Cold recovery therefore again waits for the continued turn's turn.ended record in the session wire before it kills the process, and the server restart test waits for the first turn the same way. The L0 entry and the test guide no longer mention the :wait guarantee. * test: share the golden comparison and the baseline ratchet The new-code duplication check reported two clones in this branch. expectGolden and expectTextGolden repeated the refresh handling and the read of the committed file, which now live in one helper. The test-double check repeated how the oxlint ratchet compares, refuses to raise and rewrites its baseline; ratchet.mjs now exports that as ratchetBaseline, both checks call it, and a test covers each outcome. * chore: update the Nix pnpm dependency hash * test: compile the client modules before the conversation event tests On Windows the first test in conversation-events.test.ts also paid for compiling the whole client module graph: about 3.8 seconds of its 5 second budget. When a run went over, the unfinished send of that test reached the next test's shared API mock and failed it too. A beforeAll hook now imports the client once, so each test's timeout covers only its own work. * test: record the agent close endpoint in the KAP contract main added POST /api/v1/sessions/{session_id}/agents/{agent_id}:close and the agent_close capability (#5047), which it recorded in the API snapshot that this branch replaces. The refreshed OpenAPI document and contract summary list the two changes, both non-breaking. The contract digest is updated with the host API level kept at 1, as #5047 kept it. The KAP and ACP capability table lists agent_close as KAP-only, since ACP sessions have no side-channel agents. * test: quarantine the Desktop relaunch layout journey The journey that restores panel tabs, sidebar layout, pins and window size after a relaunch fails only on the CI macOS runner: the window comes back at the default 1440x900 instead of 1180x820. It passes locally and already failed before the network guard was added. It is tagged @quarantine and registered with an owner and an expiry date, so the nightly quarantine run keeps running it. * ci: run the Desktop E2E journeys in four shards The journeys ran in one Playwright worker on one macOS machine and took about 23 minutes. A plan job still picks the journeys as before and now splits them into up to four shards on separate machines, never more shards than changed spec files; each shard also runs the first-turn smoke that the other projects depend on. Going by the last run's time for each test, the slowest shard needs about 7 minutes. A result job reports every shard under the previous check name, so the check can be made required later without renaming it. * ci: check that fan-in jobs collect every result The L0 gate and the Desktop E2E result job turn several jobs into one check. If one stopped waiting for a job, stopped running after a failure or stopped reading a result, a failing job could leave the check green, because GitHub reports a skipped job as passed. The guards now read the registered fan-in jobs from registry.json and fail when a collected job is missing from needs, when the job is not run after failures, when the Desktop result job does not read a result, or when a new job in that workflow is left out of it. * ci: time out the test, L0 and build jobs These jobs had no timeout, so a hung run kept its runner for six hours. The test shards and the build job now stop after 20 minutes and the L0 gate after 10, several times their usual run time of about 5, 3.5 and 0.6 minutes. * test: record the context item segment field in the KAP contract main added an optional segment field ("reply", "thinking" or "tool_call") to the context item responses (#5175) and recorded it in the API snapshot that this branch replaces. The refreshed OpenAPI document and contract summary list the three new outputs, all non-breaking, and the contract digest is updated with the host API level kept at 1, as #5175 kept it. * ci: run desktop journeys on demand and stop mutation testing from killing the runner Desktop E2E now runs on a pull request only when it changes the journeys or carries the desktop-e2e label, in up to five shards. Every run takes five of the organization's macOS machines, so running it on every pull request that touches desktop or engine code would queue everything else behind it. main still runs every journey on each push and every night, and a failure there opens or updates one tracking issue that closes itself once main passes again. Mutation testing runs only on pull requests with the mutation label, with a 30-minute budget. It no longer mutates files that start or stop processes: a mutant that drops the PID guard in killProcessTree made the guard's own test send SIGKILL to the test runner's process group, or to every process of the user, which is why every run on this pull request ended with the runner losing contact. Stryker now runs in its own process group, and the processes it leaks are killed during and after the run. * test(desktop): assert the approved command's output inside its output panel The bash card highlights its command, so in `echo first-approved > first.txt && cat first.txt` the word first-approved is a span of its own, next to the same word in the output panel. Once highlighting finished, the transcript-wide exact-text locator matched both and failed in strict mode; it only passed when the assertion ran before the highlighter. It failed on CI that way, and waiting for the highlighted token first reproduces it on every run. The assertion now looks inside the output panel. * ci: keep the desktop journeys at four shards The organization runs at most five macOS jobs at once, and every push also starts the L0 smoke gate. Four shards plus the smoke gate fill the five machines exactly; with five shards one of them always queued behind it. The five-shard run took 15.3 minutes from start to finish against 12.9 with four, with shards waiting up to 6.2 minutes for a machine. * build(nix): update the pnpm dependency hash after merging main * test(cli): wait for the turn to finish before the terminal tests exit The TUI keeps a turn in its streaming phase after the answer is on screen, until the agent loop reports that it is idle. The terminal tests sent /exit as soon as the answer appeared, so on a busy machine the TUI refused it ("Cannot /exit while streaming") and the CLI never closed. The L0 first turn, the session helper tests and the PTY test failed this way on CI. Holding the model stream after the answer shows the window on every run: the answer is visible, /exit is refused, and the "Worked for ... done" summary only appears once the turn has ended. The tests now wait for that summary before they close the CLI. * test: record the session continue action in the KAP contract main added POST /api/v1/sessions/{session_id}:continue, advertised as the session_continue capability, with error code 40940 TURN_NOT_CONTINUABLE (#5048). Continuing starts model work, so the action can also answer with the sign-in errors 40110, 40111 and 40113; the session actions share one OpenAPI projection, so the six existing actions list those four responses as well. The refreshed OpenAPI document and contract summary record 146 changes, all non-breaking, and the contract digest is updated with the host API level kept at 1, as #5048 kept it. The capability ledger lists session_continue as KAP-only, since ACP has no request to continue a turn. * test(desktop): quarantine the composer drafts and models journey After main's #5048 came in, the journey failed once on CI, while it passed in the two runs before and twice locally. The trace shows the app itself presenting the model menu again: after choosing Off and pressing Escape the menu starts closing, then shows again with no further input and stays open past the 15-second timeout. That is a race in the product rather than in the test, so the journey is quarantined with an owner and an expiry while its cause is investigated, and the nightly run keeps running it without retries.
Mark MoonshotAI#5048, MoonshotAI#5068, MoonshotAI#5203 and MoonshotAI#5260 ported with executable grep probes and evidence from the fork commits that carried them.
Requirement or Bug
用户在手动终止(
:cancel/ 双击Esc)或因上游错误中断当前轮次、以及进程异常退出留下未完结轮次后,以往桌面端与 Web UI 只能伪造一条"Continue"用户消息发送,既污染对话历史,在手动终止态下甚至缺少一键继续入口。本 PR 新增服务端POST /api/v1/sessions/{session_id}:continue并在桌面端与 Web UI 完成接入(单仓合并后整合原客户端侧改动,替代 MoonshotAI/kimi-code-app#1323),支持无伪造用户消息的原位继续。Bug Reproduction Steps
N/A
Root Cause
N/A
Code Changes
核心思路
在引擎与服务端提供原生的无用户消息续跑动作
POST /api/v1/sessions/{session_id}:continue(通过meta.capabilities.session_continue宣告),客户端在「手动终止(interrupted)且输入框为空」时将发送按钮切换为实心继续按钮,在「非阻断失败(failed且end_reason !== 'blocked')」时将错误卡片原有的「继续」按钮改调:continue而不再伪造"Continue"用户消息。现有通过/prompts发送新消息的所有路径保持不变。flowchart LR subgraph UI["Desktop / Web UI"] ComposerBtn["Composer 空输入框继续按钮<br/>(仅 outcome === 'interrupted')"] ErrCard["错误卡片「继续」按钮<br/>(outcome === 'failed' && end_reason !== 'blocked')"] Pipeline["usePromptPipeline.continueSession<br/>+ continueTurnStartBySession 零闪烁桥接"] end subgraph Server["kap-server + agent-core-v2"] Route["POST /api/v1/sessions/{id}:continue"] Guard["resolveContinuableState()<br/>interrupted / non-blocked failed / hasUnfinishedTurn"] Remind["loop.remind(turn_continue)<br/>(仅已结轮次注入,UI 隐藏)"] Loop["IAgentLoopService.continueTurn()<br/>loop.continue({ force: true })"] end ComposerBtn --> Pipeline ErrCard --> Pipeline Pipeline --> Route --> Guard --> Remind --> Loop因为服务端把「是否允许继续」收口在
resolveContinuableState()(排除end_reason === 'blocked'与尾随被拒 prompt),所以客户端与外部 HTTP 调用方共用同一套可继续判据,不会把需要用户修改输入才能恢复的阻断态误放行。关键决策
outcome === 'interrupted'时把空输入框发送按钮切换为继续按钮;outcome === 'failed'时保持普通禁用发送按钮failed态也同时展示输入框继续按钮failed回合在消息流末尾已有带「继续」按钮的错误卡片,若底部输入框同时变成继续按钮会出现上下双继续入口打架;而interrupted末尾只有「已手动终止」分割线无按钮,正好由输入框承接agent: running之间的按钮状态promptStore记录continueTurnStartBySession,直到观测到agent: running、turn_begin或turn_end再结算turnActive切换:continue是非阻塞200 { continued: true },若不桥接中间几毫秒空窗,继续按钮会在点击后短暂闪回可点态Esc的视觉反馈.stop.is-armed)并缩小内部ESC字样尺寸body按全窗口居中,在展开左侧边栏时与右侧聊天区视觉中心错位;直接在终止按钮原位给出确认态更紧凑聚焦阅读指南
packages/agent-core-v2/src/agent/loop/loopService.ts— 看continueTurn()如何区分崩溃未结轮次与已结轮次并调用loop.continue({ force: true }),以及LoopSnapshot如何修正冷恢复未结轮次的state与hasUnfinishedTurn。packages/kap-server/src/routes/sessions.ts— 看resolveContinuableState()的可继续状态判据、40940 TURN_NOT_CONTINUABLE映射,以及turn_continue系统提醒注入时机。packages/app-client/src/client/usePromptPipeline.ts与packages/app-client/src/stores/prompt.ts— 看客户端canContinue计算条件、continueSession()请求流与continueTurnStartBySession状态桥接。packages/app-components/src/composer/Composer.vue与apps/desktop/src/renderer/components/chat/ConversationPane.vue— 看空输入框继续按钮、终止按钮确认态样式,以及错误卡片handleResumeTurn切换到@continue的接线。packages/app-core/src/api/、ChatDock.vue、App.vue、OpenAPI 快照、i18n 与单测/E2E 属于协议接线与验证,可略读。POST /api/v1/sessions/{id}:continue + if loop running / paused / compacting -> 40901 SESSION_BUSY + state = resolveContinuableState(snapshot, feed) + if state === 'none' -> 40940 TURN_NOT_CONTINUABLE + if state === 'ended' -> loop.remind(CONTINUE_INTERRUPTED_REMINDER, variant: 'turn_continue') + loop.continueTurn() -> 200 { continued: true } <ConversationPane> - handleResumeTurn() -> handleSubmit({ text: 'Continue', ... }) + handleResumeTurn() -> emit('continue') -> client.continueSession() <ChatDock> <Composer> + showContinueButton (empty draft && canContinue && outcome !== 'failed') + .stop.is-armed + scaled .stop-escScreenshots / Recordings
Esc:终止按钮切换为柔和浅红确认态,缩小后的ESC字样在按钮内留白充裕:interrupted)后输入框为空时,右下角发送按钮切换为实心圆角三角继续按钮;点击后直接原位续跑,不插入伪造的"Continue"用户消息气泡:failed)时,仅错误卡片保留「继续」按钮,底部空输入框维持常规禁用态发送按钮,避免上下双继续按钮重复:Behavior Changes and Affected Users
POST /api/v1/sessions/{session_id}:continue与meta.capabilities.session_continue40001),meta.capabilities无session_continuemain的崩溃未结、interrupted或非blocked的failed轮次并返回{ continued: true };运行中返回40901,新会话、completed、blocked或含尾随被拒 prompt 时返回40940 TURN_NOT_CONTINUABLE;meta.capabilities.session_continue为trueapiSurface.snapshot.test.ts.snap同步更新):continue时所有既有提交路径不变:continue续跑已结interrupted/failed轮次时的系统提醒文本:cancel仅注入"The user's next message continues the conversation."):continue续跑已结轮次时,追加一句origin: { kind: 'injection', variant: 'turn_continue' }隐藏提醒:"No new user message was sent. Continue the interrupted work from where it stopped; do not repeat steps that already completed."(约束模型接着已完成进度继续、不要重做已执行步骤)POST /api/v1/sessions/{id}:continue的会话接收该提醒;普通/prompts提交完全不触发POST /sessions/{id}/prompts)handleResumeTurn)'Continue'的真实用户消息,对话流中新增一条'Continue'用户气泡POST /api/v1/sessions/{id}:continue,对话流不再产生伪造的'Continue'用户消息气泡kimi-code-app)与浏览器 Web UI(kimi web)点击错误卡片「继续」的用户interrupted)且输入框无草稿/附件时的右下角主按钮LoopSnapshot.state在冷加载含崩溃未结轮次(loop.state.status === 'interrupted'且无活跃 fiber)时的返回值loop.state.turn非空返回'running''idle'并携带hasUnfinishedTurn: true'running'packages/agent-core-v2(agent/loop)、packages/kap-server(routes/sessions.ts、routes/meta.ts、openapi/transforms.ts、错误码与契约快照、docs/kap.md)、packages/app-core、packages/app-client、packages/app-components、packages/app-i18n、apps/desktop(含 Web UI 构建与 E2E)。blocked拒绝(40940/40901)与:cancel、上游failed后的无用户消息续跑闭环;客户端单测覆盖 API 路由、:continue期间continueTurnStartBySession零闪烁状态流转、interrupted空输入框切换继续按钮与有草稿/failed态回退发送按钮;真实kap-server+web-distChromium 实跑验证了完整交互链路。测试与检查明细
packages/kap-server/test/conversationContract.e2e.test.ts(S13端到端验证:continue各状态分支)packages/kap-server/test/apiSurface.snapshot.test.ts、packages/kap-server/test/services/conversation.test.tspackages/app-core/test/daemon-client.test.ts、packages/app-core/test/conversation.test.tspackages/app-client/test/conversation-events.test.ts、packages/app-client/test/useEscInterrupt.test.tspackages/app-components/test/composerRunningSendMode.test.tsapps/desktop/e2e/transcript-failures.spec.ts(更新错误卡片点击「继续」后不再出现伪造'Continue'用户气泡的断言)pnpm --filter kimi-code-app run typecheck、pnpm run lint(含check-comments、oxlint --type-aware --deny-warnings、check-import-boundaries、guards、ratchet、instructions)、pnpm run check:duplication origin/main、pnpm run build:web。Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.