Jelajahi Sumber

refactor: dedupe the jscpd clones; drop the baseline loading gate

- Extract the shared New Session action into WorkspacesService.startSession
  (sidebar button and workspace browser both delegate; recent-Workspace
  targeting and the no-workspace clear live in one place).
- Fold the chip-insertion transaction shared by insert-ref and paste-upgrade
  into one InputMachine helper.
- Share the fixture's session-not-found guard across the sessionId-addressed
  catalog routes.
- Drop the AppFrame baselines-ready loading gate (user ruling: the bare
  status line reads worse than the shell's own pending rendering); both
  column occupants mount from first paint.
imccyu 1 bulan lalu
induk
melakukan
dd2d9ca50a

+ 15 - 24
packages/client/connection/src/client/fixture.ts

@@ -428,6 +428,15 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy {
   }
 
   const summaryOf = (id: SessionId): SessionSummary | undefined => sessions.find(s => s.sessionId === id)
+  /** Shared session guard for sessionId-addressed catalog routes: the error response when the session is unknown, undefined when it exists. */
+  const requireSession = (request: RpcRequest<{ sessionId: SessionId }>): Promise<RpcResponse<never>> | undefined =>
+    summaryOf(request.payload.sessionId) === undefined
+      ? err<{ sessionId: SessionId }, never>(request, {
+          code: 'session-not-found',
+          message: `no session ${request.payload.sessionId}`,
+          details: { sessionId: request.payload.sessionId },
+        })
+      : undefined
   const setRunning = (id: SessionId, running: boolean): void => {
     const summary = summaryOf(id)
     if (summary === undefined || summary.running === running) return
@@ -746,14 +755,8 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy {
       // The catalog mirrors one session's effective view (every fixture
       // session has an agent, like the real host).
       list: (request) => {
-        const summary = summaryOf(request.payload.sessionId)
-        if (summary === undefined) {
-          return err(request, {
-            code: 'session-not-found',
-            message: `no session ${request.payload.sessionId}`,
-            details: { sessionId: request.payload.sessionId },
-          })
-        }
+        const missing = requireSession(request)
+        if (missing !== undefined) return missing
         return ok(request, {
           commands: [
             { name: 'compact', description: 'fixture:压缩当前会话上下文' },
@@ -763,14 +766,8 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy {
         })
       },
       execute: (request) => {
-        const summary = summaryOf(request.payload.sessionId)
-        if (summary === undefined) {
-          return err(request, {
-            code: 'session-not-found',
-            message: `no session ${request.payload.sessionId}`,
-            details: { sessionId: request.payload.sessionId },
-          })
-        }
+        const missing = requireSession(request)
+        if (missing !== undefined) return missing
         const line = request.payload.line.trim()
         const match = /^\/(\S+)(?:\s+(.*))?$/.exec(line)
         const name = match?.[1]
@@ -791,14 +788,8 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy {
     },
     skills: {
       list: (request) => {
-        const summary = summaryOf(request.payload.sessionId)
-        if (summary === undefined) {
-          return err(request, {
-            code: 'session-not-found',
-            message: `no session ${request.payload.sessionId}`,
-            details: { sessionId: request.payload.sessionId },
-          })
-        }
+        const missing = requireSession(request)
+        if (missing !== undefined) return missing
         return ok(request, {
           skills: [
             { name: 'fixture-demo', description: 'fixture 技能样本', whenToUse: '仅供 UI 目录渲染验收' },

+ 21 - 0
packages/client/runtime/src/client/workspaces/service.ts

@@ -130,6 +130,27 @@ export class WorkspacesService {
     }
   }
 
+  /**
+   * The shared New Session action behind the shell entry points (sidebar
+   * button, workspace browser): resolve the target Workspace — explicit wins,
+   * else the recent-Workspace projection — connect its blank session and
+   * navigate there; with no Workspace at all, clear the selection into the
+   * New Session view state. Connect failures are non-fatal (console
+   * diagnostics; the current view stays usable).
+   * @param workspaceId - explicit target Workspace for scoped actions.
+   */
+  startSession(workspaceId?: WorkspaceId): void {
+    const target = workspaceId ?? this.list.getSnapshot().recentWorkspaceId
+    if (target === undefined) {
+      this.sessions.clear()
+      return
+    }
+    void this.connectWorkspace(target).then(
+      (sessionId) => { this.sessions.open(sessionId) },
+      (reason: unknown) => { console.warn('new session failed:', reason) },
+    )
+  }
+
   /**
    * Create a Workspace by name or register an existing path.
    * @param input - exactly one Host create spelling.

+ 8 - 8
packages/client/ui-conversation/src/client/input/machine.ts

@@ -292,14 +292,19 @@ export class InputMachine {
   private onInsertRef(reference: ReferenceInsert, span: TokenSpan): InputEffect[] {
     if (this.phase !== 'plain' && this.phase !== 'claimed') return []
     if (!this.casOk(span)) return []
+    this.replaceSpanWithChip(reference, span)
+    this.paste = undefined
+    return []
+  }
+
+  /** Shared chip-insertion transaction: replace [span) with one placeholder occurrence (insert-ref and paste-upgrade both land here). */
+  private replaceSpanWithChip(reference: ReferenceInsert, span: TokenSpan): void {
     this.pushTxn()
     this.typingRun = undefined
     this.reconcile({ start: span.start, end: span.end, insertedLength: 1 })
     this.withMinted([this.mint(reference, span.start)])
     this.adopt(this.draft.slice(0, span.start) + PLACEHOLDER + this.draft.slice(span.end))
     this.watchClaim()
-    this.paste = undefined
-    return []
   }
 
   /**
@@ -437,12 +442,7 @@ export class InputMachine {
     if (attempt === undefined || attempt.attemptId !== attemptId) return []
     if (this.phase !== 'plain' && this.phase !== 'claimed') return []
     if (!this.casOk(span) || span.start === span.end) return []
-    this.pushTxn()
-    this.typingRun = undefined
-    this.reconcile({ start: span.start, end: span.end, insertedLength: 1 })
-    this.withMinted([this.mint(reference, span.start)])
-    this.adopt(this.draft.slice(0, span.start) + PLACEHOLDER + this.draft.slice(span.end))
-    this.watchClaim()
+    this.replaceSpanWithChip(reference, span)
     this.paste = {
       ...attempt,
       insertedRange: { start: attempt.insertedRange.start, end: attempt.insertedRange.end + 1 - (span.end - span.start) },

+ 9 - 23
packages/client/ui-layout/src/client/AppFrame.tsx

@@ -85,12 +85,7 @@ export function AppFrame({
   useStore,
   actions,
   renderSlot,
-  useWorkspaces,
 }: AppFrameProps) {
-  // Baseline gate: before both object-layer baselines land, empty snapshots
-  // are indistinguishable from a genuine no-session state — rendering the
-  // conversation shell then would flash the New Workspace hero on boot.
-  const baselinesReady = useWorkspaces(s => s.baselinesReady)
   const panels = useStore((s) => s)
   const frameRef = useRef<HTMLDivElement | null>(null)
   const [viewport, setViewport] = useState(() => window.innerWidth)
@@ -156,24 +151,15 @@ export function AppFrame({
           width: cols.sidebar,
         })}
       </div>
-      {baselinesReady
-        ? (
-          <>
-            {/* Both column occupants stay at fixed tree positions. The
-                conversation is session-maybe; the strict details entry
-                naturally renders empty while no session is current. */}
-            <CenterColumn>{renderSlot('conversation', {})}</CenterColumn>
-            <DetailsColumn>{renderSlot('details', {})}</DetailsColumn>
-          </>
-          )
-        : (
-          <>
-            <CenterColumn>
-              <div role="status">Loading workspaces and sessions…</div>
-            </CenterColumn>
-            <DetailsColumn />
-          </>
-          )}
+      <>
+        {/* Both column occupants stay at fixed tree positions from first
+            paint — no loading gate (user ruling: the bare status line looked
+            worse than the shell's own pending rendering). The conversation
+            is session-maybe; the strict details entry naturally renders
+            empty while no session is current. */}
+        <CenterColumn>{renderSlot('conversation', {})}</CenterColumn>
+        <DetailsColumn>{renderSlot('details', {})}</DetailsColumn>
+      </>
       {/* The collapsed rail is fixed-width: no resize handle while closed. */}
       {panels.sidebar > 0 && <DragHandle side="sidebar" left={cols.sidebar} onStart={onSidebarStart} onDrag={onSidebarDrag} onEnd={onDragEnd} />}
       {cols.details > 0 && <DragHandle side="details" left={viewport - cols.details} onStart={onDetailsStart} onDrag={onDetailsDrag} onEnd={onDragEnd} />}

+ 6 - 4
packages/client/ui-layout/tests/app-frame.spec.tsx

@@ -160,11 +160,13 @@ describe('AppFrame', () => {
     expect(slotCalls.map((c) => c.key)).toContain('conversation')
   })
 
-  it('keeps the loading branch until both object-layer baselines are ready', () => {
+  it('renders both column occupants before baselines settle (no loading gate)', () => {
+    // User ruling: the bare loading status looked worse than the shell's own
+    // pending rendering — both occupants mount from first paint.
     baselinesReady.current = false
-    const { slotCalls, getByRole } = mountFrame()
-    expect(getByRole('status').textContent).toContain('Loading workspaces and sessions')
-    expect(slotCalls.map((c) => c.key)).not.toContain('conversation')
+    const { slotCalls } = mountFrame()
+    expect(slotCalls.map((c) => c.key)).toContain('conversation')
+    expect(slotCalls.map((c) => c.key)).toContain('details')
   })
 
   it('sidebar slot receives live concession output as owner props', () => {

+ 3 - 13
packages/client/ui-sidebar/src/client/index.ts

@@ -13,19 +13,9 @@ export const inject = ['slots', 'layout', 'sessions', 'workspaces']
  */
 export function apply(ctx: ClientContext): void {
   const injectProps = (): SidebarRootInjected => ({
-    // The shell's New Session button targets the most recently active
-    // Workspace; an explicit Workspace still wins for scoped create actions.
-    startSession: (workspaceId) => {
-      const target = workspaceId ?? ctx.workspaces.list.getSnapshot().recentWorkspaceId
-      if (target === undefined) {
-        ctx.sessions.clear()
-        return
-      }
-      void ctx.workspaces.connectWorkspace(target).then(
-        (sessionId) => { ctx.sessions.open(sessionId) },
-        (reason: unknown) => { console.warn('new session failed:', reason) },
-      )
-    },
+    // The shell's New Session button rides the runtime's shared action
+    // (recent-Workspace targeting; explicit Workspace wins for scoped actions).
+    startSession: (workspaceId) => { ctx.workspaces.startSession(workspaceId) },
     toggleSidebar: () => { ctx.layout.toggleSidebar() },
   })
   ctx.effect(

+ 4 - 9
packages/client/ui-sidebar/tests/apply.spec.tsx

@@ -9,10 +9,7 @@ async function bench(declare = true) {
   const ctx = new Context()
   await ctx.plugin(SlotsService).await()
   const layout = { toggleSidebar: vi.fn() }
-  const workspaces = {
-    connectWorkspace: vi.fn(async () => 'blank-1' as never),
-    list: { getSnapshot: () => ({ recentWorkspaceId: undefined }) },
-  }
+  const workspaces = { startSession: vi.fn() }
   const sessions = { open: vi.fn(), clear: vi.fn() }
   ctx.provide('layout', layout)
   ctx.provide('sessions', sessions as never)
@@ -39,13 +36,11 @@ describe('ui-sidebar apply', () => {
     expect(b.slots.spec('sidebar.workspaces')).toEqual({ kind: 'single', scope: 'root' })
     const injected = (b.slots.entries('sidebar')[0]!.inject as () => SidebarRootInjected)()
     expect(Object.keys(injected)).toEqual(['startSession', 'toggleSidebar'])
-    // Workspace given: reuse-or-create the blank session, then navigate.
+    // Both arms delegate to the runtime's shared New Session action.
     injected.startSession('workspace' as never)
-    expect(b.workspaces.connectWorkspace).toHaveBeenCalledWith('workspace')
-    await vi.waitFor(() => { expect(b.sessions.open).toHaveBeenCalledWith('blank-1') })
-    // No workspace (the shell's New Session button): clear into the view state.
+    expect(b.workspaces.startSession).toHaveBeenCalledWith('workspace')
     injected.startSession()
-    expect(b.sessions.clear).toHaveBeenCalledOnce()
+    expect(b.workspaces.startSession).toHaveBeenLastCalledWith(undefined)
     injected.toggleSidebar()
     expect(b.layout.toggleSidebar).toHaveBeenCalledOnce()
   })

+ 3 - 13
packages/client/ui-workspace/src/client/index.ts

@@ -34,19 +34,9 @@ export const inject = ['slots', 'sessions', 'workspaces']
  */
 export function apply(ctx: ClientContext): void {
   const browserInjected = (): WorkspaceBrowserInjected => ({
-    // Explicit group actions keep their target; an unscoped New Session
-    // action resolves through the runtime's recent-Workspace projection.
-    startSession: (workspaceId) => {
-      const target = workspaceId ?? ctx.workspaces.list.getSnapshot().recentWorkspaceId
-      if (target === undefined) {
-        ctx.sessions.clear()
-        return
-      }
-      void ctx.workspaces.connectWorkspace(target).then(
-        (sessionId) => { ctx.sessions.open(sessionId) },
-        (reason: unknown) => { console.warn('new session failed:', reason) },
-      )
-    },
+    // Explicit group actions keep their target; unscoped New Session rides
+    // the runtime's shared action (recent-Workspace projection inside).
+    startSession: (workspaceId) => { ctx.workspaces.startSession(workspaceId) },
     open: (sessionId) => { ctx.sessions.open(sessionId) },
     renameWorkspace: async (workspaceId, title) => { await ctx.workspaces.rename(workspaceId, title) },
     insertSessionBefore: async (workspaceId, sessionId, beforeSessionId) => {

+ 6 - 9
packages/client/ui-workspace/tests/apply.spec.ts

@@ -14,17 +14,16 @@ async function bench() {
     path: 'name' in input ? `/projects/${input.name}` : input.path,
     title: 'new', sessionIds: [], createdAt: '0', updatedAt: '0',
   }))
-  const connectWorkspace = vi.fn(async () => 'blank-1' as never)
+  const startSession = vi.fn()
   const rename = vi.fn(async () => ({}))
   const insertSessionBefore = vi.fn(async () => ({}))
   const open = vi.fn()
   const clear = vi.fn()
   ctx.provide('workspaces', {
-    create, connectWorkspace, rename, insertSessionBefore,
-    list: { getSnapshot: () => ({ recentWorkspaceId: undefined }) },
+    create, startSession, rename, insertSessionBefore,
   } as never)
   ctx.provide('sessions', { open, clear } as never)
-  return { ctx, slots: ctx.get('slots') as SlotsService, create, connectWorkspace, rename, insertSessionBefore, open, clear }
+  return { ctx, slots: ctx.get('slots') as SlotsService, create, startSession, rename, insertSessionBefore, open, clear }
 }
 
 type HoleName = 'sidebar.workspaces' | 'conversation.hero.workspace' | 'conversation.empty.workspace'
@@ -60,13 +59,11 @@ describe('ui-workspace apply', () => {
     await b.ctx.plugin({ inject: [...inject], apply }).await()
 
     const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)()
-    // Workspace given: reuse-or-create the blank session, then navigate.
+    // Both arms delegate to the runtime's shared New Session action.
     browser.startSession('ws' as never)
-    expect(b.connectWorkspace).toHaveBeenCalledWith('ws')
-    await vi.waitFor(() => { expect(b.open).toHaveBeenCalledWith('blank-1') })
-    // No workspace: clear the selection into the New Session pure view state.
+    expect(b.startSession).toHaveBeenCalledWith('ws')
     browser.startSession()
-    expect(b.clear).toHaveBeenCalledOnce()
+    expect(b.startSession).toHaveBeenLastCalledWith(undefined)
     browser.open('session' as never)
     expect(b.open).toHaveBeenCalledWith('session')
     await browser.renameWorkspace('ws' as never, 'renamed')