Skip to content

feat(prompts): add back navigation to group (#39) - #617

Open
StringerBell69 wants to merge 3 commits into
bombshell-dev:mainfrom
StringerBell69:feat/group-back-navigation
Open

StringerBell69 wants to merge 3 commits into
bombshell-dev:mainfrom
StringerBell69:feat/group-back-navigation

Conversation

@StringerBell69

@StringerBell69 StringerBell69 commented Oct 15, 2026 •

Copy link
Copy Markdown

What does this PR do?

Adds opt-in back navigation to the group() utility. With group(prompts, { navigate: true }), pressing Shift+Tab returns to the previous step that showed a prompt. Answers are kept, and each step receives its earlier answer as previous, so passing it to initialValue restores what was entered. Back does nothing until a step has shown a prompt, and nothing changes for groups that don't opt in.

How I approached it (in my own words): I was building a CLI with clack (with Claude's help) and got really annoyed when I made a wrong keystroke and couldn't go back a step. I figured clack probably had this requested already if it was open source — found #39 — and wanted the least intrusive way to add a back option without changing how clack works for everyone else.

How it works

  • @clack/core: a new back action, unbound by default, so standalone prompts behave exactly as before. Prompt gets an internal Prompt.navigator hook (marked @internal) that group installs while it runs:
    • when back is pressed and the navigator allows it, the prompt erases its frame, tears down, and tells the navigator, without resolving. Steps never receive a back value, so there is no new symbol to type or check;
    • when a prompt is submitted or canceled, it reports how many rows it left on screen.
  • @clack/prompts: group() keeps a history of the steps that actually showed a prompt. Going back abandons the current step, erases what the target step left on screen, and reruns it with previous. Steps that showed no prompt (skipped conditional steps, async steps returning undefined, tasks) are passed over going back and run again going forward. group binds Shift+Tab to back only while a step that can go back is showing, and restores the previous alias state afterwards.

Known limitations

  • Output written by a non-prompt step (spinner, log) between two prompts isn't accounted for, so the erase can be off when going back over it.
  • Inside a date, Shift+Tab goes back to the previous step instead of the previous segment once going back is possible.
  • Code after the await in an abandoned step doesn't run.

Closes #39

Type of change

  • Bug fix
  • Feature
  • Refactor (no behavior change)
  • Documentation
  • Performance improvement
  • Tests
  • Chore (dependencies, CI, tooling)

Checklist

  • pnpm test passes (the only failing tests are 4 pre-existing note.test.ts snapshot cases that also fail on main in my environment, unrelated to this PR)
  • pnpm format has been run
  • I have added/updated tests for my changes (if applicable)
  • I have added a changeset

AI-generated code disclosure

  • This PR includes AI-generated code

Built with Claude (Anthropic). I described the problem and the "least intrusive" constraint, reviewed the design and the full diff, and ran the tests locally. Flagging it so reviewers can pay extra attention to the core keypress/render edges (the unresolved prompt on back, the row counting used to erase) and the group() alias handling.

@changeset-bot

changeset-bot Bot commented Oct 15, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 9e3fe06

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@clack/core Minor
@clack/prompts Minor

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

@StringerBell69
StringerBell69 force-pushed the feat/group-back-navigation branch 4 times, most recently from 8fb6fce to 8c4775b Compare October 15, 2026 15:25
@StringerBell69
StringerBell69 marked this pull request as ready for review October 15, 2026 15:25
@dreyfus92

Copy link
Copy Markdown
Member

hey @StringerBell69, thanks for picking this up! before i review, could you update the description to follow our pr template? looks like your agent wrote its own structure instead, so the type of change, checklist and ai disclosure sections are missing. i'd also love a short description in your own words of how you tackled this, it helps a lot to know where to focus on a change this size.

and since the description says it's a draft for design feedback, could you mark the pr as draft too?

@StringerBell69
StringerBell69 marked this pull request as draft October 15, 2026 16:24
@StringerBell69

StringerBell69 commented Oct 15, 2026 •

Copy link
Copy Markdown
Author

I was building a CLI with clack (with Claude's help) and got really annoyed when I made a wrong move and couldn't go back a step. I thought it was a misconfiguration on my end. I figured that someone else had probably hit the same thing, so I asked how to add a back option in the least intrusive way, without denaturing the app. That's why the whole thing is modeled on the existing cancel flow: the back action is unbound by default, standalone prompts are untouched, and the navigation logic lives in group().

I built this with Claude, but I reviewed the design and the full diff and ran the tests locally. Happy to adjust the approach. I'll be on my way back from school, so I won't be as responsive.

(wrote this in french and asked claude to translate)

@StringerBell69
StringerBell69 marked this pull request as ready for review October 16, 2026 13:13
@anthonydeseille

Copy link
Copy Markdown

Hello, and thanks for this PR. I also miss the ability to go back: I maintain a CLI built with clack that presents a long questionnaire with many conditional questions (where a question only appears based on a previous answer). After reading group.ts and testing your branch, I identified a scenario that would be a blocker for me: it is not possible to go back past a skipped step.

Within group(), a conditional step typically returns undefined to indicate that no input is required:

const result = await prompts.group({
  migration: () => prompts.select({ message: 'Migrations', options: [/* flyway, liquibase */] }),
  liquibaseFormat: ({ results }) =>
    results.migration === 'liquibase' ? prompts.select({ /* ... */ }) : undefined,
  libs: () => prompts.multiselect({ /* ... */ }),
});

If the user selects Flyway and then presses Shift+Tab while at the libs step:

  1. The index moves back to liquibaseFormat;
  2. The step is re-executed and immediately returns undefined (nothing is displayed);
  3. results.liquibaseFormat becomes undefined, the index increments, and focus returns to libs.

The cause: after index-- followed by continue, the loop "forgets" that it is moving backward. The skipped step returns undefined, which is treated as a valid response, and the process then resumes with index++.

A possible solution: keep a history of the steps that have been displayed. Navigating back would then return directly to the most recently viewed step, without re-traversing the skipped steps.

I reproduced the blockage on the branch (commit 8c4775b) using this test

import { BACK_SYMBOL } from '@clack/core';
import { expect, test } from 'vitest';
import * as prompts from '../src/index.js';

test('going back past a skipped (conditional) step reaches the step before it', async () => {
        const visits: string[] = [];
        let cBack = 0;
        await prompts.group({
                a: () => {
                        visits.push('a');
                        return Promise.resolve('a1');
                },
                b: () => {
                        visits.push('b');
                        return undefined; // conditional step, skipped
                },
                c: () => {
                        visits.push('c');
                        // The user presses Shift+Tab twice, then answers.
                        if (cBack < 2) {
                                cBack++;
                                return Promise.resolve(BACK_SYMBOL);
                        }
                        return Promise.resolve('c1');
                },
        });
        expect(visits.filter((v) => v === 'a').length).toBeGreaterThan(1);
});

Result: visits is equal to ["a","b","c","b","c","b","c"] and the test fails; 'a' is never revisited.

Drafted with AI assistance; I reviewed it.

Pressing Shift+Tab during a grouped prompt returns to the previous step,
discarding its answer and re-running the previous prompt.

- @clack/core: add a `back` action (unbound by default, so standalone
  prompts are unchanged), a `BACK_SYMBOL`/`isBack()` pair mirroring
  `CANCEL_SYMBOL`/`isCancel()`, and a `'back'` prompt state.
- @clack/prompts: rework `group()` into a navigable loop. Back is on by
  default (disable with `navigate: false`) and exposes `onBack`.

Closes bombshell-dev#39
Going back could not move past a step that opted out by returning
undefined: the skipped step re-ran, returned undefined again, and the
loop treated it as an answer and advanced, trapping focus on the next
step. Track the steps actually displayed and jump back to the most
recent one, skipping omitted conditional steps. onBack now reports the
real step returned to.
@StringerBell69
StringerBell69 force-pushed the feat/group-back-navigation branch from 8c4775b to 032ddab Compare November 30, 2026 14:42
@pkg-pr-new

pkg-pr-new Bot commented Nov 30, 2026

Copy link
Copy Markdown

commit: 032ddab

@dreyfus92 dreyfus92 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hey @StringerBell69, thanks for the fix on the skipped steps, and thanks @anthonydeseille for the repro 🙌 i pulled the branch and played with it, left a few comments inline. the main ones are the stuck back navigation on async steps and the type hole, the rest is cleanup

cc. @43081j for a second look on the design

Comment thread packages/prompts/src/group.ts Outdated
// Only a real prompt returns a thenable; a skipped conditional step
// returns `undefined`. We record the ones shown so `back` can skip the
// rest, and so the alias state above reflects what the user can see.
const displayed = typeof (step as Promise<unknown> | undefined)?.then === 'function';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

an async conditional step still gets stuck here since it always returns a promise. anthony's test with b: async () => undefined gives a, b, c, b, c, b, c. same with a non-prompt step like a spinner task, it re-runs every time you go back and you can't get past it

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9e3fe06. A step now counts as shown only if a prompt actually finished during it (core reports it to group), so async () => undefined and non-prompt steps like a spinner task are skipped going back, and run again going forward. Covered by the lifecycle test.

Comment thread packages/core/src/prompts/prompt.ts Outdated
if (this.state === 'back') {
// Going back: erase this step's output so navigation stays clean,
// rather than leaving a finalized frame behind like submit/cancel do.
this.restoreCursor();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this only erases the step you're leaving, so the steps you go back to get printed twice. going back from ok? to name? leaves name? paul / color? blue on screen two times

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed. Each finished prompt now reports how many rows it left on screen, and going back erases the step you return to before it redraws. There's a test that replays the output on a tiny terminal and checks the screen is the same as never going back.

Comment thread packages/core/src/prompts/prompt.ts Outdated

public prompt() {
return new Promise<TValue | typeof CANCEL_SYMBOL | undefined>((resolve) => {
type Resolution = TValue | typeof CANCEL_SYMBOL | typeof BACK_SYMBOL | undefined;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

text() and friends still cast this to T | typeof CANCEL_SYMBOL, so a step that awaits a prompt inside it gets BACK_SYMBOL typed as a string. if (isCancel(city)) return; city.toUpperCase() typechecks and throws on shift+tab

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good catch. I changed the mechanism so a step never sees a back value: on Shift+Tab the prompt no longer resolves, group abandons the step and moves back. That removes BACK_SYMBOL entirely, so the type hole is gone. The tradeoff is that code after the await in an abandoned step never runs. Since this is a design change, happy to go back to BACK_SYMBOL with opt-in only if you and 43081j prefer.

Comment thread packages/prompts/src/group.ts Outdated
): Promise<Prettify<PromptGroupAwaitedReturn<T>>> => {
const results = {} as any;
const promptNames = Object.keys(prompts);
const navigate = opts?.navigate !== false;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because of the type thing above, i'm wondering if this should be opt-in instead of on by default, since existing groups could break without changing anything

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, navigate now defaults to false, so existing groups behave exactly as before.

Comment thread packages/prompts/src/group.ts Outdated
// We bind Shift+Tab -> `back` only while a step that *can* go back is showing,
// and restore the previous alias state afterwards so we never clobber a user's
// own binding. We only manage the alias when the user hasn't bound it already.
const manageAlias = navigate && !settings.aliases.has(SHIFT_TAB_SEQUENCE);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure about group toggling the global shift+tab alias while it runs, @43081j what do you think?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Left this as is for now until 43081j weighs in.

Comment thread packages/prompts/src/index.ts Outdated
export type { ClackSettings } from '@clack/core';
export { CANCEL_SYMBOL, isCancel, settings, updateSettings } from '@clack/core';
export {
BACK_SYMBOL,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a fair bit of new public api (BACK_SYMBOL, isBack, a back state, navigate, onBack, previous). could we trim it to what group actually needs?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Trimmed: BACK_SYMBOL, isBack, the back state and event, and onBack are gone. What's left is navigate and previous on group, the back action (so the key can be remapped like cancel), and a Prompt.navigator hook marked @internal that group uses.

Comment thread packages/prompts/test/group.test.ts Outdated
});
});

describe('back navigation (core wiring)', () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the tests feel like a lot for this change, 16 tests and almost 280 lines with quite a bit of overlap. could we fold the back/previous/onBack/skip cases into one lifecycle test, keep the first step and navigate: false ones, and move these keypress tests to packages/core/test since that's what they cover?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: one lifecycle test (going back over an async empty step and a non-prompt step, answer restored), the first step and navigate: false ones, plus one screen test for the double print. The keypress tests moved to packages/core/test/prompts/prompt.test.ts.

Comment thread .changeset/group-back-navigation.md Outdated
Comment on lines +1 to +17
---
'@clack/core': minor
'@clack/prompts': minor
---

Add back navigation to `group`

The `group` utility can now return to a previous step. Pressing `Shift+Tab`
during a prompt returns to the previous one. Answers are kept, and each step
receives its previous answer as `previous`, so passing it to the prompt's
`initialValue` restores what the user had entered. It is on by default and can
be turned off with `group(prompts, { navigate: false })`; an
`onBack({ from, to, results })` callback is also available.

Under the hood this adds a `back` action to `@clack/core` (unbound by default, so
standalone prompts are unchanged), a `BACK_SYMBOL`/`isBack()` pair mirroring
`CANCEL_SYMBOL`/`isCancel()`, and a `'back'` prompt state. Closes #39.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

could you regenerate this with pnpm changeset? looks hand written and it's pretty long for a changelog entry. one or two sentences on what users get is plenty, the implementation details and closes #39 can live in the pr description

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Regenerated with pnpm changeset, it's one sentence now. The details and closes #39 are going in the PR description.

- Only count a step as shown when a prompt actually finished during it, so
  async conditional steps and non-prompt steps are skipped going back.
- Erase the step being returned to before it redraws, so nothing is
  printed twice.
- Going back no longer resolves the prompt with a symbol: the group
  abandons the step instead, so steps never see an unexpected value.
  This removes BACK_SYMBOL, isBack, the back state/event and onBack.
- Make navigation opt-in (navigate defaults to false).
- Fold the group tests, move keypress tests to core, regenerate the
  changeset.
@StringerBell69

Copy link
Copy Markdown
Author

Thanks @dreyfus92 for trying it out and for the detailed review, and @anthonydeseille for the original repro. Pushed 9e3fe06, replies are inline.

@43081j one design point for your second look: to fix the type hole and trim the API, going back no longer resolves the prompt with a BACK_SYMBOL, group abandons the step instead. If you'd rather keep the symbol (with navigation opt-in), I can switch back. The global Shift+Tab alias is unchanged for now.

Known limitations:

  • Output written by a non-prompt step (spinner, log) between two prompts isn't accounted for, so the erase can be off when going back over it.
  • Inside a date, Shift+Tab goes back to the previous step instead of the previous segment once going back is possible. I could let the date walk back through its segments first and only go back from the first one, if you'd like.
  • Code after the await in an abandoned step doesn't run.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Feature Request] Allow users to return to previous step.

3 participants