Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Skip the New file dialog when there is nothing to ask (PRD-7982) (#3559)
tim-inkeepc6d67fffa5a3
diff --git a/.changeset/new-file-shortcut-fast-path.md b/.changeset/new-file-shortcut-fast-path.mdnew file mode 100644index 000000000..4885c644c--- /dev/null+++ b/.changeset/new-file-shortcut-fast-path.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++The new-file keyboard shortcut now skips the dialog when there is nothing to ask. With no template resolved for the folder you're creating in, the only field left was a name you were about to retype in the editor anyway, so the shortcut creates an `untitled` doc (then `untitled-2`, `untitled-3`, …) and opens it straight away. Add a template for the folder and the dialog comes back, because now there's a real choice to make. The New file dialog itself also drops the "Start from" picker entirely when no templates resolve, instead of showing an empty picker plus a hint — that applies to every surface that still opens it (file tree, command palette, folder overview).diff --git a/packages/app/package.json b/packages/app/package.jsonindex f4cc36880..b19e1d7ab 100644--- a/packages/app/package.json+++ b/packages/app/package.json@@ -27,7 +27,7 @@"measure:stress": "bash scripts/measure-stress.sh","measure:sweep": "bash scripts/measure-sweep.sh","perf:compare": "bash scripts/perf-compare.sh",- "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts",+ "test:e2e": "playwright test tests/stress/ux-interactions.e2e.ts tests/stress/file-tree-create.e2e.ts tests/stress/file-tree-drag-to-root.e2e.ts tests/stress/file-tree-deselect-to-root.e2e.ts tests/stress/file-tree-collapse-spaced-folder.e2e.ts tests/stress/sidebar-file-list-fills.e2e.ts tests/stress/file-tree-sticky-collapse.e2e.ts tests/stress/create-then-rename-editable.e2e.ts tests/stress/find-replace.e2e.ts tests/stress/editor-tabs.e2e.ts tests/stress/crdt-stress.e2e.ts tests/stress/slash-command.e2e.ts tests/stress/paste-fidelity.e2e.ts tests/stress/fr-7a-disconnect-source-mode.e2e.ts tests/stress/docs-open.e2e.ts tests/stress/frozen-table-headers.e2e.ts tests/stress/asset-embed.e2e.ts tests/stress/asset-embed-advanced.e2e.ts tests/stress/asset-click-dispatch.e2e.ts tests/stress/handoff.e2e.ts tests/stress/multi-agent-presence.e2e.ts tests/stress/editor-mode-persistence.e2e.ts tests/stress/lint-config-toggle.e2e.ts tests/stress/plugin-enable-notice.e2e.ts tests/stress/schema-edit-fields-view.e2e.ts tests/stress/sidebar-search-pill.e2e.ts tests/stress/navigation-history.e2e.ts tests/stress/command-palette-semantic.e2e.ts tests/stress/agent-activity-panel.e2e.ts tests/stress/drop-pipeline-auto-open.e2e.ts tests/stress/command-palette-flicker.e2e.ts tests/stress/cm6-list-hanging-indent.e2e.ts tests/stress/ng7-rapid-nav-coherence.e2e.ts tests/stress/reveal-on-activate.e2e.ts tests/stress/selection-indicator.e2e.ts tests/stress/new-file-cross-doc-bleed.e2e.ts tests/stress/new-item-shortcut-fast-path.e2e.ts tests/stress/editor-mode-flip-cross-doc-bleed.e2e.ts tests/stress/editor-area-viewport-resize.e2e.ts tests/stress/qa-sidebar-responsive.e2e.ts tests/stress/prd-6955-reassertion-repro.e2e.ts tests/stress/prd-6955-reassertion-wedge.e2e.ts tests/stress/prd-6914-repro.e2e.ts tests/stress/showall-lazy-tree.e2e.ts tests/stress/tabs-component-strip.e2e.ts tests/stress/source-find-scroll.e2e.ts tests/stress/harness-app-warmth.e2e.ts tests/stress/qa-canary-authoring-both-modes.e2e.ts tests/stress/qa-canary-live-typing.e2e.ts tests/stress/keystroke-cadence-danger-space.e2e.ts tests/stress/jsx-unregistered-backspace-delete.e2e.ts tests/stress/jsx-unregistered-ime-concurrent.e2e.ts tests/stress/jsx-backspace-delete.e2e.ts tests/stress/link-authoring-bytes.e2e.ts tests/stress/link-authoring-apex.e2e.ts tests/stress/command-palette-parity.e2e.ts tests/stress/settings-search.e2e.ts tests/stress/okf-generated-index-settings.e2e.ts tests/stress/okf-recommended-skill-install.e2e.ts tests/stress/chip-popover-positioning.e2e.ts tests/stress/docs-open-scroll-restore.e2e.ts tests/stress/file-tree-decoration-chip-strip-repro.e2e.ts tests/stress/grip-click-nodeselect.e2e.ts tests/stress/jsx-halo-semantics.e2e.ts tests/stress/jsx-image-body-click.e2e.ts tests/stress/jsx-prop-panel-placeholder.e2e.ts tests/stress/jsx-range-encompass-halo.e2e.ts tests/stress/jsx-wildcard-convert.e2e.ts tests/stress/markdown-lint.e2e.ts tests/stress/frontmatter-schema-badge.e2e.ts tests/stress/frontmatter-glob-picker.e2e.ts tests/stress/unified-problems.e2e.ts tests/stress/mid-type-recovery.e2e.ts tests/stress/observer-a-multi-client.e2e.ts tests/stress/outline-toolbar-occlusion.e2e.ts tests/stress/quiet-tree-hidden-doc.e2e.ts tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts tests/stress/rename-noext-probe.e2e.ts tests/stress/show-ok-folders.e2e.ts tests/stress/source-polish.e2e.ts tests/stress/warm-skeleton-scroll-restore.e2e.ts tests/stress/props-toggle-scroll-preserve.e2e.ts tests/stress/yjs-no-dual-import.e2e.ts tests/stress/graph-panel-surfaces.e2e.ts tests/stress/asset-embed-real-fidelity.e2e.ts tests/stress/image-invalid-placeholder.e2e.ts tests/stress/local-target-audit.e2e.ts tests/stress/rename-content-preservation.e2e.ts tests/stress/rename-consolidation.e2e.ts tests/stress/outline-active-heading.e2e.ts tests/stress/outline-navigation.e2e.ts tests/stress/prd-7627-default-swatch.e2e.ts tests/stress/clipboard-dollar-math-source-fallback.e2e.ts tests/stress/source-mode-undo-keymap.e2e.ts tests/stress/timeline-recovered-restore.e2e.ts tests/stress/blank-line-preservation.e2e.ts tests/stress/landing-helpers.e2e.ts tests/stress/mode-switch-landing.e2e.ts tests/stress/mode-switch-ordinal-divergence.e2e.ts tests/stress/comment-annotation-visibility.e2e.ts tests/stress/comment-opens-in-panel.e2e.ts tests/stress/qa-miles-edge-blanks.e2e.ts tests/stress/prop-upload.e2e.ts tests/stress/slash-command-auto-open.e2e.ts tests/stress/clipboard-relative-url-source-fallback.e2e.ts tests/stress/editor-split-view.e2e.ts tests/stress/language-load-failure.e2e.ts tests/stress/language-first-paint.e2e.ts tests/stress/user-text-direction.e2e.ts tests/stress/pseudolocale.e2e.ts tests/stress/language-picker.e2e.ts tests/stress/zh-hans-coverage-sweep.e2e.ts tests/stress/preview-tab-promotion.e2e.ts tests/stress/cv-paint-lock-click.e2e.ts tests/stress/history-traversal-preview-tab.e2e.ts","test:e2e:install-browsers": "playwright install chromium webkit firefox","test:visual": "playwright test --config playwright.visual.config.ts","test:visual:update": "playwright test --config playwright.visual.config.ts --update-snapshots",diff --git a/packages/app/src/App.tsx b/packages/app/src/App.tsxindex 45c39dd60..f141dfef8 100644--- a/packages/app/src/App.tsx+++ b/packages/app/src/App.tsx@@ -1,5 +1,6 @@import { mediaKindForSidebarAssetExtension, SHOW_INSTALL_SKILL } from '@inkeep/open-knowledge-core';import { lazy, type ReactNode, Suspense, useEffect, useRef, useState } from 'react';+import { toast } from 'sonner';import { CommentQueueShortcut } from '@/comments/CommentQueueShortcut';import { CommandPalette } from '@/components/CommandPalette';import { ConnectingBanner } from '@/components/ConnectingBanner';@@ -39,9 +40,11 @@ import {import { EditorLifecycleFlush } from '@/editor/EditorLifecycleFlush';import { parseEditorTabId, tabIdForNavigationTarget } from '@/editor/editor-tabs';import { previewOpenDisposition } from '@/editor/preview-open-disposition';+import { useFolderConfig } from '@/hooks/use-folder-config';import { useInstalledClis } from '@/hooks/use-installed-clis';import { useReconcileSkillTabs } from '@/hooks/use-reconcile-skill-tabs';import { ConfigProvider, useConfigContext } from '@/lib/config-provider';+import { createPageRequest, nextUntitledDocName, openCreatedPage } from '@/lib/create-page-request';import {assetPathFromHash,docNameFromHash,@@ -539,9 +542,21 @@ function ActiveTargetBridgePush() {function NewItemShortcutHandler() {const { activeDocName, activeTarget } = useDocumentContext();+ const { pages, addPage } = usePageList();const [dialogOpen, setDialogOpen] = useState(false);const initialDir =activeTarget?.kind === 'folder' ? activeTarget.folderPath : defaultInitialDir(activeDocName);+ // Hoisted out of the dialog so the keydown path can read the resolved+ // cascade synchronously and decide whether the dialog has anything to ask.+ // Threaded back in via `folderConfig`, which puts the dialog's own+ // `useFolderConfig` on its null (no-fetch) branch — same one request.+ const folderConfig = useFolderConfig(initialDir);+ const folderState = folderConfig.state;+ // Held-down Cmd+N (or an impatient double-press) repeats the keydown while+ // the first create is still in flight. `pages` cannot grow until `addPage`+ // runs in the `.then`, so every repeat would pick the same name and lose to+ // the first with a 409 — a burst of error toasts for one intended doc.+ const createInFlightRef = useRef(false);useEffect(() => {function onKeyDown(e: KeyboardEvent) {@@ -550,7 +565,7 @@ function NewItemShortcutHandler() {// ShortcutEventLike shape used by the pure predicate.const target = e.target as { tagName?: string; isContentEditable?: boolean } | null;if (- isNewItemShortcut({+ !isNewItemShortcut({target,metaKey: e.metaKey,ctrlKey: e.ctrlKey,@@ -559,14 +574,54 @@ function NewItemShortcutHandler() {key: e.key,})) {- e.preventDefault();+ return;+ }+ e.preventDefault();+ // Nothing to start *from* and nothing else the dialog would ask about:+ // skip it and drop straight into an `untitled` doc. Any other state+ // (still loading, fetch failed, templates resolved) opens the dialog,+ // so the decision never blocks on a request from inside the keydown.+ if (+ folderState.status !== 'ready' ||+ (folderState.data.folder.templates_available ?? []).length > 0+ ) {setDialogOpen(true);+ return;}+ if (createInFlightRef.current) return;+ createInFlightRef.current = true;+ const docName = nextUntitledDocName(initialDir, pages);+ // `.md` is pinned here: the dialog's `.mdx` affordance is a typed-in+ // extension, and this path never takes a typed name.+ void createPageRequest({ path: `${docName}.md`, kind: 'file' })+ .then((result) => {+ // A create that loses a race (name taken since the page list last+ // refreshed) or fails on the wire toasts the reason and falls back to+ // the dialog rather than swallowing the keypress — the toast keeps the+ // first failure legible even though the reopened dialog starts clean.+ if (!result.ok) {+ toast.error(result.error);+ setDialogOpen(true);+ return;+ }+ openCreatedPage(result.docName, addPage);+ })+ // `createPageRequest` never throws, but `openCreatedPage` fans out a+ // synchronous `documents-changed` dispatch — a throwing listener would+ // otherwise surface as an unhandled rejection with the doc already+ // created and navigated to.+ .catch((err: unknown) => {+ console.warn('[NewItemShortcutHandler] create tail failed:', err);+ setDialogOpen(true);+ })+ .finally(() => {+ createInFlightRef.current = false;+ });}window.addEventListener('keydown', onKeyDown);return () => window.removeEventListener('keydown', onKeyDown);- }, []);+ }, [folderState, initialDir, pages, addPage]);return (<NewItemDialog@@ -574,6 +629,7 @@ function NewItemShortcutHandler() {onOpenChange={setDialogOpen}kind="file"initialDir={initialDir}+ folderConfig={folderConfig}/>);}diff --git a/packages/app/src/components/NewItemDialog.tsx b/packages/app/src/components/NewItemDialog.tsxindex 541f9da3e..9b14b2709 100644--- a/packages/app/src/components/NewItemDialog.tsx+++ b/packages/app/src/components/NewItemDialog.tsx@@ -1,6 +1,5 @@// biome-ignore-all lint/plugin/no-physical-direction-utility: pre-rule backlog — physical margin/padding/inset utilities predate the rule; drain by swapping ml/mr → ms/me, pl/pr → ps/pe, left/right → start/end, then deleting this line. See https://github.com/inkeep/open-knowledge/blob/main/biome-plugins/README.md#no-physical-direction-utilitygrit-import { CreatePageSuccessSchema } from '@inkeep/open-knowledge-core';import type { MessageDescriptor } from '@lingui/core';import { msg } from '@lingui/core/macro';import { Trans, useLingui } from '@lingui/react/macro';@@ -33,14 +32,13 @@ import {type TemplateMenuEntry,useFolderConfig,} from '@/hooks/use-folder-config';-import { emitDocumentsChanged } from '@/lib/documents-events';+import { createPageRequest, openCreatedPage } from '@/lib/create-page-request';import {isEditableShortcutTarget,matchesKeyboardShortcut,type ShortcutEventLike,type ShortcutPlatform,} from '@/lib/keyboard-shortcuts';-import { parseServerResponse } from '@/lib/parse-server-response';import { cn } from '@/lib/utils';import { type DocExtension, detectExtension } from './extension-picker-utils';import { sortTemplatesForPicker } from './template-picker-utils';@@ -265,10 +263,15 @@ export function NewItemDialog({const sorted = sortTemplatesForPicker(folderConfig.state.data.folder.templates_available ?? []);if (sorted.length > 0) setSelectedTemplate(sorted[0].name);}, [open, defaultToTemplate, initialTemplate, templateUserPicked, folderConfig.state]);- const showTemplatePicker = kind === 'file';const templatesLoading =folderConfig.state.status === 'loading' || folderConfig.state.status === 'idle';const templatesError = folderConfig.state.status === 'error' ? folderConfig.state.message : null;+ // With no templates resolved there is nothing to start *from*, so the+ // picker is pure chrome — hide it and let the dialog be name-only. Hidden+ // while the cascade loads too, so the common (no-template) case never+ // flashes a disabled combobox that then vanishes. Kept on error, since the+ // inline "could not load templates" notice hangs off this block.+ const showTemplatePicker = kind === 'file' && (templates.length > 0 || !!templatesError);function handleFileNameChange(next: string) {setFileName(next);@@ -300,7 +303,15 @@ export function NewItemDialog({return null;}- const isSubmitDisabled = busy || !fileName.trim() || (kind === 'folder' && !folderName.trim());+ // Submit waits out the cascade for files. The picker is hidden while it+ // loads, so in a template-bearing folder a fast typist would otherwise+ // submit before the choice ever rendered and get a blank doc, never knowing+ // a template was on offer.+ const isSubmitDisabled =+ busy ||+ !fileName.trim() ||+ (kind === 'folder' && !folderName.trim()) ||+ (kind === 'file' && templatesLoading);async function handleCreate() {const clientError = getClientError();@@ -318,46 +329,16 @@ export function NewItemDialog({// today's blank-doc behavior). Otherwise forward the template name.const templateParam =kind === 'file' && selectedTemplate !== BLANK_TEMPLATE_VALUE ? selectedTemplate : undefined;- const requestBody: { path: string; template?: string } = { path };- if (templateParam !== undefined) requestBody.template = templateParam;-- try {- const res = await fetch('/api/create-page', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(requestBody),- });- // Mutation flow — use the canonical parseServerResponse helper- // for consistency with sibling FileTree.tsx mutations (rename,- // delete). Surfaces the typed RFC 9457 title on error and the- // schema-parsed success body on success in one pass.- const status = res.status;- const parsed = await parseServerResponse(res, t`Server error (HTTP ${status})`);- if (!parsed.ok) {- setBusy(false);- setError(parsed.title);- setErrorField('form');- return;- }- const success = CreatePageSuccessSchema.safeParse(parsed.body);- setBusy(false);- if (!success.success) {- setError(kind === 'folder' ? t`Failed to create folder` : t`Failed to create file`);- setErrorField('form');- return;- }- const docName = success.data.docName;- onOpenChange(false);- window.location.hash = `#/${docName}`;- addPage(docName);- emitDocumentsChanged(['files', 'backlinks', 'graph']);- onCreated?.(docName);- } catch (err) {- console.warn('[NewItemDialog] create failed:', err);- setBusy(false);- setError(t`Network error — please try again`);+ const result = await createPageRequest({ path, template: templateParam, kind });+ setBusy(false);+ if (!result.ok) {+ setError(result.error);setErrorField('form');+ return;}+ onOpenChange(false);+ openCreatedPage(result.docName, addPage);+ onCreated?.(result.docName);}const dirDisplay = initialDir || t`(root)`;@@ -420,19 +401,6 @@ export function NewItemDialog({templates={templates}loading={templatesLoading}/>- {!templatesLoading && !templatesError && templates.length === 0 ? (- // Discoverability signpost: cmdk's CommandEmpty only fires- // on a search miss, not on a structurally-empty list. With- // the sidebar shortcut also hidden when no templates- // resolve, the user has no in-product hint about where- // templates come from.- <p className="text-1sm text-muted-foreground">- <Trans>- No templates yet. Add one in this folder's Templates section, or in Settings →- Templates.- </Trans>- </p>- ) : null}</div>)}{kind === 'folder' && (diff --git a/packages/app/src/lib/create-page-request.test.ts b/packages/app/src/lib/create-page-request.test.tsnew file mode 100644index 000000000..c10180bf2--- /dev/null+++ b/packages/app/src/lib/create-page-request.test.ts@@ -0,0 +1,80 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { createPageRequest, nextUntitledDocName } from './create-page-request';++describe('nextUntitledDocName', () => {+ it('starts at bare "untitled" at the content root', () => {+ expect(nextUntitledDocName('', new Set())).toBe('untitled');+ });++ it('prefixes the directory', () => {+ expect(nextUntitledDocName('notes/daily', new Set())).toBe('notes/daily/untitled');+ });++ it('skips taken names, numbering from 2', () => {+ expect(nextUntitledDocName('', new Set(['untitled']))).toBe('untitled-2');+ expect(nextUntitledDocName('', new Set(['untitled', 'untitled-2']))).toBe('untitled-3');+ });++ it('fills the first gap rather than appending past the highest', () => {+ expect(nextUntitledDocName('', new Set(['untitled', 'untitled-3']))).toBe('untitled-2');+ });++ it('scopes taken-ness to the directory', () => {+ // An `untitled` at the root does not push the one in `notes/` to -2.+ expect(nextUntitledDocName('notes', new Set(['untitled']))).toBe('notes/untitled');+ });+});++describe('createPageRequest', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ function stubFetch(impl: () => Promise<Response>) {+ vi.stubGlobal('fetch', vi.fn(impl));+ }++ it('returns the server docName on a 2xx success body', async () => {+ stubFetch(async () => new Response(JSON.stringify({ docName: 'untitled' }), { status: 200 }));+ const result = await createPageRequest({ path: 'untitled.md', kind: 'file' });+ expect(result).toEqual({ ok: true, docName: 'untitled' });+ });++ it('surfaces the RFC 9457 title on a server rejection', async () => {+ stubFetch(+ async () =>+ new Response(+ JSON.stringify({+ type: 'urn:ok:error:doc-already-exists',+ title: 'A file named untitled already exists',+ }),+ { status: 409, headers: { 'content-type': 'application/problem+json' } },+ ),+ );+ const result = await createPageRequest({ path: 'untitled.md', kind: 'file' });+ expect(result).toEqual({ ok: false, error: 'A file named untitled already exists' });+ });++ it('reports a kind-specific failure when a 2xx body is missing docName', async () => {+ // The server committed something the client cannot read back.+ stubFetch(async () => new Response(JSON.stringify({ unexpected: true }), { status: 200 }));+ expect(await createPageRequest({ path: 'untitled.md', kind: 'file' })).toEqual({+ ok: false,+ error: 'Failed to create file',+ });+ expect(await createPageRequest({ path: 'notes', kind: 'folder' })).toEqual({+ ok: false,+ error: 'Failed to create folder',+ });+ });++ it('comes back as a result rather than throwing when fetch rejects', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ stubFetch(async () => {+ throw new Error('offline');+ });+ const result = await createPageRequest({ path: 'untitled.md', kind: 'file' });+ expect(result).toEqual({ ok: false, error: 'Network error — please try again' });+ });+});diff --git a/packages/app/src/lib/create-page-request.ts b/packages/app/src/lib/create-page-request.tsnew file mode 100644index 000000000..f44670729--- /dev/null+++ b/packages/app/src/lib/create-page-request.ts@@ -0,0 +1,76 @@+import { CreatePageSuccessSchema } from '@inkeep/open-knowledge-core';+// The core macro, not `useLingui()`: this module is called from a plain+// keydown listener (App's new-item shortcut) as well as from React, so the+// messages have to resolve against the active catalog at call time.+import { t } from '@lingui/core/macro';+import { emitDocumentsChanged } from '@/lib/documents-events';+import { parseServerResponse } from '@/lib/parse-server-response';++/**+ * `POST /api/create-page` with the canonical response parse.+ *+ * Shared by `NewItemDialog` (which renders `error` inline) and the dialogless+ * Cmd+N fast path in `App.tsx` (which toasts `error` before falling back to+ * the dialog). Never throws — a network failure comes back as `{ ok: false }`+ * like a server rejection, so callers branch on `ok` instead of try/catch.+ *+ * Sibling `create-page.ts` wraps the same endpoint but throws instead of+ * returning a result union — new callers should prefer this never-throw shape.+ */+export async function createPageRequest(args: {+ path: string;+ template?: string;+ kind: 'file' | 'folder';+}): Promise<{ ok: true; docName: string } | { ok: false; error: string }> {+ const requestBody: { path: string; template?: string } = { path: args.path };+ if (args.template !== undefined) requestBody.template = args.template;++ try {+ const res = await fetch('/api/create-page', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(requestBody),+ });+ const status = res.status;+ const parsed = await parseServerResponse(res, t`Server error (HTTP ${status})`);+ if (!parsed.ok) return { ok: false, error: parsed.title };+ const success = CreatePageSuccessSchema.safeParse(parsed.body);+ if (!success.success) {+ return {+ ok: false,+ error: args.kind === 'folder' ? t`Failed to create folder` : t`Failed to create file`,+ };+ }+ return { ok: true, docName: success.data.docName };+ } catch (err) {+ console.warn('[create-page-request] create failed:', err);+ return { ok: false, error: t`Network error — please try again` };+ }+}++/**+ * Post-create tail shared by every create surface: navigate to the new doc,+ * seed it into the page list optimistically, and fan out the change event.+ */+export function openCreatedPage(docName: string, addPage: (docName: string) => void) {+ window.location.hash = `#/${docName}`;+ addPage(docName);+ emitDocumentsChanged(['files', 'backlinks', 'graph']);+}++/**+ * First free `untitled`, `untitled-2`, `untitled-3`, … docName in `dir`,+ * against the docNames the page list already knows about. Extension-less,+ * matching `PageListContext`'s `pages` set — callers append `.md`.+ *+ * Lowercase + hyphen (unlike the file-tree's transient `Untitled N`): this name+ * persists as the doc's filename and URL hash, so it stays URL-safe, and it+ * matches `doc-paths.ts`'s `untitled` fallback.+ */+export function nextUntitledDocName(dir: string, takenDocNames: ReadonlySet<string>): string {+ const prefix = dir ? `${dir}/` : '';+ for (let n = 1; ; n++) {+ const candidate = `${prefix}untitled${n === 1 ? '' : `-${n}`}`;+ if (!takenDocNames.has(candidate)) return candidate;+ }+}diff --git a/packages/app/src/locales/ar/messages.json b/packages/app/src/locales/ar/messages.jsonindex f674a6602..cb8c0338c 100644--- a/packages/app/src/locales/ar/messages.json+++ b/packages/app/src/locales/ar/messages.json@@ -4749,9 +4749,6 @@"ليس لديك إذن بالدفع إلى هذا المستودع. لا تزال «المتابعة» قادرة على إبقاء نسختك محدَّثة."],"uVbUP8": ["الإعدادات…"],- "uWtdQR": [- "لا توجد قوالب بعد. أضف واحدًا في قسم «القوالب» لهذا المجلد، أو في الإعدادات ← القوالب."- ],"u_lS4C": ["اكتمل الاستنساخ — يجري فتح المشروع"],"uaUc6t": ["إعادة تشغيل الخادم"],"ubMwcO": ["انتهت جلسة الطرفية (الإشارة ", ["0"], ")."],diff --git a/packages/app/src/locales/ar/messages.po b/packages/app/src/locales/ar/messages.poindex 46be87671..1e8ca6778 100644--- a/packages/app/src/locales/ar/messages.po+++ b/packages/app/src/locales/ar/messages.po@@ -5181,12 +5181,12 @@ msgid "Failed to clean up pending {kind}"msgstr "فشل تنظيف {kind} المعلق"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "فشل إنشاء الملف"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "فشل إنشاء المجلد"@@ -7798,7 +7798,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "خطأ في الشبكة - لا يزال {kind} «{createdPath}» موجودًا على القرص"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "خطأ في الشبكة — يرجى المحاولة مرة أخرى"@@ -8333,10 +8333,6 @@ msgstr "لا توجد قوالب متاحة"msgid "No templates found."msgstr "لم يُعثر على قوالب."-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "لا توجد قوالب بعد. أضف واحدًا في قسم «القوالب» لهذا المجلد، أو في الإعدادات ← القوالب."-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "لا توجد قوالب بعد. أضف واحدًا لتمنح المستندات الجديدة في هذا المجلد نقطة انطلاق جاهزة."@@ -11116,7 +11112,7 @@ msgstr "فاصل"msgid "Server can't open documents"msgstr "لا يستطيع الخادم فتح المستندات"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "خطأ في الخادم (HTTP {status})"diff --git a/packages/app/src/locales/bn/messages.json b/packages/app/src/locales/bn/messages.jsonindex 3c179d615..011a0d7de 100644--- a/packages/app/src/locales/bn/messages.json+++ b/packages/app/src/locales/bn/messages.json@@ -4064,9 +4064,6 @@"uUCrBv": ["সিমলিংক"],"uUiiyC": ["এই রিপোজিটরিতে পুশ করার অনুমতি আপনার নেই। Follow তবুও আপনার অনুলিপি হালনাগাদ রাখতে পারে।"],"uVbUP8": ["সেটিং…"],- "uWtdQR": [- "এখনও কোনো টেমপ্লেট নেই। এই ফোল্ডারের Templates বিভাগে, বা Settings → Templates-এ একটি যোগ করুন।"- ],"u_lS4C": ["ক্লোন সম্পূর্ণ — প্রকল্প খোলা হচ্ছে"],"uaUc6t": ["সার্ভার পুনরায় চালু করুন"],"ubMwcO": ["টার্মিনাল সেশন শেষ হয়েছে (সংকেত ", ["0"], ")।"],diff --git a/packages/app/src/locales/bn/messages.po b/packages/app/src/locales/bn/messages.poindex b14ff01ba..949d0b514 100644--- a/packages/app/src/locales/bn/messages.po+++ b/packages/app/src/locales/bn/messages.po@@ -5177,12 +5177,12 @@ msgid "Failed to clean up pending {kind}"msgstr "অপেক্ষমাণ {kind} পরিষ্কার করতে ব্যর্থ"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "ফাইল তৈরি করতে ব্যর্থ"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "ফোল্ডার তৈরি করতে ব্যর্থ"@@ -7794,7 +7794,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "নেটওয়ার্ক ত্রুটি - {kind} \"{createdPath}\" এখনও ডিস্কে আছে"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "নেটওয়ার্ক ত্রুটি — অনুগ্রহ করে আবার চেষ্টা করুন"@@ -8329,10 +8329,6 @@ msgstr "কোনো টেমপ্লেট নেই"msgid "No templates found."msgstr "কোনো টেমপ্লেট পাওয়া যায়নি।"-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "এখনও কোনো টেমপ্লেট নেই। এই ফোল্ডারের Templates বিভাগে, বা Settings → Templates-এ একটি যোগ করুন।"-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "এখনও কোনো টেমপ্লেট নেই। এই ফোল্ডারের নতুন নথিগুলোকে একটি তৈরি শুরুর বিন্দু দিতে একটি যোগ করুন।"@@ -11112,7 +11108,7 @@ msgstr "বিভাজক"msgid "Server can't open documents"msgstr "সার্ভার নথি খুলতে পারছে না"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "সার্ভার ত্রুটি (HTTP {status})"diff --git a/packages/app/src/locales/en/messages.json b/packages/app/src/locales/en/messages.jsonindex 39f3384f3..2a55e237c 100644--- a/packages/app/src/locales/en/messages.json+++ b/packages/app/src/locales/en/messages.json@@ -4197,9 +4197,6 @@"You don't have permission to push to this repo. Follow can still keep your copy up to date."],"uVbUP8": ["Settings…"],- "uWtdQR": [- "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."- ],"u_lS4C": ["Clone complete — opening project"],"uaUc6t": ["Restart server"],"ubMwcO": ["The terminal session ended (signal ", ["0"], ")."],diff --git a/packages/app/src/locales/en/messages.po b/packages/app/src/locales/en/messages.poindex ebe5cdd59..807e24732 100644--- a/packages/app/src/locales/en/messages.po+++ b/packages/app/src/locales/en/messages.po@@ -5181,12 +5181,12 @@ msgid "Failed to clean up pending {kind}"msgstr "Failed to clean up pending {kind}"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "Failed to create file"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "Failed to create folder"@@ -7798,7 +7798,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "Network error - {kind} \"{createdPath}\" still exists on disk"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "Network error — please try again"@@ -8333,10 +8333,6 @@ msgstr "No templates available"msgid "No templates found."msgstr "No templates found."-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "No templates yet. Add one to give new docs in this folder a ready-made starting point."@@ -11116,7 +11112,7 @@ msgstr "Separator"msgid "Server can't open documents"msgstr "Server can't open documents"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "Server error (HTTP {status})"diff --git a/packages/app/src/locales/es/messages.json b/packages/app/src/locales/es/messages.jsonindex 4b9b76a16..d8020fa17 100644--- a/packages/app/src/locales/es/messages.json+++ b/packages/app/src/locales/es/messages.json@@ -4834,9 +4834,6 @@"No tienes permiso para hacer push a este repositorio. Seguir puede mantener tu copia al día igualmente."],"uVbUP8": ["Ajustes…"],- "uWtdQR": [- "Todavía no hay plantillas. Añade una en la sección Plantillas de esta carpeta o en Ajustes → Plantillas."- ],"u_lS4C": ["Clonación completada: abriendo el proyecto"],"uaUc6t": ["Reiniciar el servidor"],"ubMwcO": ["La sesión de terminal terminó (señal ", ["0"], ")."],diff --git a/packages/app/src/locales/es/messages.po b/packages/app/src/locales/es/messages.poindex 2d2185a88..3f8d734cc 100644--- a/packages/app/src/locales/es/messages.po+++ b/packages/app/src/locales/es/messages.po@@ -5181,12 +5181,12 @@ msgid "Failed to clean up pending {kind}"msgstr "No se pudo limpiar {kind} pendiente"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "No se pudo crear el archivo"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "No se pudo crear la carpeta"@@ -7798,7 +7798,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "Error de red - {kind} \"{createdPath}\" sigue existiendo en el disco"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "Error de red: inténtalo de nuevo"@@ -8333,10 +8333,6 @@ msgstr "No hay plantillas disponibles"msgid "No templates found."msgstr "No se encontraron plantillas."-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "Todavía no hay plantillas. Añade una en la sección Plantillas de esta carpeta o en Ajustes → Plantillas."-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "Todavía no hay plantillas. Añade una para dar a los documentos nuevos de esta carpeta un punto de partida ya hecho."@@ -11116,7 +11112,7 @@ msgstr "Separador"msgid "Server can't open documents"msgstr "El servidor no puede abrir documentos"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "Error del servidor (HTTP {status})"diff --git a/packages/app/src/locales/fr/messages.json b/packages/app/src/locales/fr/messages.jsonindex 4ff2e6818..bb676cb47 100644--- a/packages/app/src/locales/fr/messages.json+++ b/packages/app/src/locales/fr/messages.json@@ -4886,9 +4886,6 @@"Vous n'avez pas la permission de pousser vers ce dépôt. Suivre peut tout de même maintenir votre copie à jour."],"uVbUP8": ["Paramètres…"],- "uWtdQR": [- "Pas encore de modèles. Ajoutez-en un dans la section Modèles de ce dossier, ou dans Paramètres → Modèles."- ],"u_lS4C": ["Clonage terminé — ouverture du projet"],"uaUc6t": ["Redémarrer le serveur"],"ubMwcO": ["La session de terminal s'est terminée (signal ", ["0"], ")."],diff --git a/packages/app/src/locales/fr/messages.po b/packages/app/src/locales/fr/messages.poindex 2e3edcae0..7da11375d 100644--- a/packages/app/src/locales/fr/messages.po+++ b/packages/app/src/locales/fr/messages.po@@ -5181,12 +5181,12 @@ msgid "Failed to clean up pending {kind}"msgstr "Échec du nettoyage du {kind} en attente"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "Échec de la création du fichier"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "Échec de la création du dossier"@@ -7798,7 +7798,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "Erreur réseau - {kind} « {createdPath} » existe encore sur le disque"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "Erreur réseau — veuillez réessayer"@@ -8333,10 +8333,6 @@ msgstr "Aucun modèle disponible"msgid "No templates found."msgstr "Aucun modèle trouvé."-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "Pas encore de modèles. Ajoutez-en un dans la section Modèles de ce dossier, ou dans Paramètres → Modèles."-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "Pas encore de modèles. Ajoutez-en un pour donner aux nouveaux documents de ce dossier un point de départ prêt à l'emploi."@@ -11116,7 +11112,7 @@ msgstr "Séparateur"msgid "Server can't open documents"msgstr "Le serveur ne peut pas ouvrir de documents"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "Erreur serveur (HTTP {status})"diff --git a/packages/app/src/locales/hi/messages.json b/packages/app/src/locales/hi/messages.jsonindex 7e03009d0..b2b89c58b 100644--- a/packages/app/src/locales/hi/messages.json+++ b/packages/app/src/locales/hi/messages.json@@ -4059,9 +4059,6 @@"आपके पास इस रिपॉज़िटरी में पुश करने की अनुमति नहीं है। Follow फिर भी आपकी प्रति को अद्यतित रख सकता है।"],"uVbUP8": ["सेटिंग…"],- "uWtdQR": [- "अभी कोई टेम्पलेट नहीं। इस फ़ोल्डर के Templates अनुभाग में, या Settings → Templates में एक जोड़ें।"- ],"u_lS4C": ["क्लोन पूर्ण — प्रोजेक्ट खोला जा रहा है"],"uaUc6t": ["सर्वर पुनः आरंभ करें"],"ubMwcO": ["टर्मिनल सत्र समाप्त हो गया (सिग्नल ", ["0"], ")।"],diff --git a/packages/app/src/locales/hi/messages.po b/packages/app/src/locales/hi/messages.poindex ecb008ccd..044f271c7 100644--- a/packages/app/src/locales/hi/messages.po+++ b/packages/app/src/locales/hi/messages.po@@ -5177,12 +5177,12 @@ msgid "Failed to clean up pending {kind}"msgstr "लंबित {kind} की सफ़ाई करने में विफल"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "फ़ाइल बनाने में विफल"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "फ़ोल्डर बनाने में विफल"@@ -7794,7 +7794,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "नेटवर्क त्रुटि - {kind} \"{createdPath}\" अब भी डिस्क पर मौजूद है"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "नेटवर्क त्रुटि — कृपया फिर कोशिश करें"@@ -8329,10 +8329,6 @@ msgstr "कोई टेम्पलेट उपलब्ध नहीं"msgid "No templates found."msgstr "कोई टेम्पलेट नहीं मिला।"-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "अभी कोई टेम्पलेट नहीं। इस फ़ोल्डर के Templates अनुभाग में, या Settings → Templates में एक जोड़ें।"-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "अभी कोई टेम्पलेट नहीं। इस फ़ोल्डर के नए दस्तावेज़ों को एक तैयार शुरुआती बिंदु देने के लिए एक जोड़ें।"@@ -11112,7 +11108,7 @@ msgstr "विभाजक"msgid "Server can't open documents"msgstr "सर्वर दस्तावेज़ नहीं खोल सकता"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "सर्वर त्रुटि (HTTP {status})"diff --git a/packages/app/src/locales/id/messages.json b/packages/app/src/locales/id/messages.jsonindex 196ad321e..42c8137ff 100644--- a/packages/app/src/locales/id/messages.json+++ b/packages/app/src/locales/id/messages.json@@ -4227,9 +4227,6 @@"Anda tidak punya izin push ke repo ini. Ikuti tetap bisa menjaga salinan Anda mutakhir."],"uVbUP8": ["Pengaturan…"],- "uWtdQR": [- "Belum ada templat. Tambahkan satu di bagian Templat folder ini, atau di Pengaturan → Templat."- ],"u_lS4C": ["Kloning selesai — membuka proyek"],"uaUc6t": ["Mulai ulang server"],"ubMwcO": ["Sesi terminal berakhir (sinyal ", ["0"], ")."],diff --git a/packages/app/src/locales/id/messages.po b/packages/app/src/locales/id/messages.poindex 64dd855c6..270deffd6 100644--- a/packages/app/src/locales/id/messages.po+++ b/packages/app/src/locales/id/messages.po@@ -5177,12 +5177,12 @@ msgid "Failed to clean up pending {kind}"msgstr "Gagal membersihkan {kind} yang tertunda"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "Gagal membuat berkas"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "Gagal membuat folder"@@ -7794,7 +7794,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "Galat jaringan - {kind} \"{createdPath}\" masih ada di disk"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "Galat jaringan — silakan coba lagi"@@ -8329,10 +8329,6 @@ msgstr "Tidak ada templat yang tersedia"msgid "No templates found."msgstr "Tidak ada templat yang ditemukan."-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "Belum ada templat. Tambahkan satu di bagian Templat folder ini, atau di Pengaturan → Templat."-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "Belum ada templat. Tambahkan satu agar dokumen baru di folder ini punya titik awal yang siap pakai."@@ -11112,7 +11108,7 @@ msgstr "Pemisah"msgid "Server can't open documents"msgstr "Server tidak bisa membuka dokumen"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "Galat server (HTTP {status})"diff --git a/packages/app/src/locales/ko/messages.json b/packages/app/src/locales/ko/messages.jsonindex cbe1bbafd..8f58d60aa 100644--- a/packages/app/src/locales/ko/messages.json+++ b/packages/app/src/locales/ko/messages.json@@ -4034,9 +4034,6 @@"이 저장소에 푸시할 권한이 없습니다. 팔로우를 사용하면 복사본을 최신 상태로 유지할 수 있습니다."],"uVbUP8": ["설정…"],- "uWtdQR": [- "아직 템플릿이 없습니다. 이 폴더의 템플릿 섹션이나 설정 → 템플릿에서 하나를 추가하세요."- ],"u_lS4C": ["클론 완료. 프로젝트 여는 중"],"uaUc6t": ["서버 재시작"],"ubMwcO": ["터미널 세션 종료(신호 ", ["0"], ")."],diff --git a/packages/app/src/locales/ko/messages.po b/packages/app/src/locales/ko/messages.poindex 7f344ede8..e34b94ffc 100644--- a/packages/app/src/locales/ko/messages.po+++ b/packages/app/src/locales/ko/messages.po@@ -5181,12 +5181,12 @@ msgid "Failed to clean up pending {kind}"msgstr "대기 중인 {kind} 정리에 실패했습니다"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "파일을 만들지 못했습니다"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "폴더를 만들지 못했습니다"@@ -7798,7 +7798,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "{kind} “{createdPath}”에 대한 네트워크 오류입니다. 해당 항목이 디스크에 여전히 있습니다."#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "네트워크 오류입니다. 다시 시도하세요."@@ -8333,10 +8333,6 @@ msgstr "템플릿을 사용할 수 없습니다"msgid "No templates found."msgstr "템플릿을 찾지 못했습니다."-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "아직 템플릿이 없습니다. 이 폴더의 템플릿 섹션이나 설정 → 템플릿에서 하나를 추가하세요."-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "아직 템플릿이 없습니다. 이 폴더의 새 문서에 바로 쓸 시작점을 제공하려면 하나 추가하세요."@@ -11116,7 +11112,7 @@ msgstr "구분선"msgid "Server can't open documents"msgstr "서버에서 문서를 열 수 없습니다"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "서버 오류 (HTTP {status})"diff --git a/packages/app/src/locales/pseudo/messages.json b/packages/app/src/locales/pseudo/messages.jsonindex 312d143a6..d1e362d7a 100644--- a/packages/app/src/locales/pseudo/messages.json+++ b/packages/app/src/locales/pseudo/messages.json@@ -4197,9 +4197,6 @@"Ŷōũ ďōń'ţ ĥàvē ƥēŕḿĩśśĩōń ţō ƥũśĥ ţō ţĥĩś ŕēƥō. Ƒōĺĺōŵ ćàń śţĩĺĺ ķēēƥ ŷōũŕ ćōƥŷ ũƥ ţō ďàţē."],"uVbUP8": ["Śēţţĩńĝś…"],- "uWtdQR": [- "Ńō ţēḿƥĺàţēś ŷēţ. Àďď ōńē ĩń ţĥĩś ƒōĺďēŕ'ś Ţēḿƥĺàţēś śēćţĩōń, ōŕ ĩń Śēţţĩńĝś → Ţēḿƥĺàţēś."- ],"u_lS4C": ["Ćĺōńē ćōḿƥĺēţē — ōƥēńĩńĝ ƥŕōĴēćţ"],"uaUc6t": ["Ŕēśţàŕţ śēŕvēŕ"],"ubMwcO": ["Ţĥē ţēŕḿĩńàĺ śēśśĩōń ēńďēď (śĩĝńàĺ ", ["0"], ")."],diff --git a/packages/app/src/locales/pseudo/messages.po b/packages/app/src/locales/pseudo/messages.poindex 4cf65858c..220c77c17 100644--- a/packages/app/src/locales/pseudo/messages.po+++ b/packages/app/src/locales/pseudo/messages.po@@ -5177,12 +5177,12 @@ msgid "Failed to clean up pending {kind}"msgstr ""#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr ""#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr ""@@ -7794,7 +7794,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr ""#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr ""@@ -8329,10 +8329,6 @@ msgstr ""msgid "No templates found."msgstr ""-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr ""-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr ""@@ -11112,7 +11108,7 @@ msgstr ""msgid "Server can't open documents"msgstr ""-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr ""diff --git a/packages/app/src/locales/pt-BR/messages.json b/packages/app/src/locales/pt-BR/messages.jsonindex 00105de95..a7b553fff 100644--- a/packages/app/src/locales/pt-BR/messages.json+++ b/packages/app/src/locales/pt-BR/messages.json@@ -4741,9 +4741,6 @@"Você não tem permissão para enviar a este repositório. Acompanhar ainda consegue manter sua cópia atualizada."],"uVbUP8": ["Configurações…"],- "uWtdQR": [- "Ainda não há modelos. Adicione um na seção Modelos desta pasta ou em Configurações → Modelos."- ],"u_lS4C": ["Clonagem concluída — abrindo o projeto"],"uaUc6t": ["Reiniciar o servidor"],"ubMwcO": ["A sessão de terminal terminou (sinal ", ["0"], ")."],diff --git a/packages/app/src/locales/pt-BR/messages.po b/packages/app/src/locales/pt-BR/messages.poindex 83885533b..0b07224ea 100644--- a/packages/app/src/locales/pt-BR/messages.po+++ b/packages/app/src/locales/pt-BR/messages.po@@ -5177,12 +5177,12 @@ msgid "Failed to clean up pending {kind}"msgstr "Falha ao limpar {kind} pendente"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "Falha ao criar o arquivo"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "Falha ao criar a pasta"@@ -7794,7 +7794,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "Erro de rede - {kind} \"{createdPath}\" ainda existe no disco"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "Erro de rede — tente de novo"@@ -8329,10 +8329,6 @@ msgstr "Nenhum modelo disponível"msgid "No templates found."msgstr "Nenhum modelo encontrado."-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "Ainda não há modelos. Adicione um na seção Modelos desta pasta ou em Configurações → Modelos."-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "Ainda não há modelos. Adicione um para dar aos novos documentos desta pasta um ponto de partida pronto."@@ -11112,7 +11108,7 @@ msgstr "Separador"msgid "Server can't open documents"msgstr "O servidor não consegue abrir documentos"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "Erro do servidor (HTTP {status})"diff --git a/packages/app/src/locales/ur/messages.json b/packages/app/src/locales/ur/messages.jsonindex dd7e7d16c..f263a0791 100644--- a/packages/app/src/locales/ur/messages.json+++ b/packages/app/src/locales/ur/messages.json@@ -4269,9 +4269,6 @@"آپ کو اس ریپو میں پُش کرنے کی اجازت نہیں۔ «پیروی» پھر بھی آپ کی نقل تازہ رکھ سکتی ہے۔"],"uVbUP8": ["ترتیبات…"],- "uWtdQR": [- "ابھی کوئی ٹیمپلیٹ نہیں۔ اس فولڈر کے «ٹیمپلیٹس» سیکشن میں، یا ترتیبات ← ٹیمپلیٹس میں ایک شامل کریں۔"- ],"u_lS4C": ["کلون مکمل — پروجیکٹ کھولا جا رہا ہے"],"uaUc6t": ["سرور دوبارہ چلائیں"],"ubMwcO": ["ٹرمینل کا سیشن ختم ہو گیا (سگنل ", ["0"], ")۔"],diff --git a/packages/app/src/locales/ur/messages.po b/packages/app/src/locales/ur/messages.poindex d6986699c..b47670bd4 100644--- a/packages/app/src/locales/ur/messages.po+++ b/packages/app/src/locales/ur/messages.po@@ -5181,12 +5181,12 @@ msgid "Failed to clean up pending {kind}"msgstr "زیرِ التوا {kind} کی صفائی نہیں ہو سکی"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "فائل نہیں بن سکی"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "فولڈر نہیں بن سکا"@@ -7798,7 +7798,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "نیٹ ورک کی خرابی - {kind} «{createdPath}» اب بھی ڈسک پر موجود ہے"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "نیٹ ورک کی خرابی — براہِ کرم دوبارہ کوشش کریں"@@ -8333,10 +8333,6 @@ msgstr "کوئی ٹیمپلیٹ دستیاب نہیں"msgid "No templates found."msgstr "کوئی ٹیمپلیٹ نہیں ملا۔"-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "ابھی کوئی ٹیمپلیٹ نہیں۔ اس فولڈر کے «ٹیمپلیٹس» سیکشن میں، یا ترتیبات ← ٹیمپلیٹس میں ایک شامل کریں۔"-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "ابھی کوئی ٹیمپلیٹ نہیں۔ اس فولڈر کی نئی دستاویزات کو تیار شدہ نقطۂ آغاز دینے کے لیے ایک شامل کریں۔"@@ -11116,7 +11112,7 @@ msgstr "علیحدہ کنندہ"msgid "Server can't open documents"msgstr "سرور دستاویزات نہیں کھول سکتا"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "سرور کی خرابی (HTTP {status})"diff --git a/packages/app/src/locales/zh-Hans/messages.json b/packages/app/src/locales/zh-Hans/messages.jsonindex eb7f936f5..bdad28bbf 100644--- a/packages/app/src/locales/zh-Hans/messages.json+++ b/packages/app/src/locales/zh-Hans/messages.json@@ -3713,7 +3713,6 @@"uUCrBv": ["符号链接"],"uUiiyC": ["你没有推送到这个仓库的权限。「跟随」仍然可以让你的副本保持最新。"],"uVbUP8": ["设置…"],- "uWtdQR": ["还没有模板。可在这个文件夹的「模板」区域添加,或在「设置 → 模板」中添加。"],"u_lS4C": ["克隆完成——正在打开项目"],"uaUc6t": ["重启服务器"],"ubMwcO": ["终端会话已结束(信号 ", ["0"], ")。"],diff --git a/packages/app/src/locales/zh-Hans/messages.po b/packages/app/src/locales/zh-Hans/messages.poindex b33eba02b..9dcd0b20d 100644--- a/packages/app/src/locales/zh-Hans/messages.po+++ b/packages/app/src/locales/zh-Hans/messages.po@@ -5181,12 +5181,12 @@ msgid "Failed to clean up pending {kind}"msgstr "清理待处理的{kind}失败"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "创建文件失败"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "创建文件夹失败"@@ -7798,7 +7798,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "网络错误 - {kind}“{createdPath}”在磁盘上仍然存在"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "网络错误——请重试"@@ -8333,10 +8333,6 @@ msgstr "没有可用的模板"msgid "No templates found."msgstr "没有找到模板。"-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "还没有模板。可在这个文件夹的「模板」区域添加,或在「设置 → 模板」中添加。"-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "还没有模板。添加一个,让这个文件夹中的新文档有个现成的起点。"@@ -11116,7 +11112,7 @@ msgstr "分隔符"msgid "Server can't open documents"msgstr "服务器无法打开文档"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "服务器错误(HTTP {status})"diff --git a/packages/app/src/locales/zh-Hant/messages.json b/packages/app/src/locales/zh-Hant/messages.jsonindex 50bf9a300..56b2c0cd9 100644--- a/packages/app/src/locales/zh-Hant/messages.json+++ b/packages/app/src/locales/zh-Hant/messages.json@@ -3743,7 +3743,6 @@"uUCrBv": ["符號連結"],"uUiiyC": ["你沒有推送到這個儲存庫的權限。「跟隨」仍然可以讓你的副本保持最新。"],"uVbUP8": ["設定…"],- "uWtdQR": ["還沒有範本。可以在這個資料夾的「範本」區塊加一個,或在「設定 → 範本」中新增。"],"u_lS4C": ["複製完成——正在開啟專案"],"uaUc6t": ["重新啟動伺服器"],"ubMwcO": ["終端機工作階段已結束(訊號 ", ["0"], ")。"],diff --git a/packages/app/src/locales/zh-Hant/messages.po b/packages/app/src/locales/zh-Hant/messages.poindex 66008a3a1..d86c3baeb 100644--- a/packages/app/src/locales/zh-Hant/messages.po+++ b/packages/app/src/locales/zh-Hant/messages.po@@ -5181,12 +5181,12 @@ msgid "Failed to clean up pending {kind}"msgstr "清理待處理的{kind}失敗"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create file"msgstr "建立檔案失敗"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Failed to create folder"msgstr "建立資料夾失敗"@@ -7798,7 +7798,7 @@ msgid "Network error - {kind} \"{createdPath}\" still exists on disk"msgstr "網路錯誤 - {kind}「{createdPath}」在磁碟上仍然存在"#: src/components/FileTree.tsx-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Network error — please try again"msgstr "網路錯誤——請再試一次"@@ -8333,10 +8333,6 @@ msgstr "沒有可用的範本"msgid "No templates found."msgstr "找不到範本。"-#: src/components/NewItemDialog.tsx-msgid "No templates yet. Add one in this folder's Templates section, or in Settings → Templates."-msgstr "還沒有範本。可以在這個資料夾的「範本」區塊加一個,或在「設定 → 範本」中新增。"-#: src/components/TemplatesCard.tsxmsgid "No templates yet. Add one to give new docs in this folder a ready-made starting point."msgstr "還沒有範本。加一個,讓這個資料夾裡的新文件有個現成的起點。"@@ -11116,7 +11112,7 @@ msgstr "分隔線"msgid "Server can't open documents"msgstr "伺服器無法開啟文件"-#: src/components/NewItemDialog.tsx+#: src/lib/create-page-request.tsmsgid "Server error (HTTP {status})"msgstr "伺服器錯誤(HTTP {status})"diff --git a/packages/app/tests/stress/new-file-cross-doc-bleed.e2e.ts b/packages/app/tests/stress/new-file-cross-doc-bleed.e2e.tsindex 4bb5cd170..92d206e17 100644--- a/packages/app/tests/stress/new-file-cross-doc-bleed.e2e.ts+++ b/packages/app/tests/stress/new-file-cross-doc-bleed.e2e.ts@@ -92,33 +92,71 @@ const CM6_BODY = [const CANARY = 'CANARY_CROSS_DOC_BLEED_TOKEN_XYZ_123456789ABCDEF';/**- * Trigger NewItemDialog via the browser-safe Cmd+Alt+N (or Ctrl+Alt+N) shortcut,- * submit a brand-new docName, and wait for the new file's editor to mount.- *- * Settlement: wait for the new doc's HocuspocusProvider to finish initial- * sync (`window.__activeProvider?.isSynced`), then yield two paint frames so- * React's commit + TipTap's `EditorContent.componentDidMount` + the- * move-all-siblings code path complete before the caller asserts. This is- * the condition-based equivalent of the empirical-driver's 2500ms wall-clock- * settle — STOP-rule compliant and still observing only user-visible- * state (the provider's synced flag is the standard editor-ready signal per- * `_helpers/provider.ts`).+ * Defocus the editor so the global shortcut isn't suppressed by an INPUT /+ * TEXTAREA / contenteditable target (per isNewItemShortcut's guard in+ * components/NewItemDialog.tsx). Waits for focus to actually land on body —+ * browser focus dispatch is async on some platforms.*/-async function newFileViaShortcut(page: Page, newDocName: string): Promise<void> {- // Defocus the editor so the global shortcut isn't suppressed by an INPUT /- // TEXTAREA / contenteditable target (per isNewItemShortcut's guard in- // components/NewItemDialog.tsx). Wait for focus to actually land on body —- // browser focus dispatch is async on some platforms.+async function blurToBody(page: Page): Promise<void> {await page.locator('body').click({ position: { x: 5, y: 5 } });await page.waitForFunction(() => document.activeElement === null || document.activeElement === document.body,null,{ timeout: 1_000 },);+}++/**+ * Settle the freshly-created doc: wait for its HocuspocusProvider to finish+ * initial sync (`window.__activeProvider?.isSynced`), then yield two paint+ * frames so React's commit + TipTap's `EditorContent.componentDidMount` + the+ * move-all-siblings code path complete before the caller asserts. This is+ * the condition-based equivalent of the empirical-driver's 2500ms wall-clock+ * settle — STOP-rule compliant and still observing only user-visible+ * state (the provider's synced flag is the standard editor-ready signal per+ * `_helpers/provider.ts`).+ */+async function settleNewFile(page: Page): Promise<void> {+ await waitForActiveProviderSynced(page);+ await yieldFramesInPage(page);+ await yieldFramesInPage(page);+}++/**+ * Create a file via the browser-safe Cmd+Alt+N (or Ctrl+Alt+N) shortcut and+ * wait for the new file's editor to mount. The worker fixture's contentDir+ * carries no templates, so the shortcut skips the dialog and drops straight+ * into a fresh `untitled` doc. The tests here assert on the new doc's editor,+ * not its name, so the name it picked is not surfaced.+ */+async function newFileViaShortcut(page: Page): Promise<void> {+ await blurToBody(page);+ const beforeHash = await page.evaluate(() => window.location.hash);const modKey = process.platform === 'darwin' ? 'Meta' : 'Control';await page.keyboard.press(`${modKey}+Alt+KeyN`);+ await page.waitForFunction((prev) => window.location.hash !== prev, beforeHash, {+ timeout: 10_000,+ });+ await expect(page.getByRole('dialog', { name: /New file/i })).toBeHidden();++ await settleNewFile(page);+}++/**+ * Create a file at a caller-chosen docName via the command palette's "New+ * file" command, which still routes through NewItemDialog. The keyboard+ * shortcut can't drive this case — it names the doc itself.+ */+async function newFileViaPalette(page: Page, newDocName: string): Promise<void> {+ await blurToBody(page);+ await page.keyboard.press('ControlOrMeta+KeyK');+ await page+ .getByRole('option', { name: /^New file/ })+ .first()+ .click();+await expect(page.getByRole('dialog', { name: /New file/i })).toBeVisible({timeout: 5_000,});@@ -134,11 +172,7 @@ async function newFileViaShortcut(page: Page, newDocName: string): Promise<void>timeout: 10_000,});- // New doc's provider finished handshake + initial Y.Doc sync.- await waitForActiveProviderSynced(page);- // Two paint frames for React commit + TipTap mount + DOM-vacuum settlement.- await yieldFramesInPage(page);- await yieldFramesInPage(page);+ await settleNewFile(page);}/**@@ -220,8 +254,7 @@ test.describe('new-file cross-doc bleed', () => {).toHaveCount(1);// Trigger the New File flow.- const newDocName = `newfile-${randomUUID()}`;- await newFileViaShortcut(page, newDocName);+ await newFileViaShortcut(page);// Bug assertion: exactly one empty PM in the visible Activity.await assertVisibleActivityHasOnlyEmptyEditor(page);@@ -253,8 +286,7 @@ test.describe('new-file cross-doc bleed', () => {await waitForActiveProviderSynced(page);// Trigger New File from B's view.- const newDocName = `newfile-${randomUUID()}`;- await newFileViaShortcut(page, newDocName);+ await newFileViaShortcut(page);await assertVisibleActivityHasOnlyEmptyEditor(page);});@@ -291,7 +323,7 @@ test.describe('new-file cross-doc bleed', () => {// Trigger New File with the SAME docName the deleted file had — the// docName-reuse-after-delete path is the worst case for the in-memory// pool entry that may still reference the prior doc's editor instance.- await newFileViaShortcut(page, reusedDocName);+ await newFileViaPalette(page, reusedDocName);await assertVisibleActivityHasOnlyEmptyEditor(page);});diff --git a/packages/app/tests/stress/new-item-shortcut-fast-path.e2e.ts b/packages/app/tests/stress/new-item-shortcut-fast-path.e2e.tsnew file mode 100644index 000000000..c5a93eba7--- /dev/null+++ b/packages/app/tests/stress/new-item-shortcut-fast-path.e2e.ts@@ -0,0 +1,158 @@+/**+ * The new-item shortcut's two branches.+ *+ * With no template resolved for the target folder, the New file dialog has+ * nothing left to ask — the name is the only field, and it is a name the user+ * is about to retype in the editor anyway. So the shortcut skips the dialog+ * and drops straight into a fresh `untitled` doc. Resolve a template and the+ * dialog comes back, because now there is a real choice to make.+ *+ * Tier: Playwright e2e against the per-worker dev-server fixture.+ */++import type { Page } from '@playwright/test';+import { expect, test, waitForActiveProviderSynced } from './_helpers';++const NEW_FILE_DIALOG = /New file/i;++async function putRootTemplate(baseURL: string, name: string): Promise<void> {+ const res = await fetch(`${baseURL}/api/template`, {+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ folder: '', name, frontmatter: { title: name }, body: 'Template body' }),+ });+ if (!res.ok) throw new Error(`PUT /api/template failed: ${res.status} ${await res.text()}`);+}++async function deleteRootTemplate(baseURL: string, name: string): Promise<void> {+ const res = await fetch(`${baseURL}/api/template?${new URLSearchParams({ folder: '', name })}`, {+ method: 'DELETE',+ });+ if (!res.ok && res.status !== 404) throw new Error(`DELETE /api/template failed: ${res.status}`);+}++async function deleteDoc(baseURL: string, docName: string): Promise<void> {+ const res = await fetch(`${baseURL}/api/delete-path`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ kind: 'file', path: `${docName}.md` }),+ });+ if (!res.ok && res.status !== 404) throw new Error(`delete-path failed: ${res.status}`);+}++/**+ * Open `hash` and wait until the folder cascade has actually landed.+ *+ * The shortcut only takes its branch once `/api/folder-config` resolves — a+ * synced provider says nothing about that request, so pressing on provider-sync+ * alone races the fetch and would silently exercise the loading branch (dialog+ * opens) instead of the branch under test.+ */+async function gotoWithFolderConfig(page: Page, hash: string): Promise<void> {+ const folderConfigLanded = page.waitForResponse(+ (res) => res.url().includes('/api/folder-config') && res.ok(),+ { timeout: 15_000 },+ );+ await page.goto(hash);+ await page.waitForLoadState('domcontentloaded');+ await folderConfigLanded;+ await waitForActiveProviderSynced(page);+}++/** Press the browser-safe new-item shortcut with focus parked on body. */+async function pressNewItemShortcut(page: Page): Promise<void> {+ await page.locator('body').click({ position: { x: 5, y: 5 } });+ await page.waitForFunction(+ () => document.activeElement === null || document.activeElement === document.body,+ null,+ { timeout: 1_000 },+ );+ await page.keyboard.press(`${process.platform === 'darwin' ? 'Meta' : 'Control'}+Alt+KeyN`);+}++test.describe('new-item shortcut fast path', () => {+ test.describe.configure({ mode: 'serial' });++ test('no templates: creates untitled docs without the dialog, numbering past the taken names', async ({+ page,+ workerServer,+ }) => {+ await deleteDoc(workerServer.baseURL, 'untitled');+ await deleteDoc(workerServer.baseURL, 'untitled-2');+ await gotoWithFolderConfig(page, '/#/test-doc');++ await pressNewItemShortcut(page);+ await page.waitForFunction(() => window.location.hash === '#/untitled', null, {+ timeout: 10_000,+ });+ await expect(page.getByRole('dialog', { name: NEW_FILE_DIALOG })).toBeHidden();+ await waitForActiveProviderSynced(page);++ // The page list now carries `untitled`, so the next press has to step past it.+ await pressNewItemShortcut(page);+ await page.waitForFunction(() => window.location.hash === '#/untitled-2', null, {+ timeout: 10_000,+ });+ await expect(page.getByRole('dialog', { name: NEW_FILE_DIALOG })).toBeHidden();++ // The surfaces that keep the dialog (here: the command palette) drop the+ // picker too when nothing resolves — there is no "Start from" to offer.+ await page.locator('body').click({ position: { x: 5, y: 5 } });+ await page.keyboard.press('ControlOrMeta+KeyK');+ await page+ .getByRole('option', { name: /^New file/ })+ .first()+ .click();+ const dialog = page.getByRole('dialog', { name: NEW_FILE_DIALOG });+ await expect(dialog).toBeVisible({ timeout: 10_000 });+ await expect(dialog.getByLabel(/^File name$/i)).toBeVisible();+ await expect(dialog.getByText('Start from')).toHaveCount(0);++ await deleteDoc(workerServer.baseURL, 'untitled');+ await deleteDoc(workerServer.baseURL, 'untitled-2');+ });++ test('a failed fast create surfaces the error and falls back to the dialog', async ({ page }) => {+ await gotoWithFolderConfig(page, '/#/test-doc');++ // Force the instant create to lose (as a name race would): the keypress must+ // not be swallowed — the reason toasts and the dialog opens as the recovery+ // path, rather than a blank dialog with the first failure's reason lost.+ await page.route('**/api/create-page', async (route) => {+ await route.fulfill({+ status: 409,+ contentType: 'application/problem+json',+ body: JSON.stringify({+ type: 'urn:ok:error:doc-already-exists',+ title: 'A file named untitled already exists',+ }),+ });+ });++ await pressNewItemShortcut(page);++ await expect(page.getByRole('dialog', { name: NEW_FILE_DIALOG })).toBeVisible({+ timeout: 10_000,+ });+ await expect(page.locator('[data-sonner-toast]', { hasText: /already exists/i })).toBeVisible();+ });++ test('a resolved template brings the dialog back, with the picker', async ({+ page,+ workerServer,+ }) => {+ const templateName = 'zz-shortcut-fast-path-template';+ await putRootTemplate(workerServer.baseURL, templateName);+ try {+ await gotoWithFolderConfig(page, '/#/test-doc');++ await pressNewItemShortcut(page);+ const dialog = page.getByRole('dialog', { name: NEW_FILE_DIALOG });+ await expect(dialog).toBeVisible({ timeout: 10_000 });+ await expect(dialog.getByText('Start from')).toBeVisible();+ await expect(dialog.getByRole('combobox')).toBeVisible();+ } finally {+ await deleteRootTemplate(workerServer.baseURL, templateName);+ }+ });+});