@promptbook/cli 0.114.0-50 → 0.114.0-51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/apps/agents-server/README.md +2 -0
  2. package/apps/agents-server/src/app/AddAgentButton.tsx +4 -1
  3. package/apps/agents-server/src/app/dashboard/page.tsx +1 -0
  4. package/apps/agents-server/src/app/page.tsx +6 -7
  5. package/apps/agents-server/src/components/Header/Header.tsx +1 -0
  6. package/apps/agents-server/src/components/Header/useHeaderAgentMenus.tsx +5 -7
  7. package/apps/agents-server/src/components/Homepage/AgentsList.tsx +4 -1
  8. package/apps/agents-server/src/components/Homepage/AgentsListListView.tsx +4 -1
  9. package/apps/agents-server/src/components/Homepage/HomepagePrimarySections.tsx +4 -0
  10. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/ManGoNewAgentWizard.tsx +15 -7
  11. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/README.md +36 -0
  12. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/components/EmailTestRun.tsx +25 -53
  13. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/components/TestChat.tsx +23 -6
  14. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/components/steps/BookStep.tsx +16 -36
  15. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/components/steps/DoneStep.tsx +16 -55
  16. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/components/steps/KnowledgeStep.tsx +19 -48
  17. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/components/steps/TestStep.tsx +23 -88
  18. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/components/steps/ZadaniStep.tsx +11 -2
  19. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/services/agentEvalService.ts +9 -6
  20. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/services/agentTestService.ts +11 -7
  21. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/services/bookService.ts +15 -8
  22. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/services/postManGoOnboardingJson.ts +2 -0
  23. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/services/uploadService.ts +2 -2
  24. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/state/OnboardingProvider.tsx +24 -97
  25. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/state/createInitialOnboardingState.ts +28 -0
  26. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/state/createOnboardingActions.ts +262 -0
  27. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/state/createOnboardingSession.ts +168 -0
  28. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/state/retireLegacyOnboardingSnapshot.ts +14 -0
  29. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/state/runOnboardingOperation.ts +29 -0
  30. package/apps/agents-server/src/components/NewAgentDialog/ManGoNewAgentWizard/types.ts +27 -2
  31. package/apps/agents-server/src/components/NewAgentDialog/useNewAgentDialog.tsx +178 -58
  32. package/apps/agents-server/tests/e2e/e2eEnvironment.cjs +3 -0
  33. package/esm/index.es.js +36 -11
  34. package/esm/index.es.js.map +1 -1
  35. package/esm/scripts/verify-prompts/verify-prompts.d.ts +5 -0
  36. package/esm/src/version.d.ts +1 -1
  37. package/package.json +1 -1
  38. package/src/other/templates/getTemplatesPipelineCollection.ts +1133 -1530
  39. package/src/version.ts +2 -2
  40. package/src/versions.txt +1 -0
  41. package/umd/index.umd.js +36 -11
  42. package/umd/index.umd.js.map +1 -1
  43. package/umd/scripts/verify-prompts/verify-prompts.d.ts +5 -0
  44. package/umd/src/version.d.ts +1 -1
@@ -2,6 +2,8 @@
2
2
 
3
3
  Agents Server is the main web application where Promptbook agents live
4
4
 
5
+ The manGo new-agent wizard uses an independent creation session for every explicit opening. Work is retained across steps; closing or reloading abandons the in-memory draft. See [manGo creation sessions](./src/components/NewAgentDialog/ManGoNewAgentWizard/README.md) for lifecycle, recovery behavior and regression coverage.
6
+
5
7
  ## Local CLI configuration
6
8
 
7
9
  The installed CLI can initialize a local Agents Server project before it starts the packaged web app:
@@ -10,6 +10,8 @@ import { useServerLanguage } from '../components/ServerLanguage/ServerLanguagePr
10
10
  * Props for the AddAgentButton component.
11
11
  */
12
12
  type AddAgentButtonProps = {
13
+ /** Authenticated user/server scope used to abandon a manGo draft when the host changes. */
14
+ readonly creationScope?: string;
13
15
  /**
14
16
  * Folder identifier for the current list view, or null for the root.
15
17
  */
@@ -19,12 +21,13 @@ type AddAgentButtonProps = {
19
21
  /**
20
22
  * Renders the add-agent card and creation dialog workflow.
21
23
  */
22
- export function AddAgentButton({ currentFolderId }: AddAgentButtonProps) {
24
+ export function AddAgentButton({ currentFolderId, creationScope }: AddAgentButtonProps) {
23
25
  const { formatText } = useAgentNaming();
24
26
  const { t } = useServerLanguage();
25
27
  const addButtonLabel = formatText(t('agentCreation.addButtonLabel'));
26
28
 
27
29
  const { isPreparingDialog, openNewAgentDialog, dialog } = useNewAgentDialog({
30
+ creationScope,
28
31
  onCreateFailed: async (error) => {
29
32
  console.error('Failed to create agent:', error);
30
33
  await showAlert({
@@ -48,6 +48,7 @@ export default async function DashboardPage() {
48
48
  <div className="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50 dark:from-slate-950 dark:via-slate-950 dark:to-slate-900">
49
49
  <div className="container mx-auto px-4 py-16">
50
50
  <HomepagePrimarySections
51
+ creationScope={JSON.stringify([publicUrl.href, currentUser?.username])}
51
52
  agents={agents}
52
53
  folders={folders}
53
54
  isAdmin={isAdmin}
@@ -9,11 +9,7 @@ import { $provideServer } from '../tools/$provideServer';
9
9
  import { resolveDefaultAgentsStatus } from '../utils/defaultAgents/resolveDefaultAgentsStatus';
10
10
  import { isUserAdmin } from '../utils/isUserAdmin';
11
11
  import { isUserGlobalAdmin } from '../utils/isUserGlobalAdmin';
12
- import {
13
- createServerPublicUrl,
14
- resolveRegisteredServerByHost,
15
- type ServerRecord,
16
- } from '../utils/serverRegistry';
12
+ import { createServerPublicUrl, resolveRegisteredServerByHost, type ServerRecord } from '../utils/serverRegistry';
17
13
  import { listRegisteredServersUsingServiceRole } from '../utils/serverRegistryNode';
18
14
  import { isStandaloneVpsRawIpBootstrapActive } from '../utils/standaloneVpsRawIpBootstrap';
19
15
  import { getHomePageAgents } from './_data/getHomePageAgents';
@@ -40,7 +36,7 @@ export default async function HomePage() {
40
36
 
41
37
  const [{ publicUrl }, isAdmin, { agents, folders, homepageMessage, currentUser }] = await Promise.all([
42
38
  $provideServer(),
43
- isUserAdmin(), /* <- TODO: [??] Here should be user permissions */
39
+ isUserAdmin() /* <- TODO: [??] Here should be user permissions */,
44
40
  getHomePageAgents(),
45
41
  ]);
46
42
 
@@ -68,6 +64,7 @@ export default async function HomePage() {
68
64
  />
69
65
  )}
70
66
  <HomepagePrimarySections
67
+ creationScope={JSON.stringify([publicUrl.href, currentUser?.username])}
71
68
  agents={agents}
72
69
  folders={folders}
73
70
  isAdmin={isAdmin}
@@ -86,7 +83,9 @@ export default async function HomePage() {
86
83
  * @param host - Request host header.
87
84
  * @returns Routing instruction or `null` when normal homepage rendering should continue.
88
85
  */
89
- async function resolveIpAddressRouting(host: string | null): Promise<'LOGIN' | 'CONFIGURE' | ReadonlyArray<ServerRecord> | null> {
86
+ async function resolveIpAddressRouting(
87
+ host: string | null,
88
+ ): Promise<'LOGIN' | 'CONFIGURE' | ReadonlyArray<ServerRecord> | null> {
90
89
  if (!host || !isIpAddressHost(host)) {
91
90
  return null;
92
91
  }
@@ -191,6 +191,7 @@ export function Header(props: HeaderProps) {
191
191
  newAgentDialog,
192
192
  viewAllAgentsLabel,
193
193
  } = useHeaderAgentMenus({
194
+ creationScope: JSON.stringify([serverName, currentUser?.username]),
194
195
  activeAgent,
195
196
  activeAgentEmail,
196
197
  activeAgentFolderContext,
@@ -32,6 +32,8 @@ type HeaderTranslate = (key: ServerTranslationKey, variables?: Record<string, st
32
32
  * @private type of Header
33
33
  */
34
34
  type UseHeaderAgentMenusOptions = {
35
+ /** Authenticated user/server scope used to abandon a manGo draft when the host changes. */
36
+ readonly creationScope?: string;
35
37
  readonly activeAgent: AgentOrganizationAgent | null;
36
38
  readonly activeAgentEmail: string;
37
39
  readonly activeAgentFolderContext: AgentFolderContext | null;
@@ -148,6 +150,7 @@ async function showNewAgentFailure(
148
150
  * @private function of Header
149
151
  */
150
152
  export function useHeaderAgentMenus({
153
+ creationScope,
151
154
  activeAgent,
152
155
  activeAgentEmail,
153
156
  activeAgentFolderContext,
@@ -216,6 +219,7 @@ export function useHeaderAgentMenus({
216
219
  openNewAgentDialog,
217
220
  dialog: newAgentDialog,
218
221
  } = useNewAgentDialog({
222
+ creationScope,
219
223
  onCreateFailed: async (error) => {
220
224
  await showNewAgentFailure('Failed to create agent:', error, namingSingular, translate);
221
225
  },
@@ -265,13 +269,7 @@ export function useHeaderAgentMenus({
265
269
  handleCreateAgent,
266
270
  ),
267
271
  ],
268
- [
269
- agentMenuTreeWithActions,
270
- createNewAgentLabelNode,
271
- handleCreateAgent,
272
- isPreparingDialog,
273
- viewAllAgentsLabel,
274
- ],
272
+ [agentMenuTreeWithActions, createNewAgentLabelNode, handleCreateAgent, isPreparingDialog, viewAllAgentsLabel],
275
273
  );
276
274
 
277
275
  return {
@@ -12,6 +12,8 @@ import { useAgentsListState } from './useAgentsListState';
12
12
  * Props for the agents list component.
13
13
  */
14
14
  type AgentsListProps = {
15
+ /** Authenticated user/server scope used to abandon a manGo draft when the host changes. */
16
+ readonly creationScope?: string;
15
17
  /**
16
18
  * List of agents to display, each with basic information and visibility status
17
19
  */
@@ -44,7 +46,7 @@ type AgentsListProps = {
44
46
  * Renders the agents list with folder navigation and organization controls.
45
47
  */
46
48
  export function AgentsList(props: AgentsListProps) {
47
- const { canOrganize, isAdmin, publicUrl } = props;
49
+ const { creationScope, canOrganize, isAdmin, publicUrl } = props;
48
50
  const state = useAgentsListState(props);
49
51
  const contextMenuFolder = state.contextMenuFolder;
50
52
  const onDeleteContextMenuFolder =
@@ -89,6 +91,7 @@ export function AgentsList(props: AgentsListProps) {
89
91
  onSetHiddenFoldersVisible={state.setHiddenFoldersVisible}
90
92
  />
91
93
  <AgentsListListView
94
+ creationScope={creationScope}
92
95
  activeAgent={state.activeAgent}
93
96
  activeDragItemType={state.activeDragItemType}
94
97
  activeFolder={state.activeFolder}
@@ -25,6 +25,8 @@ import { SortableFolderCard } from './SortableFolderCard';
25
25
  * @private function of AgentsList
26
26
  */
27
27
  type AgentsListListViewProps = {
28
+ /** Authenticated user/server scope used to abandon a manGo draft when the host changes. */
29
+ readonly creationScope?: string;
28
30
  /**
29
31
  * Agent currently shown in the drag overlay.
30
32
  */
@@ -178,6 +180,7 @@ type SortableFolderCardProps = ComponentProps<typeof SortableFolderCard>;
178
180
  * @private function of AgentsList
179
181
  */
180
182
  export function AgentsListListView({
183
+ creationScope,
181
184
  activeAgent,
182
185
  activeDragItemType,
183
186
  activeFolder,
@@ -274,7 +277,7 @@ export function AgentsListListView({
274
277
  })}
275
278
  </SortableContext>
276
279
 
277
- {isAdmin && <AddAgentButton currentFolderId={currentFolderId} />}
280
+ {isAdmin && <AddAgentButton creationScope={creationScope} currentFolderId={currentFolderId} />}
278
281
  {canOrganize && (
279
282
  <Link
280
283
  href="/recycle-bin"
@@ -12,6 +12,8 @@ import { HomepageMessage } from './HomepageMessage';
12
12
  * Props for the shared homepage/dashboard agents section.
13
13
  */
14
14
  type HomepagePrimarySectionsProps = {
15
+ /** Authenticated user/server scope used to abandon a manGo draft when the host changes. */
16
+ readonly creationScope?: string;
15
17
  /**
16
18
  * Local agents rendered in the main agents list.
17
19
  */
@@ -42,6 +44,7 @@ type HomepagePrimarySectionsProps = {
42
44
  * Renders the homepage/dashboard sections that depend on folder/view query params.
43
45
  */
44
46
  export function HomepagePrimarySections({
47
+ creationScope,
45
48
  agents,
46
49
  folders,
47
50
  isAdmin,
@@ -56,6 +59,7 @@ export function HomepagePrimarySections({
56
59
  <>
57
60
  {!isSubfolderView && <HomepageMessage message={homepageMessage} />}
58
61
  <AgentsList
62
+ creationScope={creationScope}
59
63
  agents={[...agents]}
60
64
  folders={[...folders]}
61
65
  isAdmin={isAdmin}
@@ -1,7 +1,7 @@
1
1
  'use client';
2
2
 
3
3
  import type { string_book } from '@promptbook-local/types';
4
- import { useCallback, useMemo, useState } from 'react';
4
+ import { useCallback, useMemo, useSyncExternalStore } from 'react';
5
5
  import type { NewAgentWizardMode } from '../../../constants/newAgentWizard';
6
6
  import type { AgentVisibility } from '../../../utils/agentVisibility';
7
7
  import type { NewAgentOpenEditorRequest } from '../NewAgentOpenEditorRequest';
@@ -9,6 +9,7 @@ import { Dialog } from '../../Portal/Dialog';
9
9
  import { ONBOARDING_ENTRY_PATH, ONBOARDING_STEPS } from './config/steps';
10
10
  import { ManGoOnboardingNavigationContext } from './ManGoOnboardingNavigation';
11
11
  import { OnboardingProvider } from './state/OnboardingProvider';
12
+ import type { OnboardingSession } from './state/createOnboardingSession';
12
13
  import { WizardShell } from './components/WizardShell';
13
14
  import { BookStep } from './components/steps/BookStep';
14
15
  import { DoneStep, type ManGoCreatedAgentPayload } from './components/steps/DoneStep';
@@ -20,6 +21,10 @@ import { ZadaniStep } from './components/steps/ZadaniStep';
20
21
  * Props accepted by the imported manGo new-agent wizard.
21
22
  */
22
23
  type ManGoNewAgentWizardProps = {
24
+ /** Explicit creation lifetime supplied by the shared host before mounting any UI. */
25
+ readonly session: OnboardingSession;
26
+ /** Replaces the complete draft while retaining folder/visibility configuration. */
27
+ readonly onRestart: () => void;
23
28
  /**
24
29
  * Metadata-driven flow assignment used for analytics.
25
30
  */
@@ -118,11 +123,14 @@ function renderManGoWizardStep(props: {
118
123
  * @returns Fullscreen create-agent wizard dialog.
119
124
  */
120
125
  export function ManGoNewAgentWizard(props: ManGoNewAgentWizardProps) {
121
- const { defaultVisibility, onClose, onCreate, onOpenCreatedAgent, onOpenEditor } = props;
122
- const [currentPath, setCurrentPath] = useState(ONBOARDING_ENTRY_PATH);
123
- const navigateToPath = useCallback((path: string) => {
124
- setCurrentPath(path);
125
- }, []);
126
+ const { session, onRestart, defaultVisibility, onClose, onCreate, onOpenCreatedAgent, onOpenEditor } = props;
127
+ const { currentPath } = useSyncExternalStore(session.subscribe, session.getState, session.getState);
128
+ const navigateToPath = useCallback(
129
+ (path: string) => {
130
+ session.update({ currentPath: path });
131
+ },
132
+ [session],
133
+ );
126
134
  const navigationContextValue = useMemo(
127
135
  () => ({
128
136
  currentPath,
@@ -141,7 +149,7 @@ export function ManGoNewAgentWizard(props: ManGoNewAgentWizardProps) {
141
149
  className="!h-[100dvh] !w-screen !max-w-none !overflow-hidden !rounded-none !border-0 !bg-transparent !p-0 !shadow-none"
142
150
  >
143
151
  <ManGoOnboardingNavigationContext.Provider value={navigationContextValue}>
144
- <OnboardingProvider>
152
+ <OnboardingProvider session={session} onRestart={onRestart}>
145
153
  <WizardShell defaultVisibility={defaultVisibility} onOpenEditor={onOpenEditor}>
146
154
  {renderManGoWizardStep({
147
155
  currentPath,
@@ -0,0 +1,36 @@
1
+ # manGo creation sessions
2
+
3
+ `useNewAgentDialog` owns each explicit `MANGO_WIZARD` opening. It creates a random identity before mounting the wizard, ends the previous session synchronously, and mounts the provider with that identity. Start-over uses the same state factory while preserving the host's folder, visibility and mode. Account/server scope changes abandon the previous draft.
4
+
5
+ The provider exposes a session-owned in-memory store. Back/Next, rail navigation and provider remounts retain assignment inputs, edited Books, knowledge associations, test conversations/evaluation, pending operations, errors and saved identity. Local editor/file-input resources are mounted under the creation identity. No implicit draft recovery is supported after closing, cancelling, completing-and-leaving, or reloading the page. A later **New agent** action always starts empty. A deliberate classic-editor handoff carries only the current composed Book and the host's folder/visibility settings.
6
+
7
+ The old `onboarding:v2` snapshot is never read. Only that obsolete wizard entry is retired when opening manGo; unrelated drafts, authentication, storage and caches are untouched. Creation does not require browser storage, so malformed entries, blocked storage and exhausted quotas cannot restore another agent or prevent creation. There is no session snapshot to copy into another tab or authenticated-user/server scope.
8
+
9
+ Session operation tokens combine lifetime ownership with a request revision. Superseded generation/test requests and removed uploads are aborted where supported, and all results, failures and settlement callbacks also check ownership. Concurrent uploads have separate item tokens. Editing the assignment or Book supersedes a pending generation without erasing manual edits; explicit generation reads the latest assignment. Ordinary navigation retains the Book. Editing test inputs or Book/knowledge supersedes pending test/review work.
10
+
11
+ Saving uses the existing create-agent action, permissions, folder and visibility semantics. The session owns duplicate-submission protection across step/provider remounts and effect replay; failures retain the draft for explicit retry. Success is recorded before host notification, and completion retains its canonical identity for the correct chat action. Even if a server save finishes after cancellation, that outcome belongs to its original operation; it neither closes the replacement dialog nor deletes/retries the created agent. Reset removes draft associations and transient resources without deleting uploaded objects.
12
+
13
+ ## Reproduction and verification
14
+
15
+ Source inspection confirmed that the former provider hydrated every mount from `onboarding:v2`; Book generation skipped any nonempty restored Book, and completion reused any restored saved identifier. Client generation sends only the supplied name/brief to `/api/onboarding/book`. The server helper constructs a new `LiteAgent` per invocation; no shared backend agent or cache change is needed.
16
+
17
+ The two legacy-snapshot cases in `ManGoSession.integration.test.tsx` were executed against the host/provider/steps from `cc82cd1c97d8bc1cdb251d401a0ab62a29c296f1`, substituted by a temporary Jest transformer without changing the workspace sources. Both failed: after entering B's name/brief, its editor still contained A's Book and `KNOWLEDGE` marker, including for a completed snapshot. This was a deterministic React/jsdom reproduction, not a browser run or paid model call. Both cases pass with the session implementation.
18
+
19
+ `ManGoSession.integration.test.tsx` exercises the actual controller, provider, navigation and steps with deterministic generation/upload/persistence boundaries. `state/createOnboardingSession.test.ts` verifies independent collections/revisions, stale cleanup and the ownership of a late successful server save. `tests/e2e/mango-session-isolation.spec.ts` exercises the real browser, editor and host entry points with fixture AI/upload routes and the existing E2E mock database. It reads saved Books independently through the Book API and compares A after B/C creation. No production agents, real user uploads or paid model calls are involved.
20
+
21
+ Verification executed on 2026-10-07:
22
+
23
+ | Check | Result |
24
+ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
25
+ | Baseline Jest run filtered to `ignores a legacy A snapshot`, with the original host/provider/steps | 2 expected failures reproducing stale Book/knowledge content |
26
+ | `node node_modules/jest/bin/jest.js --runInBand apps/agents-server/src/components/NewAgentDialog` (repository root) | 10 suites, 59 tests passed |
27
+ | `npm run lint` (Agents Server) | Passed with zero warnings |
28
+ | `node scripts/build-e2e.js --no-lint` (Agents Server) | Production build passed, including type validation and 146 static pages; lint had already passed separately |
29
+ | `node ../../node_modules/playwright/cli.js test mango-session-isolation.spec.ts new-agent-redirect.spec.ts header-homepage-navigation.spec.ts --project=chromium`, with `PTBK_E2E_BUILD_READY=true` (Agents Server) | 10 browser tests passed together: 4 manGo regressions and 6 existing editor/navigation regressions |
30
+ | `node node_modules/typescript/bin/tsc --project .tmp/mango-session-verification/tsconfig.json --noEmit` (repository root) | Passed; the temporary configuration extends the app configuration and includes all changed TypeScript files, their imported dependencies and ambient declarations |
31
+ | Full Agents Server `tsc --noEmit` | Failed with 17 existing errors in 5 unchanged test files; no errors in touched code |
32
+ | `git diff --check` | Passed |
33
+
34
+ The full app type-check errors are in `agent-goal-chat-planned-messages/route.test.ts` (7), `StalwartMessageProvider.test.ts` (4), `enqueueAgentGoalChatTurn.test.ts` (2), `resolveInheritedAgentSource.test.ts` (3), and `getUserChatForJobRunner.test.ts` (1). They concern Jest mock types and test environment types; this fix leaves them unchanged. Next's production type validation and the explicit check including the changed tests both passed.
35
+
36
+ The first browser attempt encountered `ECONNRESET` while reading a saved fixture Book. That read now permits two transport retries; creation and content assertions are never retried. Combined runs also exposed duplicate metadata rows in the initial fixture setup and the existing warm metadata-cache timing when switching to Boilerplate. Fixture setup now updates an existing setting, and the editor regression waits for its configured surface through ordinary open/cancel actions. No production cache behavior was changed.
@@ -1,19 +1,13 @@
1
1
  'use client';
2
2
 
3
- import { useState } from 'react';
4
-
5
- import { createId } from '../lib/id';
6
3
  import { cn } from '../lib/cn';
7
- import { agentTestService } from '../services/agentTestService';
8
- import { evaluateReply, type ReplyCheck } from '../services/agentEvalService';
4
+ import { useOnboarding } from '../state/OnboardingProvider';
9
5
  import type { KnowledgeItem } from '../types';
10
6
  import { Badge } from './ui/Badge';
11
7
  import { Button } from './ui/Button';
12
8
  import { CONTROL } from './ui/Field';
13
9
  import { Spinner } from './ui/Spinner';
14
10
 
15
- type Phase = 'idle' | 'running' | 'done' | 'error';
16
-
17
11
  type EmailTestRunProps = {
18
12
  readonly email: string;
19
13
  readonly onEmailChange: (value: string) => void;
@@ -35,7 +29,10 @@ function RunStep({
35
29
  }) {
36
30
  return (
37
31
  <div className="flex gap-3 border-b border-zinc-100 py-3.5 last:border-b-0">
38
- <div className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-zinc-100 text-base" aria-hidden>
32
+ <div
33
+ className="flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-lg bg-zinc-100 text-base"
34
+ aria-hidden
35
+ >
39
36
  {icon}
40
37
  </div>
41
38
  <div className="min-w-0 flex-1">
@@ -53,48 +50,12 @@ function RunStep({
53
50
  );
54
51
  }
55
52
 
56
- export function EmailTestRun({ email, onEmailChange, bookSource, knowledge, onEditBook }: EmailTestRunProps) {
57
- const [phase, setPhase] = useState<Phase>('idle');
58
- const [reply, setReply] = useState('');
59
- const [error, setError] = useState<string | null>(null);
60
- const [checks, setChecks] = useState<ReplyCheck[] | null>(null);
61
- const [checksLoading, setChecksLoading] = useState(false);
62
-
53
+ /** Displays session-owned email generation and evaluation results. */
54
+ export function EmailTestRun({ email, onEmailChange, knowledge, onEditBook }: EmailTestRunProps) {
55
+ const { state, actions } = useOnboarding();
56
+ const { phase, reply, error, checks, isEvaluating: isChecksLoading } = state.emailTest;
63
57
  const readyKnowledge = knowledge.filter((item) => item.status === 'ready').length;
64
58
 
65
- async function run() {
66
- const text = email.trim();
67
- if (!text || phase === 'running') {
68
- return;
69
- }
70
- setPhase('running');
71
- setReply('');
72
- setChecks(null);
73
- setError(null);
74
-
75
- try {
76
- const result = await agentTestService.send({
77
- bookSource,
78
- knowledge,
79
- messages: [{ id: createId(), role: 'user', content: text }],
80
- });
81
- setReply(result.content);
82
- setPhase('done');
83
-
84
- setChecksLoading(true);
85
- try {
86
- setChecks(await evaluateReply({ bookSource, customerEmail: text, reply: result.content }));
87
- } catch {
88
- setChecks([]);
89
- } finally {
90
- setChecksLoading(false);
91
- }
92
- } catch (caught) {
93
- setError(caught instanceof Error ? caught.message : 'Testovací běh selhal.');
94
- setPhase('error');
95
- }
96
- }
97
-
98
59
  return (
99
60
  <div className="space-y-4">
100
61
  <div className="rounded-2xl border border-zinc-200/60 bg-white p-5 shadow-[var(--ob-shadow-sm)]">
@@ -113,7 +74,7 @@ export function EmailTestRun({ email, onEmailChange, bookSource, knowledge, onEd
113
74
  <Button
114
75
  isLoading={phase === 'running'}
115
76
  leadingIcon={<span aria-hidden>▶</span>}
116
- onClick={() => void run()}
77
+ onClick={() => void actions.runEmailTest()}
117
78
  disabled={email.trim().length === 0}
118
79
  >
119
80
  Spustit testovací běh
@@ -125,7 +86,11 @@ export function EmailTestRun({ email, onEmailChange, bookSource, knowledge, onEd
125
86
  <div className="rounded-2xl border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-800">
126
87
  <div className="font-medium">Testovací běh se nezdařil.</div>
127
88
  <p className="mt-1">{error}</p>
128
- <button type="button" onClick={() => void run()} className="mt-1 font-medium underline underline-offset-2">
89
+ <button
90
+ type="button"
91
+ onClick={() => void actions.runEmailTest()}
92
+ className="mt-1 font-medium underline underline-offset-2"
93
+ >
129
94
  Zkusit znovu
130
95
  </button>
131
96
  </div>
@@ -152,7 +117,9 @@ export function EmailTestRun({ email, onEmailChange, bookSource, knowledge, onEd
152
117
  </RunStep>
153
118
  <RunStep icon="🧠" title="Prohledání znalostí" done>
154
119
  {readyKnowledge > 0
155
- ? `${readyKnowledge} ${readyKnowledge === 1 ? 'zdroj' : 'zdroje/ů'} připojeno k agentovi.`
120
+ ? `${readyKnowledge} ${
121
+ readyKnowledge === 1 ? 'zdroj' : 'zdroje/ů'
122
+ } připojeno k agentovi.`
156
123
  : 'Bez znalostní báze — agent vychází jen z booku.'}
157
124
  </RunStep>
158
125
  <RunStep icon="✍️" title="Návrh odpovědi">
@@ -176,7 +143,7 @@ export function EmailTestRun({ email, onEmailChange, bookSource, knowledge, onEd
176
143
  {phase === 'done' && (
177
144
  <div className="border-t border-zinc-200 bg-zinc-50/60 px-4 py-3.5">
178
145
  <div className="mb-2 text-xs font-semibold text-zinc-500">Kontroly výsledku</div>
179
- {checksLoading ? (
146
+ {isChecksLoading ? (
180
147
  <div className="flex items-center gap-2 text-[13px] text-zinc-500">
181
148
  <Spinner className="h-4 w-4" /> Hodnotím odpověď proti booku…
182
149
  </div>
@@ -203,7 +170,12 @@ export function EmailTestRun({ email, onEmailChange, bookSource, knowledge, onEd
203
170
  <Button variant="outline" size="sm" onClick={onEditBook}>
204
171
  ✏️ Upravit book
205
172
  </Button>
206
- <Button variant="ghost" size="sm" leadingIcon={<span aria-hidden>↻</span>} onClick={() => void run()}>
173
+ <Button
174
+ variant="ghost"
175
+ size="sm"
176
+ leadingIcon={<span aria-hidden>↻</span>}
177
+ onClick={() => void actions.runEmailTest()}
178
+ >
207
179
  Spustit znovu
208
180
  </Button>
209
181
  </div>
@@ -12,6 +12,8 @@ import { CONTROL } from './ui/Field';
12
12
  const GREETING = '👋 Jsem připravený. Vložte zadání — třeba popis e-mailu od zákazníka — a ukážu vám, jak odpovím.';
13
13
 
14
14
  type TestChatProps = {
15
+ readonly inputValue: string;
16
+ readonly onInputChange: (value: string) => void;
15
17
  readonly messages: readonly ChatMessage[];
16
18
  readonly isSending: boolean;
17
19
  readonly onSend: (text: string) => void;
@@ -29,7 +31,12 @@ function Bubble({
29
31
  readonly footer?: ReactNode;
30
32
  }) {
31
33
  return (
32
- <div className={cn('group flex max-w-[85%] flex-col gap-1', role === 'user' ? 'items-end self-end' : 'items-start self-start')}>
34
+ <div
35
+ className={cn(
36
+ 'group flex max-w-[85%] flex-col gap-1',
37
+ role === 'user' ? 'items-end self-end' : 'items-start self-start',
38
+ )}
39
+ >
33
40
  <div
34
41
  className={cn(
35
42
  'whitespace-pre-wrap rounded-2xl px-3.5 py-2.5 text-[13px] leading-relaxed',
@@ -45,8 +52,15 @@ function Bubble({
45
52
  );
46
53
  }
47
54
 
48
- export function TestChat({ messages, isSending, onSend, onStop, onRetry }: TestChatProps) {
49
- const [text, setText] = useState('');
55
+ export function TestChat({
56
+ inputValue: text,
57
+ onInputChange,
58
+ messages,
59
+ isSending,
60
+ onSend,
61
+ onStop,
62
+ onRetry,
63
+ }: TestChatProps) {
50
64
  const [copiedId, setCopiedId] = useState<string | null>(null);
51
65
  const scrollRef = useRef<HTMLDivElement>(null);
52
66
 
@@ -60,7 +74,7 @@ export function TestChat({ messages, isSending, onSend, onStop, onRetry }: TestC
60
74
  return;
61
75
  }
62
76
  onSend(trimmed);
63
- setText('');
77
+ onInputChange('');
64
78
  }
65
79
 
66
80
  function copy(id: string, content: string) {
@@ -88,7 +102,10 @@ export function TestChat({ messages, isSending, onSend, onStop, onRetry }: TestC
88
102
  </span>
89
103
  </div>
90
104
 
91
- <div ref={scrollRef} className="flex max-h-[420px] min-h-[300px] flex-1 flex-col gap-3.5 overflow-y-auto p-4">
105
+ <div
106
+ ref={scrollRef}
107
+ className="flex max-h-[420px] min-h-[300px] flex-1 flex-col gap-3.5 overflow-y-auto p-4"
108
+ >
92
109
  <Bubble role="agent">{GREETING}</Bubble>
93
110
  {messages.map((message) =>
94
111
  message.role === 'agent' ? (
@@ -140,7 +157,7 @@ export function TestChat({ messages, isSending, onSend, onStop, onRetry }: TestC
140
157
  aria-label="Testovací zadání pro agenta"
141
158
  placeholder="Vložte testovací zadání pro agenta…"
142
159
  disabled={isSending}
143
- onChange={(event) => setText(event.target.value)}
160
+ onChange={(event) => onInputChange(event.target.value)}
144
161
  onKeyDown={(event) => event.key === 'Enter' && submit()}
145
162
  className={cn(CONTROL, 'py-2 disabled:opacity-60')}
146
163
  />
@@ -1,10 +1,9 @@
1
1
  'use client';
2
2
 
3
- import { useCallback, useEffect, useRef, useState } from 'react';
3
+ import { useEffect } from 'react';
4
4
 
5
5
  import { ONBOARDING_ENTRY_PATH, ONBOARDING_STEPS } from '../../config/steps';
6
6
  import { useManGoOnboardingNavigation } from '../../ManGoOnboardingNavigation';
7
- import { generateBook } from '../../services/bookService';
8
7
  import { useOnboarding } from '../../state/OnboardingProvider';
9
8
  import { ManGoBookEditor } from '../ManGoBookEditor';
10
9
  import { StepFooter, StepHeader } from '../StepFrame';
@@ -13,53 +12,34 @@ import { Button } from '../ui/Button';
13
12
  import { Card } from '../ui/Card';
14
13
  import { Spinner } from '../ui/Spinner';
15
14
 
16
- type Phase = 'init' | 'generating' | 'ready' | 'error';
17
-
15
+ /** Edits the active draft and requests deliberate Book replacement through the existing service. */
18
16
  export function BookStep() {
19
17
  const { navigateToPath } = useManGoOnboardingNavigation();
20
- const { state, isHydrated, update } = useOnboarding();
21
- const [phase, setPhase] = useState<Phase>('init');
22
- const [error, setError] = useState<string | null>(null);
23
- const startedRef = useRef(false);
24
-
18
+ const { state, update, actions } = useOnboarding();
19
+ const { phase, error } = state.bookGeneration;
25
20
  const isBriefAvailable = state.agentName.trim().length > 0 && state.agentBrief.trim().length > 0;
26
21
 
27
- const generate = useCallback(async () => {
28
- setPhase('generating');
29
- setError(null);
30
- try {
31
- const book = await generateBook({ agentName: state.agentName, agentBrief: state.agentBrief });
32
- update({ bookSource: book });
33
- setPhase('ready');
34
- } catch (caught) {
35
- setError(caught instanceof Error ? caught.message : 'Generování booku selhalo.');
36
- setPhase('error');
37
- }
38
- }, [state.agentName, state.agentBrief, update]);
39
-
40
- // Generate the Book once, after hydration completes — so we read the persisted
41
- // name/brief rather than the initial empty state. Runs a single time (startedRef),
42
- // reading the latest values from the closure captured when hydration flips true.
22
+ // The host resolves ownership before mounting. Navigation retains edits and pending work;
23
+ // synchronous session state also prevents duplicate generation during Strict Mode replay.
43
24
  useEffect(() => {
44
- if (!isHydrated || startedRef.current) {
25
+ if (phase !== 'init') {
45
26
  return;
46
27
  }
47
- startedRef.current = true;
48
-
49
- if (state.bookSource.trim().length > 0) {
50
- setPhase('ready');
51
- } else if (isBriefAvailable) {
52
- void generate();
28
+ if (!state.bookSource.trim() && isBriefAvailable) {
29
+ void actions.generate();
53
30
  } else {
54
- setPhase('ready');
31
+ update({ bookGeneration: { phase: 'ready', error: null } });
55
32
  }
56
- }, [generate, isBriefAvailable, isHydrated, state.bookSource]);
33
+ }, [actions, isBriefAvailable, phase, state.bookSource, update]);
57
34
 
58
35
  if (phase === 'init' || phase === 'generating') {
59
36
  return (
60
37
  <div className="mx-auto max-w-2xl">
61
38
  <StepHeader eyebrow="Definice agenta" title="Generujeme book" />
62
- <Card variant="elevated" className="flex flex-col items-center justify-center gap-5 px-8 py-20 text-center">
39
+ <Card
40
+ variant="elevated"
41
+ className="flex flex-col items-center justify-center gap-5 px-8 py-20 text-center"
42
+ >
63
43
  <span className="relative flex h-14 w-14 items-center justify-center">
64
44
  <span className="absolute inset-0 animate-ping rounded-full bg-[color:var(--ob-accent-200)] opacity-60" />
65
45
  <span className="relative flex h-14 w-14 items-center justify-center rounded-full bg-[color:var(--ob-accent-50)]">
@@ -108,7 +88,7 @@ export function BookStep() {
108
88
  <ManGoBookEditor
109
89
  value={state.bookSource}
110
90
  onChange={(value) => update({ bookSource: value })}
111
- onRegenerate={isBriefAvailable ? () => void generate() : undefined}
91
+ onRegenerate={isBriefAvailable ? () => void actions.generate() : undefined}
112
92
  />
113
93
 
114
94
  <StepFooter