The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): drag to create sessions from New session, project + controls, and profile groups
abundantbeing6b1e12c7f483
diff --git a/apps/desktop/src/app/chat/new-session-drag.test.ts b/apps/desktop/src/app/chat/new-session-drag.test.tsnew file mode 100644index 00000000000..2f47c53b1d2--- /dev/null+++ b/apps/desktop/src/app/chat/new-session-drag.test.ts@@ -0,0 +1,420 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import type * as TreeModel from '@/components/pane-shell/tree/model'+import type * as TreeStore from '@/components/pane-shell/tree/store'+import { NEW_SESSION_DRAG } from '@/components/pane-shell/tree/store'++import { type NewSessionPlacement, startNewProjectDrag, startNewSessionDrag } from './new-session-drag'++// ---------------------------------------------------------------------------+// The drag MACHINERY (startDragSession) is exercised by the pane-shell's own+// tests; here we capture the spec the resolver hands it and drive resolveMove /+// onCommit directly. Geometry helpers are mocked so targeting is deterministic+// without real layout — the assertions are about the DROP LANGUAGE (stack /+// split / deny) and the create-on-commit contract, which is what's new here.+// ---------------------------------------------------------------------------++const captured: { spec: null | Record<string, any> } = { spec: null }++// vi.mock factories are hoisted above these declarations, so the mocks they+// reference must be created in a vi.hoisted() block (available at hoist time)+// rather than as plain top-level consts (a TDZ error when the factory runs).+const { findGroup, setTreeDragging, slotBefore, subZonePosition } = vi.hoisted(() => ({+ findGroup: vi.fn(),+ setTreeDragging: vi.fn(),+ slotBefore: vi.fn(() => ({ before: 'workspace' })),+ subZonePosition: vi.fn()+}))++vi.mock('@/components/pane-shell/tree/renderer/drag-session', () => ({+ rectContains: (rect: { bottom: number; left: number; right: number; top: number }, x: number, y: number) =>+ x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom,+ slotBefore,+ snapshotStrips: () => [+ { groupId: 'g1', rect: { bottom: 40, left: 0, right: 800, top: 0 }, slots: [{ id: 'workspace', mid: 400 }] }+ ],+ snapshotZones: () => [{ id: 'g1', rect: { bottom: 600, left: 0, right: 800, top: 0 } }],+ startDragSession: (_e: unknown, spec: Record<string, any>) => {+ captured.spec = spec+ },+ subZonePosition+}))++vi.mock('@/components/pane-shell/tree/store', async importOriginal => {+ const actual = await importOriginal<typeof TreeStore>()++ return {+ ...actual,+ $layoutTree: { get: () => ({}) },+ $treeDragging: { set: setTreeDragging }+ }+})++vi.mock('@/components/pane-shell/tree/model', async importOriginal => {+ const actual = await importOriginal<typeof TreeModel>()++ return {+ ...actual,+ findGroup+ }+})++vi.mock('@/i18n', () => ({+ // Key-aware so each resolver's ghost label is pinned to its own string.+ translateNow: (key: string) => (key === 'sidebar.projects.newButton' ? 'New project' : 'New session')+}))++// A chat zone hosting the workspace pane — the only kind of zone a new session+// may land in.+findGroup.mockImplementation((_tree: unknown, groupId: string) => (groupId === 'g1' ? { panes: ['workspace'] } : null))++const fakePointerEvent = () =>+ ({+ button: 0,+ clientX: 0,+ clientY: 0,+ currentTarget: { style: { opacity: '', setProperty: vi.fn() } },+ pointerId: 1+ }) as unknown as React.PointerEvent<HTMLElement>++function engage(+ onCreate: (placement: NewSessionPlacement) => void = vi.fn(),+ opts?: Parameters<typeof startNewSessionDrag>[2]+) {+ startNewSessionDrag(onCreate, fakePointerEvent(), opts)+ const spec = captured.spec++ if (!spec) {+ throw new Error('startDragSession was not called')+ }++ spec.onEngage(0, 0)++ return spec+}++describe('startNewSessionDrag', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ captured.spec = null+ findGroup.mockImplementation((_tree: unknown, groupId: string) =>+ groupId === 'g1' ? { panes: ['workspace'] } : null+ )+ })++ it('advertises the distinct NEW_SESSION_DRAG sentinel on engage', () => {+ engage()+ expect(setTreeDragging).toHaveBeenCalledWith(NEW_SESSION_DRAG)+ })++ it('drops a ghost labelled like the New session row', () => {+ startNewSessionDrag(vi.fn(), fakePointerEvent())+ expect(captured.spec?.ghost).toEqual({ label: 'New session' })+ })++ it('stacks a fresh tab on a center drop (never links — nothing to link yet)', () => {+ const onCreate = vi.fn()+ subZonePosition.mockReturnValue('center')+ const spec = engage(onCreate)++ const hint = spec.resolveMove(400, 300, false)++ expect(hint).toMatchObject({ groupId: 'g1', pos: 'center' })+ expect(hint?.stack).toBeUndefined()++ spec.onCommit(hint)+ expect(onCreate).toHaveBeenCalledWith({ anchor: 'workspace', dir: 'center' } satisfies NewSessionPlacement)+ })++ it('splits a new tile off a zone edge', () => {+ const onCreate = vi.fn()+ subZonePosition.mockReturnValue('right')+ const spec = engage(onCreate)++ const hint = spec.resolveMove(780, 300, false)++ expect(hint).toMatchObject({ groupId: 'g1', pos: 'right' })++ spec.onCommit(hint)+ expect(onCreate).toHaveBeenCalledWith({ anchor: 'workspace', dir: 'right' } satisfies NewSessionPlacement)+ })++ it('stacks at a tab-strip slot, carrying the insertion point', () => {+ const onCreate = vi.fn()+ slotBefore.mockReturnValue({ before: 'workspace' })+ const spec = engage(onCreate)++ // Inside the strip band (top 40px of the zone).+ const hint = spec.resolveMove(150, 20, false)++ expect(hint?.stack).toEqual({ before: 'workspace' })++ spec.onCommit(hint)+ expect(onCreate).toHaveBeenCalledWith({+ anchor: 'workspace',+ before: 'workspace',+ dir: 'center'+ } satisfies NewSessionPlacement)+ })++ it('creates nothing when released over a deny zone', () => {+ const onCreate = vi.fn()+ const spec = engage(onCreate)++ // Far outside any zone.+ const hint = spec.resolveMove(5000, 5000, false)++ expect(hint).toBeNull()++ spec.onCommit(hint)+ expect(onCreate).not.toHaveBeenCalled()+ })++ it('creates nothing when the drag never resolves a target before commit', () => {+ const onCreate = vi.fn()+ const spec = engage(onCreate)++ // Commit straight after engage, with no move over a valid zone.+ spec.onCommit(null)+ expect(onCreate).not.toHaveBeenCalled()+ })++ it('restores the source row opacity on end', () => {+ const event = fakePointerEvent()++ const source = event.currentTarget as unknown as {+ style: { opacity: string; setProperty: ReturnType<typeof vi.fn> }+ }++ startNewSessionDrag(vi.fn(), event)+ const spec = captured.spec!++ spec.onEngage(0, 0)+ expect(source.style.setProperty).toHaveBeenCalledWith('opacity', '0.45')++ spec.onEnd()+ expect(source.style.opacity).toBe('')+ })++ it('labels the ghost with the project name for a project-row drag', () => {+ startNewSessionDrag(vi.fn(), fakePointerEvent(), { cwd: '/repo', label: 'New session in Hermes Browser' })+ expect(captured.spec?.ghost).toEqual({ label: 'New session in Hermes Browser' })+ })++ it('pins the created session to the project cwd on a center drop', () => {+ const onCreate = vi.fn()+ subZonePosition.mockReturnValue('center')+ const spec = engage(onCreate, { cwd: '/repo/hermes-browser' })++ const hint = spec.resolveMove(400, 300, false)+ spec.onCommit(hint)++ expect(onCreate).toHaveBeenCalledWith({+ anchor: 'workspace',+ cwd: '/repo/hermes-browser',+ dir: 'center'+ } satisfies NewSessionPlacement)+ })++ it('pins the created session to the project cwd on an edge split', () => {+ const onCreate = vi.fn()+ subZonePosition.mockReturnValue('left')+ const spec = engage(onCreate, { cwd: '/repo/hermes-browser' })++ const hint = spec.resolveMove(20, 300, false)+ spec.onCommit(hint)++ expect(onCreate).toHaveBeenCalledWith({+ anchor: 'workspace',+ cwd: '/repo/hermes-browser',+ dir: 'left'+ } satisfies NewSessionPlacement)+ })++ it('pins the created session to a profile for a profile-group drag', () => {+ const onCreate = vi.fn()+ subZonePosition.mockReturnValue('center')+ const spec = engage(onCreate, { profile: 'reviewer' })++ const hint = spec.resolveMove(400, 300, false)+ spec.onCommit(hint)++ expect(onCreate).toHaveBeenCalledWith({+ anchor: 'workspace',+ cwd: undefined,+ dir: 'center',+ profile: 'reviewer'+ } satisfies NewSessionPlacement)+ })++ it('leaves cwd undefined for a plain New session drag', () => {+ const onCreate = vi.fn()+ subZonePosition.mockReturnValue('center')+ const spec = engage(onCreate)++ const hint = spec.resolveMove(400, 300, false)+ spec.onCommit(hint)++ expect(onCreate).toHaveBeenCalledWith({ anchor: 'workspace', cwd: undefined, dir: 'center' })+ })++ it('ignores an inactive tab surface when resolving the center-drop anchor', () => {+ const rect = { bottom: 600, height: 600, left: 0, right: 800, top: 0, width: 800, x: 0, y: 0, toJSON: () => ({}) }+ document.body.innerHTML = `+ <div data-pane-hidden>+ <div data-session-anchor="session-tile:hidden"></div>+ </div>+ <div data-session-anchor="workspace"></div>+ `++ for (const element of document.querySelectorAll<HTMLElement>('[data-session-anchor]')) {+ element.getBoundingClientRect = vi.fn(() => rect)+ }++ const onCreate = vi.fn()+ subZonePosition.mockReturnValue('center')+ const spec = engage(onCreate)+ const hint = spec.resolveMove(400, 300, false)+ spec.onCommit(hint)++ expect(onCreate).toHaveBeenCalledWith({ anchor: 'workspace', cwd: undefined, dir: 'center' })+ })++ it('ignores an inactive tab composer when resolving an edge split', () => {+ const rect = { bottom: 600, height: 600, left: 0, right: 800, top: 0, width: 800, x: 0, y: 0, toJSON: () => ({}) }+ document.body.innerHTML = `+ <div data-session-anchor="workspace"></div>+ <div data-pane-hidden>+ <div data-slot="composer-root"></div>+ </div>+ `+ document.querySelector<HTMLElement>('[data-session-anchor]')!.getBoundingClientRect = vi.fn(() => rect)+ document.querySelector<HTMLElement>('[data-slot="composer-root"]')!.getBoundingClientRect = vi.fn(() => rect)++ const onCreate = vi.fn()+ subZonePosition.mockReturnValue('right')+ const spec = engage(onCreate)+ const hint = spec.resolveMove(780, 300, false)+ spec.onCommit(hint)++ expect(onCreate).toHaveBeenCalledWith({ anchor: 'workspace', cwd: undefined, dir: 'right' })+ })+})++// ---------------------------------------------------------------------------+// startNewProjectDrag — the "New project" + variant. Same drop language, but+// the placement ARMS the dialog flow instead of creating anything at release:+// a valid commit arms + opens the dialog, a sub-threshold release is the plain+// click, and an aborted/deny-zone drag clears any stale arm.+// ---------------------------------------------------------------------------++describe('startNewProjectDrag', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ captured.spec = null+ findGroup.mockImplementation((_tree: unknown, groupId: string) =>+ groupId === 'g1' ? { panes: ['workspace'] } : null+ )+ })++ function engageProject(onArm: (placement: NewSessionPlacement | null) => void = vi.fn(), onTap?: () => void) {+ startNewProjectDrag(onArm, fakePointerEvent(), { onTap })+ const spec = captured.spec++ if (!spec) {+ throw new Error('startDragSession was not called')+ }++ spec.onEngage(0, 0)++ return spec+ }++ it('arms the dropped placement and opens the project dialog on a valid commit', () => {+ const onArm = vi.fn()+ const onTap = vi.fn()+ subZonePosition.mockReturnValue('center')+ const spec = engageProject(onArm, onTap)++ const hint = spec.resolveMove(400, 300, false)+ spec.onCommit(hint)++ expect(onArm).toHaveBeenCalledWith({ anchor: 'workspace', dir: 'center' })+ // The SAME dialog a plain click opens — the drag only adds the placement.+ expect(onTap).toHaveBeenCalledOnce()+ })++ it('opens NOTHING on a denied drop — same language as Escape', () => {+ const onArm = vi.fn()+ const onTap = vi.fn()+ const spec = engageProject(onArm, onTap)++ // Released far outside any zone: the drop reads as cancelled.+ const hint = spec.resolveMove(5000, 5000, false)++ expect(hint).toBeNull()++ spec.onCommit(hint)++ expect(onTap).not.toHaveBeenCalled()++ // Teardown still sweeps any stale arm (onEnd sees placement === null).+ spec.onEnd()+ expect(onArm).toHaveBeenCalledOnce()+ expect(onArm).toHaveBeenCalledWith(null)+ })++ it('carries the tab-strip slot in the armed placement', () => {+ const onArm = vi.fn()+ slotBefore.mockReturnValue({ before: 'session-tile:abc' })+ const spec = engageProject(onArm)++ const hint = spec.resolveMove(150, 20, false)+ spec.onCommit(hint)++ expect(onArm).toHaveBeenCalledWith({ anchor: 'workspace', before: 'session-tile:abc', dir: 'center' })+ })++ it('keeps a sub-threshold release an ordinary dialog click — nothing armed', () => {+ const onArm = vi.fn()+ const onTap = vi.fn()+ engageProject(onArm, onTap)++ captured.spec!.onTap!()++ expect(onTap).toHaveBeenCalledOnce()+ expect(onArm).not.toHaveBeenCalled()+ })++ it('clears the arm when released over a deny zone', () => {+ const onArm = vi.fn()+ const spec = engageProject(onArm)++ const hint = spec.resolveMove(5000, 5000, false)++ expect(hint).toBeNull()++ spec.onCommit(hint)+ spec.onEnd()++ expect(onArm).toHaveBeenLastCalledWith(null)+ })++ it('does not clear a committed arm on drag end', () => {+ const onArm = vi.fn()+ subZonePosition.mockReturnValue('right')+ const spec = engageProject(onArm)++ const hint = spec.resolveMove(780, 300, false)+ spec.onCommit(hint)+ spec.onEnd()++ expect(onArm).toHaveBeenCalledOnce()+ expect(onArm).not.toHaveBeenCalledWith(null)+ })++ it('drops a ghost labelled like the New project control', () => {+ engageProject()+ expect(captured.spec?.ghost).toEqual({ label: 'New project' })+ })+})diff --git a/apps/desktop/src/app/chat/new-session-drag.ts b/apps/desktop/src/app/chat/new-session-drag.tsnew file mode 100644index 00000000000..4ca0172c89e--- /dev/null+++ b/apps/desktop/src/app/chat/new-session-drag.ts@@ -0,0 +1,325 @@+/**+ * Sidebar "New session" drag — the NEW-session resolver over the shared+ * pointer drag session (pane-shell drag-session.ts). Same machinery and drop+ * language as a session drag (session-drag.ts): a chat zone's TAB STRIP stacks,+ * a chat zone's EDGE splits, and the CENTER stacks a fresh tab.+ *+ * The ONE deliberate difference from a session drag: there is no "link to chat"+ * (composer `@session` chip) target. A session that doesn't exist yet can't be+ * linked, so a center drop creates + stacks instead. This is why the drag rides+ * the distinct NEW_SESSION_DRAG sentinel (not SESSION_TILE_DRAG): the overlay's+ * `sessionDrag` checks that gate the link affordance stay false here, so the+ * zone sheet shows its normal "stack here" wash over a chat center and the+ * composer's "Drop to link this chat" overlay never lights — with zero edits to+ * those hot overlay paths.+ *+ * Create-on-commit: the session is only created when the drag commits over a+ * valid target. A sub-threshold release stays an ordinary click (the button's+ * own onClick), an Esc abort or a release on a deny zone creates nothing — no+ * orphan empty sessions.+ */++import type { PointerEvent as ReactPointerEvent } from 'react'++import { queryAllVisible } from '@/components/pane-shell/pane-visibility'+import {+ rectContains,+ slotBefore,+ snapshotStrips,+ snapshotZones,+ startDragSession,+ type StripSnapshot,+ subZonePosition+} from '@/components/pane-shell/tree/renderer/drag-session'+import { $treeDragging, type DropHint, NEW_SESSION_DRAG } from '@/components/pane-shell/tree/store'+import type { EngineZone, ZoneRect } from '@/components/pane-shell/tree/zones-engine'+import { translateNow } from '@/i18n'+import type { AgentProfileRoute } from '@/store/profile'+import type { TileDock } from '@/store/session-states'++import { tileZoneHost } from './tile-zone-host'++/** Create a new session as a tile at a resolved drop target. The shared+ * handler shape threaded from every create-drag source through the sidebar+ * into `openNewSessionTile` — one declaration, so the payload cannot drift+ * between call sites. */+export type NewSessionSplitHandler = (+ dir: TileDock,+ opts?: {+ anchor?: string+ before?: null | string+ cwd?: null | string+ profile?: string+ route?: AgentProfileRoute | null+ }+) => void++/** Where a dragged new session lands. `center` stacks a fresh tab into the+ * anchor's zone (optionally at a strip slot via `before`); an edge dir splits+ * a new tile docked to that edge of the anchor. `cwd` pins the new session to+ * a project's path when the drag started from a project row (null = the+ * default new-session cwd). `profile` / `route` pins the new session to a+ * specific profile when dragged from a profile group. */+export interface NewSessionPlacement {+ anchor: string+ before?: null | string+ cwd?: null | string+ dir: TileDock+ profile?: string+ route?: AgentProfileRoute | null+}++const snapRect = (el: HTMLElement): ZoneRect => {+ const r = el.getBoundingClientRect()++ return { bottom: r.bottom, left: r.left, right: r.right, top: r.top }+}++interface SurfaceSnapshot {+ anchor: string+ rect: ZoneRect+}++function snapshotSurfaces(): SurfaceSnapshot[] {+ return queryAllVisible('[data-session-anchor]').map(el => ({+ anchor: el.dataset.sessionAnchor || 'workspace',+ rect: snapRect(el)+ }))+}++/**+ * Begin dragging a brand-new session from the sidebar's "New session" row. The+ * drop language mirrors a session drag (stack / split), but commit CREATES the+ * session at the resolved placement via `onCreate` rather than moving an+ * existing one. Sub-threshold releases stay ordinary clicks (`opts.onTap`), so+ * the row's normal new-session action is untouched; Esc aborts instantly and+ * creates nothing.+ */+export function startNewSessionDrag(+ onCreate: (placement: NewSessionPlacement) => void,+ e: ReactPointerEvent<HTMLElement>,+ opts?: {+ /** Pin the created session to a project's path (drag from a project row).+ * Omitted/null = the default new-session cwd (drag from "New session"). */+ cwd?: null | string+ /** Ghost chip label — the project's name for a project-row drag, else the+ * default "New session". */+ label?: string+ /** Pin the created session to a specific profile (drag from a profile group). */+ profile?: string+ route?: AgentProfileRoute | null+ onTap?: () => void+ }+) {+ let zones: EngineZone[] = []+ let strips: StripSnapshot[] = []+ let surfaces: SurfaceSnapshot[] = []+ let composers: ZoneRect[] = []+ let zoneHost = new Map<string, { chat: boolean; pane: string }>()++ // Commit intent, updated per resolved move (the machinery flushes the final+ // move before commit, so this always matches the released-at position).+ let placement: NewSessionPlacement | null = null++ // The drag SOURCE (the "New session" row or a project's + button). Dimmed+ // while lifted so it reads as "picked up" — the same in-place feedback a+ // sidebar session row uses.+ const source = e.currentTarget+ const restoreOpacity = source?.style.opacity ?? ''++ startDragSession(e, {+ ghost: { label: opts?.label || translateNow('sidebar.nav.new-session') },+ onTap: opts?.onTap,++ onEngage() {+ zones = snapshotZones()+ strips = snapshotStrips()+ surfaces = snapshotSurfaces()+ composers = queryAllVisible('[data-slot="composer-root"]').map(snapRect)+ zoneHost = new Map(+ zones.flatMap(z => {+ const host = tileZoneHost(z.id)++ return host ? [[z.id, host]] : []+ })+ )+ source?.style.setProperty('opacity', '0.45')+ // The distinct sentinel: the zone overlay lights its normal targets, but+ // the "link to chat" affordance (gated on SESSION_TILE_DRAG) stays dark.+ $treeDragging.set(NEW_SESSION_DRAG)+ },++ onEnd() {+ if (source) {+ source.style.opacity = restoreOpacity+ }+ },++ resolveMove(x, y): DropHint | null {+ const zone = zones.find(z => rectContains(z.rect, x, y))+ const host = zone ? zoneHost.get(zone.id) : null++ if (!zone || !host) {+ placement = null++ return null+ }++ // The zone's TAB STRIP stacks the new session at the divider's slot.+ const strip = strips.find(s => s.groupId === zone.id && rectContains(s.rect, x, y))++ if (strip) {+ const stack = slotBefore(strip.slots, x)+ placement = {+ anchor: host.pane,+ before: stack.before,+ cwd: opts?.cwd,+ dir: 'center',+ profile: opts?.profile,+ route: opts?.route+ }++ return { groupId: zone.id, groupIds: [zone.id], kind: 'group', pos: 'center', stack }+ }++ // Over the composer (and everything in it) counts as the zone CENTER —+ // dropping on a chat's input stacks into that chat, never splits below it.+ const surface = surfaces.find(s => rectContains(s.rect, x, y))+ const anchor = surface?.anchor ?? host.pane+ const pos = composers.some(rect => rectContains(rect, x, y)) ? 'center' : subZonePosition(zones, zone.id, x, y)++ if (pos === 'center') {+ placement = { anchor, cwd: opts?.cwd, dir: 'center', profile: opts?.profile, route: opts?.route }+ } else {+ placement = { anchor, cwd: opts?.cwd, dir: pos, profile: opts?.profile, route: opts?.route }+ }++ return { groupId: zone.id, groupIds: [zone.id], kind: 'group', pos }+ },++ onCommit() {+ if (!placement) {+ return+ }++ // The create path (openNewSessionTile) owns the post-create reveal — it+ // round-trips session.create, then revealTreePane's the fresh tile. A+ // commit with no placement (release on a deny zone) creates nothing.+ onCreate(placement)+ }+ })+}++/**+ * Begin dragging a brand-new PROJECT from the project-overview header's+ * "New project" + button. Same machinery and drop language as+ * {@link startNewSessionDrag} — tab strip / pane edge / pane center — but the+ * gesture arms a placement that is CONSUMED BY THE DIALOG FLOW rather than+ * creating anything at release:+ *+ * 1. Engaging the drag records the placement via `onArm`.+ * 2. A sub-threshold release stays an ordinary click (`opts.onTap` → the+ * project dialog); an Esc abort or a deny-zone release creates nothing and+ * clears the armed placement.+ * 3. A valid commit opens the exact same "New project" dialog. When that flow+ * later creates a project, the completion side replays the placement so the+ * project's fresh session draft opens precisely where it was dropped — and+ * stays there.+ */+export function startNewProjectDrag(+ onArm: (placement: NewSessionPlacement | null) => void,+ e: ReactPointerEvent<HTMLElement>,+ opts?: { onTap?: () => void }+) {+ let zones: EngineZone[] = []+ let strips: StripSnapshot[] = []+ let surfaces: SurfaceSnapshot[] = []+ let composers: ZoneRect[] = []+ let zoneHost = new Map<string, { chat: boolean; pane: string }>()++ let placement: NewSessionPlacement | null = null++ const source = e.currentTarget+ const restoreOpacity = source?.style.opacity ?? ''++ startDragSession(e, {+ ghost: { label: translateNow('sidebar.projects.newButton') },+ onTap: opts?.onTap,++ onEngage() {+ zones = snapshotZones()+ strips = snapshotStrips()+ surfaces = snapshotSurfaces()+ composers = queryAllVisible('[data-slot="composer-root"]').map(snapRect)+ zoneHost = new Map(+ zones.flatMap(z => {+ const host = tileZoneHost(z.id)++ return host ? [[z.id, host]] : []+ })+ )+ source?.style.setProperty('opacity', '0.45')+ $treeDragging.set(NEW_SESSION_DRAG)+ },++ onEnd() {+ if (source) {+ source.style.opacity = restoreOpacity+ }++ // A drag that never committed (Esc, deny-zone release) leaves no armed+ // placement behind, so a later plain dialog create can't inherit it.+ if (!placement) {+ onArm(null)+ }+ },++ resolveMove(x, y): DropHint | null {+ const zone = zones.find(z => rectContains(z.rect, x, y))+ const host = zone ? zoneHost.get(zone.id) : null++ if (!zone || !host) {+ placement = null++ return null+ }++ const strip = strips.find(s => s.groupId === zone.id && rectContains(s.rect, x, y))++ if (strip) {+ const stack = slotBefore(strip.slots, x)+ placement = { anchor: host.pane, before: stack.before, dir: 'center' }++ return { groupId: zone.id, groupIds: [zone.id], kind: 'group', pos: 'center', stack }+ }++ const surface = surfaces.find(s => rectContains(s.rect, x, y))+ const anchor = surface?.anchor ?? host.pane+ const pos = composers.some(rect => rectContains(rect, x, y)) ? 'center' : subZonePosition(zones, zone.id, x, y)++ if (pos === 'center') {+ placement = { anchor, dir: 'center' }+ } else {+ placement = { anchor, dir: pos }+ }++ return { groupId: zone.id, groupIds: [zone.id], kind: 'group', pos }+ },++ onCommit() {+ // A deny-zone release reads as a cancelled drop — same language as+ // Escape and the new-session drag: nothing happens. The dialog only+ // opens on a VALID commit (with the placement armed); a plain click+ // still reaches it through the drag's tap path.+ if (!placement) {+ return+ }++ // Arm BEFORE opening the dialog: the dialog's create path reads the+ // armed placement when it succeeds, so the created project lands+ // exactly here.+ onArm(placement)+ opts?.onTap?.()+ }+ })+}diff --git a/apps/desktop/src/app/chat/session-drag.ts b/apps/desktop/src/app/chat/session-drag.tsindex 5aebe63323b..ae610d0c553 100644--- a/apps/desktop/src/app/chat/session-drag.ts+++ b/apps/desktop/src/app/chat/session-drag.ts@@ -28,7 +28,6 @@import type { PointerEvent as ReactPointerEvent } from 'react'import { queryAllVisible } from '@/components/pane-shell/pane-visibility'-import { findGroup } from '@/components/pane-shell/tree/model'import {rectContains,slotBefore,@@ -38,20 +37,13 @@ import {type StripSnapshot,subZonePosition} from '@/components/pane-shell/tree/renderer/drag-session'-import {- $layoutTree,- $treeDragging,- type DropHint,- isMainStripPane,- isSessionStripPane,- revealTreePane,- SESSION_TILE_DRAG-} from '@/components/pane-shell/tree/store'+import { $treeDragging, type DropHint, revealTreePane, SESSION_TILE_DRAG } from '@/components/pane-shell/tree/store'import type { EngineZone, ZoneRect } from '@/components/pane-shell/tree/zones-engine'import { openSessionTile, type TileDock } from '@/store/session-states'import { requestComposerInsertRefs } from './composer/focus'import { type SessionDragPayload, sessionInlineRef, sessionLabel } from './composer/inline-refs'+import { tileZoneHost } from './tile-zone-host'/** A chat surface's drag-start geometry: the anchor pane id it advertises* (`data-session-anchor`) and the composer a link drop routes to@@ -80,16 +72,9 @@ function snapshotSurfaces(): SurfaceSnapshot[] {}/** A session may land in any zone hosting a MAIN tile — another chat stack, a- * Browser tile, a page — never the sidebar/terminal zones. Returns the pane a- * stack anchors to, plus whether the zone hosts a CHAT surface (only those- * offer the link-to-composer center; a preview zone's center stacks). */-function tileZoneHost(groupId: string): { chat: boolean; pane: string } | null {- const tree = $layoutTree.get()- const panes = tree ? (findGroup(tree, groupId)?.panes ?? []) : []- const pane = panes.find(isSessionStripPane) ?? panes.find(isMainStripPane)-- return pane ? { chat: panes.some(isSessionStripPane), pane } : null-}+ * Browser tile, a page — never the sidebar/terminal zones. Resolves via the+ * shared {@link tileZoneHost} (tile-zone-host.ts) so the eligibility answer+ * is byte-identical to what the zone overlay paints. *//*** Begin dragging a session — a sidebar row OR a tile's own tab (same dropdiff --git a/apps/desktop/src/app/chat/sidebar/chrome-section-add-button.test.tsx b/apps/desktop/src/app/chat/sidebar/chrome-section-add-button.test.tsxnew file mode 100644index 00000000000..17ccca4d7f9--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/chrome-section-add-button.test.tsx@@ -0,0 +1,118 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { SidebarSectionAddButton } from './chrome'++const startNewProjectDrag = vi.hoisted(() => vi.fn())+const startNewSessionDrag = vi.hoisted(() => vi.fn())++vi.mock('@/app/chat/new-session-drag', () => ({ startNewProjectDrag, startNewSessionDrag }))++vi.mock('@/i18n', () => ({+ useI18n: () => ({ t: { sidebar: { nav: { 'new-session': 'New session' } } } })+}))++vi.mock('@/lib/keybinds/use-keybind-hint', () => ({ useKeybindHint: () => null }))++afterEach(cleanup)++beforeEach(() => {+ startNewProjectDrag.mockReset()+ startNewSessionDrag.mockReset()+})++describe('SidebarSectionAddButton', () => {+ it('keeps a sub-threshold press an ordinary new-session click', () => {+ const onPlainClick = vi.fn()+ const onNewSessionSplit = vi.fn()++ render(+ <SidebarSectionAddButton+ ariaLabel="New session"+ onNewSessionSplit={onNewSessionSplit}+ onPlainClick={onPlainClick}+ />+ )++ fireEvent.click(screen.getByRole('button', { name: 'New session' }))++ expect(onPlainClick).toHaveBeenCalledOnce()+ expect(onNewSessionSplit).not.toHaveBeenCalled()+ })++ it('starts the new-session drag on pointer-down and creates at the drop placement', () => {+ const onPlainClick = vi.fn()+ const onNewSessionSplit = vi.fn()++ render(+ <SidebarSectionAddButton+ ariaLabel="New session"+ onNewSessionSplit={onNewSessionSplit}+ onPlainClick={onPlainClick}+ />+ )++ fireEvent.pointerDown(screen.getByRole('button', { name: 'New session' }), { button: 0 })++ expect(startNewSessionDrag).toHaveBeenCalledOnce()++ // Simulate the drag committing over a zone (stack at a strip slot).+ const onCreate = startNewSessionDrag.mock.calls[0]?.[0] as (placement: {+ anchor: string+ before?: null | string+ cwd?: null | string+ dir: 'center' | 'right'+ }) => void++ onCreate({ anchor: 'session-tile:abc', before: null, dir: 'right' })++ expect(onNewSessionSplit).toHaveBeenCalledWith('right', { anchor: 'session-tile:abc', before: null })+ expect(onPlainClick).not.toHaveBeenCalled()+ })++ it('drags the project variant when the + creates a project (project-overview mode)', () => {+ const onArm = vi.fn()+ const onPlainClick = vi.fn()+ const onNewSessionSplit = vi.fn()++ render(+ <SidebarSectionAddButton+ ariaLabel="New project"+ onNewProjectDrag={{ onArm }}+ onNewSessionSplit={onNewSessionSplit}+ onPlainClick={onPlainClick}+ />+ )++ fireEvent.pointerDown(screen.getByRole('button', { name: 'New project' }), { button: 0 })++ expect(startNewProjectDrag).toHaveBeenCalledOnce()+ // The arm callback is what the resolver calls with the dropped placement.+ expect(startNewProjectDrag.mock.calls[0]?.[0]).toBe(onArm)+ // The plain click rides along as the drag's tap action (same dialog).+ expect((startNewProjectDrag.mock.calls[0]?.[2] as { onTap?: () => void } | undefined)?.onTap).toBe(onPlainClick)+ expect(startNewSessionDrag).not.toHaveBeenCalled()++ // A committed drop forwards through the arm, not the session path.+ const onArmFromResolver = startNewProjectDrag.mock.calls[0]?.[0] as (placement: unknown) => void++ onArmFromResolver({ anchor: 'workspace', dir: 'center' })+ expect(onArm).toHaveBeenCalledWith({ anchor: 'workspace', dir: 'center' })+ expect(onNewSessionSplit).not.toHaveBeenCalled()+ })++ it('stays click-only without either drag handler', () => {+ const onPlainClick = vi.fn()++ render(<SidebarSectionAddButton ariaLabel="New project" onPlainClick={onPlainClick} />)++ const button = screen.getByRole('button', { name: 'New project' })++ fireEvent.pointerDown(button, { button: 0 })+ fireEvent.click(button)++ expect(startNewProjectDrag).not.toHaveBeenCalled()+ expect(startNewSessionDrag).not.toHaveBeenCalled()+ expect(onPlainClick).toHaveBeenCalledOnce()+ })+})diff --git a/apps/desktop/src/app/chat/sidebar/chrome.tsx b/apps/desktop/src/app/chat/sidebar/chrome.tsxindex 62f02714286..1bcb2117c8f 100644--- a/apps/desktop/src/app/chat/sidebar/chrome.tsx+++ b/apps/desktop/src/app/chat/sidebar/chrome.tsx@@ -1,6 +1,8 @@import { useStore } from '@nanostores/react'import type * as React from 'react'+import { type NewSessionSplitHandler, startNewProjectDrag, startNewSessionDrag } from '@/app/chat/new-session-drag'+import { Button } from '@/components/ui/button'import { Codicon } from '@/components/ui/codicon'import { DisclosureCaret } from '@/components/ui/disclosure-caret'import { RowButton } from '@/components/ui/row-button'@@ -8,6 +10,7 @@ import { Tip } from '@/components/ui/tooltip'import { compactNumber } from '@/lib/format'import { cn } from '@/lib/utils'import { $sidebarRowMeta } from '@/store/layout'+import type { TileDock } from '@/store/session-states'import {SIDEBAR_ROW_INSET,@@ -31,6 +34,75 @@ export function SidebarSectionMeta({ children }: { children: React.ReactNode })// where callers already look for row chrome.export { SIDEBAR_LEAD_ICON_SIZE, SIDEBAR_ROW_CARD_MIN_H, SIDEBAR_TRUNCATED_LEADING } from './row-geometry'+// The section header's "+" button, hover-revealed (group/section lives on+// SidebarSectionHeader), mirroring the artifacts/file browser header+// affordances. focus-visible keeps them keyboard-reachable.+const HEADER_ACTION_BTN =+ 'text-(--ui-text-tertiary) opacity-0 transition-opacity hover:bg-(--ui-control-hover-background) hover:text-foreground group-hover/section:opacity-100 focus-visible:opacity-100'++// The sessions section header's "+" — the flat list's top-level new-session+// control. Also a drag source, the same gesture as the nav's "New session"+// row: drag it onto a chat zone's tab strip / edge / center to create the+// session exactly there (stack / split). The pointer drag session owns the+// gesture — a sub-threshold release falls through to the onClick (ordinary+// new session), and an engaged drag suppresses that click so it never+// double-creates. Both paths resolve the session's profile identically: the+// create path (`openNewSessionTile`) reads `$newChatProfile` at commit, and+// neither gesture resets it — matching the header "+" click behavior exactly+// (only the nav "New session" row resets it, since it navigates to the draft+// composer instead).+export function SidebarSectionAddButton({+ ariaLabel,+ onNewProjectDrag,+ onNewSessionSplit,+ onPlainClick+}: {+ ariaLabel: string+ /** Present when this header "+" creates a PROJECT (the project-overview+ * mode's "New project" button): dragging it arms where that project should+ * start and a valid drop opens the same "New project" dialog. `onArm` also+ * receives null so an aborted/deny-zone drag can clear a stale placement. */+ onNewProjectDrag?: {+ onArm: (placement: { anchor: string; before?: null | string; cwd?: null | string; dir: TileDock } | null) => void+ }+ /** Absent when this header "+" has no session-creating drag semantics+ * (e.g. the project-overview mode, where the "+" opens the project+ * dialog). Then the button stays click-only unless `onNewProjectDrag` is+ * supplied. */+ onNewSessionSplit?: NewSessionSplitHandler+ onPlainClick: () => void+}) {+ return (+ <Tip label={ariaLabel}>+ <Button+ aria-label={ariaLabel}+ className={HEADER_ACTION_BTN}+ onClick={event => {+ event.stopPropagation()+ onPlainClick()+ }}+ onPointerDown={+ onNewProjectDrag+ ? event => {+ startNewProjectDrag(onNewProjectDrag.onArm, event, { onTap: onPlainClick })+ }+ : onNewSessionSplit+ ? event => {+ startNewSessionDrag(placement => {+ onNewSessionSplit(placement.dir, { anchor: placement.anchor, before: placement.before })+ }, event)+ }+ : undefined+ }+ size="icon-xs"+ variant="ghost"+ >+ <Codicon name="add" size="0.75rem" />+ </Button>+ </Tip>+ )+}+/** Vertical stack of rows (gap-px, single column). */export function SidebarRowStack({ className, ...props }: React.ComponentProps<'div'>) {return <div className={cn('grid grid-cols-[minmax(0,1fr)] gap-px', className)} {...props} />diff --git a/apps/desktop/src/app/chat/sidebar/index.tsx b/apps/desktop/src/app/chat/sidebar/index.tsxindex 41459bd2e1e..3f53fafa7f5 100644--- a/apps/desktop/src/app/chat/sidebar/index.tsx+++ b/apps/desktop/src/app/chat/sidebar/index.tsx@@ -85,6 +85,7 @@ import {} from '@/store/profile'import {$activeProjectId,+ $newProjectDropPlacement,$projects,$projectScope,$projectTree,@@ -127,7 +128,7 @@ import {import { $sessionDotStateById, sessionStatusBucket } from '@/store/session-dot-state'import { $unconfirmedPinWrites } from '@/store/session-pin-sync'import { $removedSessionIds } from '@/store/session-removal'-import { $focusedStoredSessionId, $workingSessionIds, type SplitDir } from '@/store/session-states'+import { $focusedStoredSessionId, $workingSessionIds } from '@/store/session-states'import { ackAllSessionsRead } from '@/store/session-unread'import { markSessionUnread } from '@/store/session-unread-remote'import { $archivedSessions, loadArchivedSessions } from '@/store/sidebar-archive'@@ -143,7 +144,9 @@ import {SKILLS_ROUTE} from '../../routes'import type { SidebarNavItem } from '../../types'+import { type NewSessionSplitHandler, startNewSessionDrag } from '../new-session-drag'+import { SidebarSectionAddButton } from './chrome'import { SidebarCronJobsSection } from './cron-jobs-section'import { SidebarFilterMenu } from './filter-menu'import { SidebarLoadMoreRow } from './load-more-row'@@ -302,8 +305,13 @@ interface ChatSidebarProps extends React.ComponentProps<typeof Sidebar> {onArchiveSession: (sessionId: string) => voidonBranchSession: (sessionId: string) => voidonNewSessionInWorkspace: (path: null | string) => void- /** Create a brand-new session and open it as a tile on `dir`. */- onNewSessionSplit: (dir: SplitDir) => void+ /** Create a brand-new session and open it as a tile. `dir` is the dock edge+ * (or `center` to stack a tab); `anchor`/`before` optionally pin it to a+ * specific zone / tab-strip slot, and `cwd` pins it to a project's path —+ * used by the new-session drags (the "New session" row and the project "+"+ * buttons), which land a fresh session exactly where it's dropped. The+ * context-menu "Open in split" path passes just a `dir`. */+ onNewSessionSplit: NewSessionSplitHandleronManageCronJob: (jobId: string) => voidonTriggerCronJob: (jobId: string) => Promise<void>}@@ -1525,6 +1533,25 @@ export function ChatSidebar({onNavigate(item)}}+ onPointerDown={event => {+ // The "New session" row is a drag source too: drag it onto+ // a chat zone's tab strip / edge / center to create the+ // session exactly there (stack / split). The pointer drag+ // session owns the gesture — a sub-threshold release falls+ // through to the onClick above (ordinary new session), and+ // an engaged drag suppresses that click so it never+ // double-creates. The create callback sets $newChatProfile+ // itself (the suppressed click can't), so a dragged new+ // session lands in the same profile a click would.+ if (!isNewSession) {+ return+ }++ startNewSessionDrag(placement => {+ $newChatProfile.set(null)+ onNewSessionSplit(placement.dir, { anchor: placement.anchor, before: placement.before })+ }, event)+ }}tooltip={item.keybindActionId? {@@ -1777,27 +1804,35 @@ export function ChatSidebar({</div>) : (<>- {!showAllProfiles ? (- <Tip label={agentsGrouped ? s.projects.newButton : s.nav['new-session']}>- <Button- aria-label={agentsGrouped ? s.projects.newButton : s.nav['new-session']}- className={HEADER_ACTION_BTN}- onClick={event => {- event.stopPropagation()-- if (agentsGrouped) {- openProjectCreate()- } else {- onNewSessionInWorkspace(null)+ {/* The flat-list header "+" is a drag source too — the+ same gesture as the nav's "New session" row: drag+ it onto a chat zone's tab strip / edge / center to+ create the session exactly there. Project-overview+ mode drags its "+" (the "New project" button) with+ the project-drag variant: a drop opens the SAME+ project dialog, and the created project starts at+ the dropped spot. */}+ <SidebarSectionAddButton+ ariaLabel={agentsGrouped ? s.projects.newButton : s.nav['new-session']}+ onNewProjectDrag={+ agentsGrouped+ ? {+ // Dragging the "New project" + arms WHERE the+ // project should start; the dialog flow consumes+ // it on create (see $newProjectDropPlacement).+ onArm: placement => $newProjectDropPlacement.set(placement)}- }}- size="icon-xs"- variant="ghost"- >- <Codicon name="add" size="0.75rem" />- </Button>- </Tip>- ) : null}+ : undefined+ }+ onNewSessionSplit={agentsGrouped ? undefined : onNewSessionSplit}+ onPlainClick={() => {+ if (agentsGrouped) {+ openProjectCreate()+ } else {+ onNewSessionInWorkspace(null)+ }+ }}+ /><div className="grid size-6 place-items-center"><SidebarFilterMenu className={HEADER_NAV_BTN} /></div>@@ -1819,10 +1854,8 @@ export function ChatSidebar({onBranchSession={onBranchSession}onDeleteSession={onDeleteSession}onEnterProject={onEnterProject}- // Unlike reorder below, this stays on across profiles: a folder- // is a folder, and the new session lands in the active profile- // — the same one the composer would have started it in.onNewSessionInWorkspace={onNewSessionInWorkspace}+ onNewSessionSplit={onNewSessionSplit}onReorderProjects={showAllProfiles ? undefined : reorderProjects}onReorderSessions={showAllProfiles ? undefined : reorderSessions}onResumeSession={onResumeSession}diff --git a/apps/desktop/src/app/chat/sidebar/project-dialog.test.tsx b/apps/desktop/src/app/chat/sidebar/project-dialog.test.tsxindex 17bc5dd9c7b..0a1fdd9e77d 100644--- a/apps/desktop/src/app/chat/sidebar/project-dialog.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/project-dialog.test.tsx@@ -1,4 +1,4 @@-import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import type * as Nanostores from 'nanostores'import { afterEach, describe, expect, it, vi } from 'vitest'@@ -38,10 +38,12 @@ vi.mock('@/i18n', () => ({// store (backend calls, project list, etc.) which is irrelevant to the Tip fix.// vi.mock factories are hoisted above the rest of the file, so the atom must// be created inside vi.hoisted to exist by the time the factory runs.-const { $projectDialog } = vi.hoisted(() => {+const { $newProjectDropPlacement, $projectDialog } = vi.hoisted(() => {const { atom } = require('nanostores') as typeof Nanostoresreturn {+ // Where a "New project" DRAG armed its drop (null = plain click).+ $newProjectDropPlacement: atom<{ anchor: string; before?: null | string; dir: string } | null>(null),$projectDialog: atom<{ mode: 'create' | 'rename' | 'add-folder'; name?: string; projectId?: string } | null>({mode: 'create'})@@ -49,8 +51,10 @@ const { $projectDialog } = vi.hoisted(() => {})vi.mock('@/store/projects', () => ({+ $newProjectDropPlacement,$projectDialog,addProjectFolder: vi.fn(),+ clearNewProjectDropPlacement: vi.fn(),closeProjectDialog: vi.fn(),createProject: vi.fn(),generateProjectIdea: vi.fn(),@@ -68,6 +72,21 @@ vi.mock('@/lib/project-idea-templates', () => ({const tipTrigger = (el: HTMLElement) => el.closest('[data-slot="tooltip-trigger"]')+// Fill the create form and click Create once the form is actually submittable+// (creation requires a name + at least one folder, so the button stays+// disabled until both are in). Awaiting the enable also keeps an async submit+// from one test leaking into the next.+async function fillCreateForm() {+ fireEvent.change(screen.getByPlaceholderText('Project name'), { target: { value: 'Skunkworks' } })+ fireEvent.click(screen.getByRole('button', { name: 'Add folder' }))+ await screen.findByText('/Users/test/my-folder')++ const create = screen.getByRole('button', { name: 'Create' }) as HTMLButtonElement++ await waitFor(() => expect(create.disabled).toBe(false))+ fireEvent.click(create)+}+describe('ProjectDialog', () => {it('wraps the "shuffle idea" button in a Tip', () => {render(<ProjectDialog />)@@ -84,4 +103,57 @@ describe('ProjectDialog', () => {const button = await screen.findByRole('button', { name: 'Remove folder' })expect(tipTrigger(button)).toBeTruthy()})++ it('forwards an armed drag placement to createProject on submit', async () => {+ const { clearNewProjectDropPlacement, createProject } = vi.mocked(await import('@/store/projects'))+ const placement = { anchor: 'workspace', dir: 'center' }++ $newProjectDropPlacement.set(placement)+ render(<ProjectDialog />)+ await fillCreateForm()+ await waitFor(() => expect(createProject).toHaveBeenCalledOnce())+ expect(createProject).toHaveBeenCalledTimes(1)++ expect(createProject.mock.calls[0]?.[0]).toMatchObject({ dropPlacement: placement })++ // Closing the dialog clears the store's arm so no later create inherits it.+ // The clear rides the post-close effect, so wait for it to flush.+ await waitFor(() => expect(clearNewProjectDropPlacement).toHaveBeenCalled())+ })++ it('keeps the armed placement when the create FAILS, so a retry still lands where dropped', async () => {+ const { clearNewProjectDropPlacement, createProject } = vi.mocked(await import('@/store/projects'))+ const placement = { anchor: 'workspace', dir: 'right' }++ vi.mocked(createProject).mockClear()+ vi.mocked(clearNewProjectDropPlacement).mockClear()+ vi.mocked(createProject).mockRejectedValueOnce(new Error('gateway hiccup'))++ $newProjectDropPlacement.set(placement)+ render(<ProjectDialog />)+ await fillCreateForm()+ await waitFor(() => expect(createProject).toHaveBeenCalledOnce())++ // The failed attempt consumed nothing and closed nothing — the dialog+ // stays open for a retry with the placement intact.+ expect(clearNewProjectDropPlacement).not.toHaveBeenCalled()+ expect(createProject.mock.calls[0]?.[0]).toMatchObject({ dropPlacement: placement })++ // Retry succeeds → forwards the SAME placement.+ await fillCreateForm()+ await waitFor(() => expect(createProject).toHaveBeenCalledTimes(2))+ expect(createProject.mock.calls[1]?.[0]).toMatchObject({ dropPlacement: placement })+ })++ it('sends no placement when opened by a plain click', async () => {+ const { createProject } = vi.mocked(await import('@/store/projects'))++ vi.mocked(createProject).mockClear()+ $newProjectDropPlacement.set(null)+ render(<ProjectDialog />)+ await fillCreateForm()+ await waitFor(() => expect(createProject).toHaveBeenCalledOnce())++ expect(createProject.mock.calls[0]?.[0]).toMatchObject({ dropPlacement: undefined })+ })})diff --git a/apps/desktop/src/app/chat/sidebar/project-dialog.tsx b/apps/desktop/src/app/chat/sidebar/project-dialog.tsxindex a6254a518b5..fff39d52c8a 100644--- a/apps/desktop/src/app/chat/sidebar/project-dialog.tsx+++ b/apps/desktop/src/app/chat/sidebar/project-dialog.tsx@@ -1,6 +1,7 @@import { useStore } from '@nanostores/react'import { useEffect, useRef, useState } from 'react'+import type { NewSessionPlacement } from '@/app/chat/new-session-drag'import { Button } from '@/components/ui/button'import { Codicon } from '@/components/ui/codicon'import {@@ -20,8 +21,10 @@ import { type ProjectIdeaTemplate, randomIdeaTemplates } from '@/lib/project-ideimport { cn } from '@/lib/utils'import { notifyError } from '@/store/notifications'import {+ $newProjectDropPlacement,$projectDialog,addProjectFolder,+ clearNewProjectDropPlacement,closeProjectDialog,createProject,generateProjectIdea,@@ -47,6 +50,22 @@ export function ProjectDialog() {const [submitting, setSubmitting] = useState(false)const nameRef = useRef<HTMLInputElement>(null)+ // A "New project" DRAG arms where the project should start (tab-strip slot /+ // pane edge / pane center) before the dialog opens. Snapshot it per open —+ // the submit forwards it as `dropPlacement`, and closing clears the store's+ // arm so a later plain-click create never inherits a stale placement.+ let dropPlacement: NewSessionPlacement | undefined++ if (open) {+ dropPlacement = $newProjectDropPlacement.get() ?? undefined+ }++ useEffect(() => {+ if (!open) {+ clearNewProjectDropPlacement()+ }+ }, [open])+useEffect(() => {if (open) {setName(state?.name ?? '')@@ -69,8 +88,11 @@ export function ProjectDialog() {}// One submit beat for every flow: guard re-entry, run the write, close on- // success, surface a toast on failure. Callers pass only the write.- const runSubmit = async (write: () => Promise<unknown>) => {+ // success, surface a toast on failure. Callers pass only the write, plus an+ // optional hook that runs exactly when the write SUCCEEDS (before the close)+ // — the New-project drop arm is consumed there, so a failed attempt keeps+ // its placement for the retry while a successful one can't leak it forward.+ const runSubmit = async (write: () => Promise<unknown>, onSuccess?: () => void) => {if (submitting) {return}@@ -79,6 +101,7 @@ export function ProjectDialog() {try {await write()+ onSuccess?.()closeProjectDialog()} catch (err) {notifyError(err, p.createFailed)@@ -124,7 +147,13 @@ export function ProjectDialog() {// A project owns sessions by folder (cwd-prefix), so creation requires at// least one — a folder-less project couldn't hold a session anyway.if (mode === 'create' && trimmed && folders.length) {- await runSubmit(() => createProject({ folders, idea: idea.trim() || undefined, name: trimmed, use: true }))+ // The arm is consumed exactly on SUCCESS (before the close): a failed+ // create leaves the dialog open for a retry that still lands where it+ // was dropped; the open-state effect discards it on cancel/teardown.+ await runSubmit(+ () => createProject({ dropPlacement, folders, idea: idea.trim() || undefined, name: trimmed, use: true }),+ clearNewProjectDropPlacement+ )}}diff --git a/apps/desktop/src/app/chat/sidebar/projects/entered-content.tsx b/apps/desktop/src/app/chat/sidebar/projects/entered-content.tsxindex 7d2fc7117c6..8f7af2f4599 100644--- a/apps/desktop/src/app/chat/sidebar/projects/entered-content.tsx+++ b/apps/desktop/src/app/chat/sidebar/projects/entered-content.tsx@@ -2,6 +2,7 @@ import { useStore } from '@nanostores/react'import type * as React from 'react'import { useMemo, useState } from 'react'+import { type NewSessionSplitHandler, startNewSessionDrag } from '@/app/chat/new-session-drag'import { Codicon } from '@/components/ui/codicon'import { ConfirmDialog } from '@/components/ui/confirm-dialog'import type { HermesGitWorktree } from '@/global'@@ -33,6 +34,7 @@ export function EnteredProjectContent({project,renderRows,onNewSession,+ onNewSessionSplit,repoWorktrees,liveSessions,removedSessionIds@@ -40,6 +42,7 @@ export function EnteredProjectContent({project: SidebarProjectTreerenderRows: (sessions: SessionInfo[]) => React.ReactNodeonNewSession?: (path: null | string) => void+ onNewSessionSplit?: NewSessionSplitHandlerrepoWorktrees?: Record<string, HermesGitWorktree[]>liveSessions?: SessionInfo[]removedSessionIds?: ReadonlySet<string>@@ -64,6 +67,7 @@ export function EnteredProjectContent({key={repo.id}liveSessions={liveSessions}onNewSession={onNewSession}+ onNewSessionSplit={onNewSessionSplit}removedSessionIds={removedSessionIds}renderRows={renderRows}repo={repo}@@ -79,6 +83,7 @@ function RepoFlatSection({showHeader,renderRows,onNewSession,+ onNewSessionSplit,discoveredWorktrees,liveSessions,removedSessionIds@@ -87,6 +92,7 @@ function RepoFlatSection({showHeader: booleanrenderRows: (sessions: SessionInfo[]) => React.ReactNodeonNewSession?: (path: null | string) => void+ onNewSessionSplit?: NewSessionSplitHandlerdiscoveredWorktrees?: HermesGitWorktree[]liveSessions?: SessionInfo[]removedSessionIds?: ReadonlySet<string>@@ -166,6 +172,7 @@ function RepoFlatSection({// The kanban bucket is read-only: it aggregates many task worktrees, so// "new session here" and "remove worktree" have no single target.onNewSession={group.isKanban ? undefined : onNewSession}+ onNewSessionSplit={group.isKanban ? undefined : onNewSessionSplit}onRemove={group.isMain || group.isKanban ? undefined : () => setRemoveTarget(group)}renderRows={renderRows}/>@@ -245,6 +252,24 @@ function RepoFlatSection({setWorkspaceNodeOpen(repo.id, true)onNewSession(repo.path)}}+ onPointerDown={+ onNewSessionSplit+ ? event => {+ startNewSessionDrag(+ placement => {+ setWorkspaceNodeOpen(repo.id, true)+ onNewSessionSplit(placement.dir, {+ anchor: placement.anchor,+ before: placement.before,+ cwd: repo.path+ })+ },+ event,+ { cwd: repo.path, label: s.newSessionIn(repo.label) }+ )+ }+ : undefined+ }/>)}diff --git a/apps/desktop/src/app/chat/sidebar/projects/overview-row.tsx b/apps/desktop/src/app/chat/sidebar/projects/overview-row.tsxindex e7c23a78ec3..8f92767b130 100644--- a/apps/desktop/src/app/chat/sidebar/projects/overview-row.tsx+++ b/apps/desktop/src/app/chat/sidebar/projects/overview-row.tsx@@ -1,6 +1,7 @@import type * as React from 'react'import { useRef } from 'react'+import { type NewSessionSplitHandler, startNewSessionDrag } from '@/app/chat/new-session-drag'import { Codicon } from '@/components/ui/codicon'import type { SessionInfo } from '@/hermes'import { useI18n } from '@/i18n'@@ -64,6 +65,9 @@ interface ProjectOverviewRowProps {project: SidebarProjectTreeonEnter?: (id: string) => voidonNewSession?: (path: null | string) => void+ /** Drag the project's "+" onto a chat zone: create a new session pinned to+ * this project's cwd, placed exactly where it's dropped. */+ onNewSessionSplit?: NewSessionSplitHandlerrenderRows?: (sessions: SessionInfo[]) => React.ReactNodeactiveProjectId?: null | stringpreviewSessions?: SessionInfo[]@@ -78,6 +82,7 @@ export function ProjectOverviewRow({project,onEnter,onNewSession,+ onNewSessionSplit,renderRows,activeProjectId,previewSessions,@@ -120,7 +125,31 @@ export function ProjectOverviewRow({for. */}{!project.isNoProject && <ProjectMenu anchorRef={rowRef} isActive={isActive} project={project} />}{onNewSession && (- <WorkspaceAddButton label={s.newSessionIn(project.label)} onClick={() => onNewSession(project.path)} />+ <WorkspaceAddButton+ label={s.newSessionIn(project.label)}+ onClick={() => onNewSession(project.path)}+ onPointerDown={+ onNewSessionSplit+ ? event => {+ // Drag the "+" onto a chat zone: create the session+ // pinned to this project's cwd, exactly where it's+ // dropped. A sub-threshold release falls through to the+ // onClick above (ordinary new session in main).+ startNewSessionDrag(+ placement => {+ onNewSessionSplit(placement.dir, {+ anchor: placement.anchor,+ before: placement.before,+ cwd: project.path+ })+ },+ event,+ { cwd: project.path, label: s.newSessionIn(project.label) }+ )+ }+ : undefined+ }+ />)}</>}diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx b/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsxindex 33f83827548..619759d05e8 100644--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-group.tsx@@ -2,6 +2,7 @@ import { useStore } from '@nanostores/react'import type * as React from 'react'import { useState } from 'react'+import { type NewSessionPlacement, type NewSessionSplitHandler, startNewSessionDrag } from '@/app/chat/new-session-drag'import { Codicon } from '@/components/ui/codicon'import { ProfileGlyph } from '@/components/ui/profile-glyph'import type { SessionInfo } from '@/hermes'@@ -10,7 +11,7 @@ import { displayPath } from '@/lib/display-path'import { useStoreSelector } from '@/lib/use-session-slice'import { setWorkspaceNodeOpen } from '@/store/layout'import { notifyError } from '@/store/notifications'-import { newSessionInProfile, selectProfile } from '@/store/profile'+import { newSessionInProfile, pinNewChatProfile, selectProfile } from '@/store/profile'import { switchBranchInRepo } from '@/store/projects'import { $sessionProfilesUsage } from '@/store/session'import { $sidebarSessionRankIds } from '@/store/sidebar-sort'@@ -32,12 +33,19 @@ interface SidebarWorkspaceGroupProps {group: SidebarSessionGrouprenderRows: (sessions: SessionInfo[]) => React.ReactNodeonNewSession?: (path: null | string) => void+ onNewSessionSplit?: NewSessionSplitHandler// When set (linked worktree rows), shows a remove affordance that runs a real// `git worktree remove`.onRemove?: () => void}-export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemove }: SidebarWorkspaceGroupProps) {+export function SidebarWorkspaceGroup({+ group,+ renderRows,+ onNewSession,+ onNewSessionSplit,+ onRemove+}: SidebarWorkspaceGroupProps) {const { t } = useI18n()const s = t.sidebarconst isProfileGroup = group.mode === 'profile'@@ -71,20 +79,16 @@ export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemov/>)- const handleNewSession = async () => {+ const prepareWorkspaceTarget = async () => {// Reveal the lane the new session targets — an empty worktree/branch lane// starts collapsed, so without this the session lands in a folder the user// can't see. Stable across the lane's default flipping open once populated.setWorkspaceNodeOpen(group.id, true)if (isProfileGroup) {- newSessionInProfile(group.id)+ pinNewChatProfile(group.id)- return- }-- if (!onNewSession) {- return+ return true}// Main-checkout lanes are branch-labeled views over the same repo root path.@@ -96,18 +100,64 @@ export function SidebarWorkspaceGroup({ group, renderRows, onNewSession, onRemov} catch (err) {notifyError(err, t.statusStack.coding.switchFailed(group.label))- return+ return false}}+ return true+ }++ const handleNewSession = async () => {+ if (isProfileGroup) {+ setWorkspaceNodeOpen(group.id, true)+ newSessionInProfile(group.id)++ return+ }++ if (!onNewSession || !(await prepareWorkspaceTarget())) {+ return+ }+onNewSession(group.path)}+ const handleNewSessionSplit = async (placement: NewSessionPlacement) => {+ if (!onNewSessionSplit || !(await prepareWorkspaceTarget())) {+ return+ }++ onNewSessionSplit(placement.dir, {+ anchor: placement.anchor,+ before: placement.before,+ cwd: group.path,+ profile: isProfileGroup ? group.id : placement.profile+ })+ }+// Profile groups start a fresh session in that profile but keep the// all-profiles browse view; workspace groups seed the new session's cwd.// Main checkout lanes are branch-targeted.const addButton = (onNewSession || isProfileGroup) && (- <WorkspaceAddButton label={s.newSessionIn(group.label)} onClick={() => void handleNewSession()} />+ <WorkspaceAddButton+ label={s.newSessionIn(group.label)}+ onClick={() => void handleNewSession()}+ onPointerDown={+ onNewSessionSplit+ ? event => {+ // Drag the "+" onto a chat zone: create the session pinned to+ // this lane's cwd (or profile for profile groups), exactly where+ // it's dropped. A sub-threshold release falls through to the+ // onClick above.+ startNewSessionDrag(placement => void handleNewSessionSplit(placement), event, {+ cwd: group.path,+ label: s.newSessionIn(group.label),+ profile: isProfileGroup ? group.id : undefined+ })+ }+ : undefined+ }+ />)return (diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-header.tsx b/apps/desktop/src/app/chat/sidebar/projects/workspace-header.tsxindex e9e6d9edb8f..db4f4822c14 100644--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-header.tsx+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-header.tsx@@ -32,13 +32,25 @@ function LaneLabel({ label, title }: { label: string; title?: string }) {}// "+" affordance shared by repo and worktree headers — reveals on header hover.-export function WorkspaceAddButton({ label, onClick }: { label: string; onClick: () => void }) {+// Also a drag source: dragging it starts the new-session drag pinned to the+// project's path (`onPointerDown`), so the created session inherits the+// project's cwd. A sub-threshold release stays an ordinary click (`onClick`).+export function WorkspaceAddButton({+ label,+ onClick,+ onPointerDown+}: {+ label: string+ onClick: () => void+ onPointerDown?: (event: React.PointerEvent<HTMLButtonElement>) => void+}) {return (<Tip label={label}><buttonaria-label={label}className="grid size-4 shrink-0 place-items-center rounded-sm bg-transparent text-(--ui-text-quaternary) opacity-0 transition-opacity hover:bg-(--ui-control-hover-background) hover:text-foreground group-hover/workspace:opacity-100"onClick={onClick}+ onPointerDown={onPointerDown}type="button"><Codicon name="add" size="0.75rem" />diff --git a/apps/desktop/src/app/chat/sidebar/sessions-section-new-session-drag.test.tsx b/apps/desktop/src/app/chat/sidebar/sessions-section-new-session-drag.test.tsxnew file mode 100644index 00000000000..b66cfc86a09--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/sessions-section-new-session-drag.test.tsx@@ -0,0 +1,434 @@+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import type { ReactNode } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import type { SessionInfo } from '@/hermes'+import { switchBranchInRepo } from '@/store/projects'++import {+ EnteredProjectContent,+ type SidebarProjectTree,+ type SidebarSessionGroup,+ SidebarWorkspaceGroup+} from './projects'+import { SidebarSessionsSection, VIRTUALIZE_THRESHOLD } from './sessions-section'+import type { VirtualSessionListProps } from './virtual-session-list'++const startNewSessionDrag = vi.hoisted(() => vi.fn())++vi.mock('../new-session-drag', () => ({ startNewSessionDrag }))++// Capture what the virtualized list receives so the divider wiring can be+// asserted on the long-list path too (jsdom can't measure a real viewport).+const virtualPropsHistory = vi.hoisted(() => [] as VirtualSessionListProps[])++vi.mock('./virtual-session-list', () => ({+ VirtualSessionList: (props: VirtualSessionListProps) => {+ virtualPropsHistory.push(props)++ return <div data-testid="virtual-session-list" />+ }+}))++// Flat-list tests only care about dividers: keep session rows inert so they+// can't collide on accessible names or pull in row-level store dependencies.+vi.mock('./session-row', () => ({+ SidebarSessionRow: ({ session }: { session: SessionInfo }) => (+ <div data-testid={`session-row-${session.id}`}>{session.id}</div>+ )+}))++vi.mock('@/i18n', () => ({+ useI18n: () => ({+ t: {+ common: { cancel: 'Cancel' },+ desktop: {},+ sidebar: {+ dateDivider: {+ earlier: 'Earlier',+ earlierThisMonth: 'Earlier this month',+ lastMonth: 'Last month',+ lastWeek: 'Last week',+ older: 'Older',+ thisMonth: 'This month',+ thisWeek: 'This week',+ today: 'Today',+ yesterday: 'Yesterday'+ },+ nav: { 'new-session': 'New session' },+ newSessionIn: (label: string) => `New session in ${label}`,+ noSessions: 'No sessions yet',+ projects: {+ copyPath: 'Copy path',+ enter: (label: string) => `Enter ${label}`,+ forceRemove: 'Force remove',+ menu: 'Actions',+ removeFromSidebar: 'Remove from sidebar',+ removeWorktree: 'Remove worktree',+ removeWorktreeConfirm: 'Remove this worktree?',+ removeWorktreeDirty: 'This worktree has changes.',+ removeWorktreeFailed: 'Could not remove worktree',+ reorder: (label: string) => `Reorder ${label}`,+ reveal: 'Reveal in file manager',+ toggle: (label: string, open: boolean) => `${open ? 'Show' : 'Hide'} ${label} sessions`+ },+ showMoreIn: (count: number, label: string) => `Show ${count} more in ${label}`+ },+ profiles: { switchToProfile: (label: string) => `Switch to ${label}` },+ statusStack: { coding: { switchFailed: (label: string) => `Could not switch to ${label}` } }+ }+ })+}))++vi.mock('./projects/model', () => ({+ PROJECT_PREVIEW_COUNT: 3,+ SIDEBAR_GROUP_PAGE: 20,+ latestProjectSessions: () => [],+ useWorkspaceNodeOpen: () => [false, vi.fn()]+}))++vi.mock('./projects/project-menu', () => ({+ ProjectContextMenu: ({ children }: { children: ReactNode }) => children,+ ProjectMenu: () => null+}))++vi.mock('@/store/projects', async () => ({+ ...(await vi.importActual('@/store/projects')),+ removeWorktreePath: vi.fn(),+ switchBranchInRepo: vi.fn()+}))++const noop = vi.fn()++const baseProps = () => ({+ activeSessionId: null,+ emptyState: null,+ label: 'Projects',+ onArchiveSession: noop,+ onDeleteSession: noop,+ onNewSessionInWorkspace: noop,+ onResumeSession: noop,+ onToggle: noop,+ onTogglePin: noop,+ onToggleUnread: noop,+ open: true,+ pinned: false,+ sessions: [] as SessionInfo[],+ workingSessionIdSet: new Set<string>()+})++const group = (overrides: Partial<SidebarSessionGroup> = {}): SidebarSessionGroup => ({+ id: '/repo/.worktrees/feature',+ isMain: false,+ label: 'feature',+ path: '/repo/.worktrees/feature',+ sessions: [],+ ...overrides+})++const project = (overrides: Partial<SidebarProjectTree> = {}): SidebarProjectTree => ({+ id: 'project-1',+ isNoProject: false,+ label: 'Project One',+ path: '/repo/project-one',+ repos: [],+ sessionCount: 0,+ ...overrides+})++function commitLatestDrag() {+ expect(startNewSessionDrag).toHaveBeenCalledOnce()++ const commit = startNewSessionDrag.mock.calls[0]?.[0] as (placement: {+ anchor: string+ before?: null | string+ dir: 'center' | 'right'+ }) => void++ commit({ anchor: 'workspace', before: 'session-tile:next', dir: 'right' })+}++afterEach(cleanup)++beforeEach(() => {+ noop.mockClear()+ startNewSessionDrag.mockReset()+ vi.mocked(switchBranchInRepo).mockReset()+})++describe('project-associated new-session drag sources', () => {+ it('drags from the project overview + with the project cwd', () => {+ const onNewSessionSplit = vi.fn()++ render(+ <SidebarSessionsSection {...baseProps()} onNewSessionSplit={onNewSessionSplit} projectOverview={[project()]} />+ )++ fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in Project One' }), { button: 0 })+ commitLatestDrag()++ expect(onNewSessionSplit).toHaveBeenCalledWith('right', {+ anchor: 'workspace',+ before: 'session-tile:next',+ cwd: '/repo/project-one'+ })+ })++ it('drags from a workspace/worktree + with that lane cwd', async () => {+ const onNewSessionSplit = vi.fn()++ render(+ <SidebarSessionsSection+ {...baseProps()}+ groups={[group({ sessions: [{ id: 'workspace-session' } as SessionInfo] })]}+ onNewSessionSplit={onNewSessionSplit}+ />+ )++ fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in feature' }), { button: 0 })+ commitLatestDrag()++ await waitFor(() => {+ expect(onNewSessionSplit).toHaveBeenCalledWith('right', {+ anchor: 'workspace',+ before: 'session-tile:next',+ cwd: '/repo/.worktrees/feature'+ })+ })+ })++ it('switches a main-checkout lane to its labeled branch before creating the dragged session', async () => {+ const onNewSessionSplit = vi.fn()+ vi.mocked(switchBranchInRepo).mockResolvedValue(undefined)++ render(+ <SidebarSessionsSection+ {...baseProps()}+ groups={[+ group({+ id: '/repo::main',+ isMain: true,+ label: 'main',+ path: '/repo',+ sessions: [{ id: 'main-session' } as SessionInfo]+ })+ ]}+ onNewSessionSplit={onNewSessionSplit}+ />+ )++ fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in main' }), { button: 0 })+ commitLatestDrag()++ await waitFor(() => expect(onNewSessionSplit).toHaveBeenCalledOnce())+ expect(switchBranchInRepo).toHaveBeenCalledWith('/repo', 'main')+ expect(vi.mocked(switchBranchInRepo).mock.invocationCallOrder[0]).toBeLessThan(+ onNewSessionSplit.mock.invocationCallOrder[0]+ )+ })++ it('drags from an entered-project repo + with that repo cwd', () => {+ const onNewSessionSplit = vi.fn()++ const repoA = {+ groups: [group({ id: '/repo/a::main', isMain: true, label: 'main', path: '/repo/a' })],+ id: '/repo/a',+ label: 'Repo A',+ path: '/repo/a',+ sessionCount: 1+ }++ const repoB = {+ groups: [group({ id: '/repo/b::main', isMain: true, label: 'main', path: '/repo/b' })],+ id: '/repo/b',+ label: 'Repo B',+ path: '/repo/b',+ sessionCount: 1+ }++ render(+ <SidebarSessionsSection+ {...baseProps()}+ onNewSessionSplit={onNewSessionSplit}+ projectContent={project({ repos: [repoA, repoB], sessionCount: 1 })}+ />+ )++ fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in Repo A' }), { button: 0 })+ commitLatestDrag()++ expect(onNewSessionSplit).toHaveBeenCalledWith('right', {+ anchor: 'workspace',+ before: 'session-tile:next',+ cwd: '/repo/a'+ })+ })++ it('drags profile-group add buttons to start a session in that profile', async () => {+ const onNewSessionSplit = vi.fn()++ render(+ <SidebarWorkspaceGroup+ group={group({ id: 'reviewer', label: 'Reviewer', mode: 'profile', path: null })}+ onNewSession={noop}+ onNewSessionSplit={onNewSessionSplit}+ renderRows={() => null}+ />+ )++ fireEvent.pointerDown(screen.getByRole('button', { name: 'New session in Reviewer' }), { button: 0 })++ expect(startNewSessionDrag).toHaveBeenCalledOnce()+ commitLatestDrag()++ await waitFor(() =>+ expect(onNewSessionSplit).toHaveBeenCalledWith('right', {+ anchor: 'workspace',+ before: 'session-tile:next',+ cwd: null,+ profile: 'reviewer'+ })+ )+ })++ it('does not expose a drag or click source for kanban aggregate lanes', () => {+ const onNewSessionSplit = vi.fn()+ const kanbanGroup = group({ id: 'kanban:review', isKanban: true, label: 'Review board' })++ const kanbanProject = project({+ repos: [+ {+ groups: [kanbanGroup],+ id: '/repo',+ label: 'Repo',+ path: '/repo',+ sessionCount: 0+ }+ ]+ })++ render(+ <EnteredProjectContent+ onNewSession={noop}+ onNewSessionSplit={onNewSessionSplit}+ project={kanbanProject}+ renderRows={() => null}+ />+ )++ expect(screen.queryByRole('button', { name: 'New session in Review board' })).toBeNull()+ expect(startNewSessionDrag).not.toHaveBeenCalled()+ expect(onNewSessionSplit).not.toHaveBeenCalled()+ })+})++describe('flat-list date-divider new-session drag source', () => {+ // Five fresh sessions, then a genuine 3-day pause: `groupEntriesByRecency`+ // cuts the run right there, so the flat list renders exactly one divider+ // below the head.+ const datedSessions = (): SessionInfo[] => {+ const now = Math.floor(Date.now() / 1000)++ return [+ ...Array.from({ length: 5 }, (_, i) => ({ id: `fresh-${i}` })),+ ...Array.from({ length: 2 }, (_, i) => ({ id: `older-${i}` }))+ ].map((row, i) => ({+ handoff_platform: null,+ handoff_state: null,+ id: row.id,+ last_active: i < 5 ? now - i * 60 : now - 3 * 24 * 60 * 60,+ profile: 'default',+ started_at: i < 5 ? now - i * 60 : now - 3 * 24 * 60 * 60+ })) as unknown as SessionInfo[]+ }++ it('drags from a date divider "+" without a cwd (flat recents)', () => {+ const onNewSessionSplit = vi.fn()++ render(+ <SidebarSessionsSection+ {...baseProps()}+ grouping="date"+ onNewSessionSplit={onNewSessionSplit}+ sessions={datedSessions()}+ />+ )++ fireEvent.pointerDown(screen.getByRole('button', { name: 'New session' }), { button: 0 })+ commitLatestDrag()++ expect(onNewSessionSplit).toHaveBeenCalledWith('right', {+ anchor: 'workspace',+ before: 'session-tile:next'+ })+ })++ it('wires the same divider action into the virtualized long list', () => {+ virtualPropsHistory.length = 0+ const onNewSessionSplit = vi.fn()++ const longList = Array.from({ length: VIRTUALIZE_THRESHOLD + 5 }, (_, i) => ({+ handoff_platform: null,+ handoff_state: null,+ id: `session-${i}`,+ last_active: Math.floor(Date.now() / 1000) - i * 60,+ profile: 'default',+ started_at: Math.floor(Date.now() / 1000) - i * 60+ })) as unknown as SessionInfo[]++ render(+ <SidebarSessionsSection+ {...baseProps()}+ grouping="date"+ onNewSessionSplit={onNewSessionSplit}+ sessions={longList}+ />+ )++ const lastProps = virtualPropsHistory.at(-1)++ expect(lastProps?.dividerAction).toBeTruthy()++ // jsdom can't measure a virtual viewport, so mount the divider action the+ // virtualizer would render and assert its drag wiring directly.+ render(<>{lastProps!.dividerAction}</>)+ fireEvent.pointerDown(screen.getByRole('button', { name: 'New session' }), { button: 0 })+ commitLatestDrag()++ expect(onNewSessionSplit).toHaveBeenCalledWith('right', {+ anchor: 'workspace',+ before: 'session-tile:next'+ })+ })++ it('renders no divider "+" when the section lacks a plain-create handler', () => {+ render(+ <SidebarSessionsSection+ {...baseProps()}+ grouping="date"+ onNewSessionInWorkspace={undefined}+ onNewSessionSplit={vi.fn()}+ sessions={datedSessions()}+ />+ )++ expect(screen.queryByRole('button', { name: 'New session' })).toBeNull()+ })++ it('keeps the divider "+" click-only without a split handler', () => {+ const onNewSessionInWorkspace = vi.fn()++ render(+ <SidebarSessionsSection+ {...baseProps()}+ grouping="date"+ onNewSessionInWorkspace={onNewSessionInWorkspace}+ sessions={datedSessions()}+ />+ )++ fireEvent.pointerDown(screen.getByRole('button', { name: 'New session' }), { button: 0 })++ expect(startNewSessionDrag).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/app/chat/sidebar/sessions-section.tsx b/apps/desktop/src/app/chat/sidebar/sessions-section.tsxindex 235b812cd48..1104a8d2abd 100644--- a/apps/desktop/src/app/chat/sidebar/sessions-section.tsx+++ b/apps/desktop/src/app/chat/sidebar/sessions-section.tsx@@ -3,6 +3,7 @@ import { useStore } from '@nanostores/react'import type * as React from 'react'import { useCallback, useEffect, useMemo } from 'react'+import { type NewSessionSplitHandler, startNewSessionDrag } from '@/app/chat/new-session-drag'import { SidebarPanelLabel } from '@/app/shell/sidebar-label'import { DisclosureCaret } from '@/components/ui/disclosure-caret'import { SidebarGroup, SidebarGroupContent } from '@/components/ui/sidebar'@@ -113,6 +114,8 @@ interface SidebarSessionsSectionProps {onTogglePin: (sessionId: string) => voidonToggleUnread: (sessionId: string) => voidonNewSessionInWorkspace?: (path: null | string) => void+ /** Create a new session as a tile at a drop target (drag from a project "+"). */+ onNewSessionSplit?: NewSessionSplitHandlerpinned: booleanrootClassName?: stringcontentClassName?: string@@ -191,6 +194,7 @@ export function SidebarSessionsSection({onTogglePin,onToggleUnread,onNewSessionInWorkspace,+ onNewSessionSplit,pinned,rootClassName,contentClassName,@@ -300,10 +304,29 @@ export function SidebarSessionsSection({// Date dividers head a group the same way a repo header does, so they carry// the same hover-revealed "+". Only for dates: "new session in WORKING" is- // not a thing.+ // not a thing. The divider "+" is a drag source too (the same gesture as the+ // nav's "New session" row): drag it onto a chat zone to create the session+ // exactly there; a sub-threshold release stays the ordinary click. The ONE+ // element here feeds both the plain and the virtualized list paths, so this+ // single wiring covers every date-divider "+" on screen.const dividerAction =grouping === 'date' && onNewSessionInWorkspace ? (- <WorkspaceAddButton label={t.sidebar.nav['new-session']} onClick={() => onNewSessionInWorkspace(null)} />+ <WorkspaceAddButton+ label={t.sidebar.nav['new-session']}+ onClick={() => onNewSessionInWorkspace(null)}+ onPointerDown={+ onNewSessionSplit+ ? event => {+ startNewSessionDrag(placement => {+ onNewSessionSplit(placement.dir, {+ anchor: placement.anchor,+ before: placement.before+ })+ }, event)+ }+ : undefined+ }+ />) : nullconst dividerToggle = useMemo(@@ -443,6 +466,7 @@ export function SidebarSessionsSection({<EnteredProjectContentliveSessions={liveSessions}onNewSession={onNewSessionInWorkspace}+ onNewSessionSplit={onNewSessionSplit}project={projectContent}removedSessionIds={removedSessionIds}renderRows={renderRowsDated}@@ -471,6 +495,11 @@ export function SidebarSessionsSection({key={project.id}onEnter={onEnterProject}onNewSession={onNewSessionInWorkspace}+ onNewSessionSplit={onNewSessionSplit}+ // Keyed by project ID to match the producer: `overlayLivePreviews`+ // writes `out[node.id]` (workspace-groups.ts). A path key made Home+ // (path: null) and any id/path-divergent project fall back to stale+ // preview rows instead of the live overlay.previewSessions={projectOverviewPreviews?.[project.id]}project={project}renderRows={renderRows}@@ -502,6 +531,7 @@ export function SidebarSessionsSection({group={group}key={group.id}onNewSession={onNewSessionInWorkspace}+ onNewSessionSplit={onNewSessionSplit}renderRows={renderRows}/>))diff --git a/apps/desktop/src/app/chat/tile-zone-host.ts b/apps/desktop/src/app/chat/tile-zone-host.tsnew file mode 100644index 00000000000..bab6944fa99--- /dev/null+++ b/apps/desktop/src/app/chat/tile-zone-host.ts@@ -0,0 +1,23 @@+/**+ * Zone eligibility for SESSION drops — the resolve-side half of the drop+ * contract shared with the zone overlay (hostsSessionDropTarget in+ * pane-shell/tree/store decides PAINT; this decides COMMIT). Living apart+ * from either resolver keeps them from importing each other (and dragging+ * their unrelated module graphs together), while still answering the same+ * question with the same pane predicates.+ */++import { findGroup } from '@/components/pane-shell/tree/model'+import { $layoutTree, isMainStripPane, isSessionStripPane } from '@/components/pane-shell/tree/store'++/** A session may land in any zone hosting a MAIN tile — another chat stack, a+ * Browser tile, a page — never the sidebar/terminal zones. Returns the pane a+ * stack anchors to, plus whether the zone hosts a CHAT surface (only those+ * offer the link-to-composer center; a preview zone's center stacks). */+export function tileZoneHost(groupId: string): { chat: boolean; pane: string } | null {+ const tree = $layoutTree.get()+ const panes = tree ? (findGroup(tree, groupId)?.panes ?? []) : []+ const pane = panes.find(isSessionStripPane) ?? panes.find(isMainStripPane)++ return pane ? { chat: panes.some(isSessionStripPane), pane } : null+}diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex c80edb0cfa8..0783e243ac9 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -58,7 +58,7 @@ import {normalizeProfileKey,refreshActiveProfile} from '@/store/profile'-import { $startWorkSessionRequest, followActiveSessionCwd } from '@/store/projects'+import { $newProjectSessionRequest, $startWorkSessionRequest, followActiveSessionCwd } from '@/store/projects'import {$activeSessionId,$connection,@@ -600,6 +600,31 @@ export function ContribWiring({ children }: { children: ReactNode }) {}}, [startSessionInWorkspace, startWorkSessionRequest])+ // "New project" DRAG completion: the dialog created a project that was+ // dropped onto a chat zone (tab-strip slot / pane edge / pane center). Open+ // its fresh session draft exactly there — the same `openNewSessionTile`+ // create path the new-session drags use — so the project starts, and stays,+ // where it was dropped. Consume-once: drop the request after handling.+ const newProjectSessionRequest = useStore($newProjectSessionRequest)++ useEffect(() => {+ if (!newProjectSessionRequest) {+ return+ }++ const { path, placement } = newProjectSessionRequest++ $newProjectSessionRequest.set(null)+ void openNewSessionTile(placement.dir, {+ anchor: placement.anchor,+ before: placement.before,+ cwd: path,+ // Same draft-tab contract as onNewSessionSplit: a center/strip drop is+ // an unlisted draft tab until its first turn; an edge split lists.+ listed: placement.dir === 'center' ? false : undefined+ })+ }, [newProjectSessionRequest, openNewSessionTile])+const composer = useComposerActions({ activeSessionId, currentCwd, requestGateway })const branchInNewChat = useCallback(@@ -992,7 +1017,15 @@ export function ContribWiring({ children }: { children: ReactNode }) {},onNavigate: selectSidebarItem,onNewSessionInWorkspace: path => startSessionInWorkspace(path, { openTab: true }),- onNewSessionSplit: dir => void openNewSessionTile(dir),+ onNewSessionSplit: (dir, opts) =>+ void openNewSessionTile(dir, {+ ...opts,+ // A CENTER drop stacks a fresh TAB: keep the existing draft-tab+ // contract and leave it out of the sidebar until its first turn+ // persists (same as the tab-strip "+" and the occupied-project "+").+ // An EDGE drop SPLITS a visible pane — list it like every other split.+ listed: dir === 'center' ? false : undefined+ }),onPasteClipboardImage: opts => composer.pasteClipboardImage(opts),onPickFiles: () => void composer.pickContextPaths('file'),onPickFolders: () => void composer.pickContextPaths('folder'),diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex cec1ebf5212..d70a6ef326d 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -732,8 +732,11 @@ export function useSessionActions({async (dir: TileDock = 'right',options?: {+ anchor?: string+ before?: null | stringcwd?: null | stringlisted?: boolean+ profile?: stringroute?: AgentProfileRoute | nullworkspaceScope?: SessionTileWorkspaceScope}@@ -747,7 +750,9 @@ export function useSessionActions({// `options?.cwd || resolve…` is wrong for Home: null is falsy and used// to fall through into the last project folder while main chat was// occupied (openTab path for "New session in Home").- const capturedRoute = options?.route === undefined ? resolveNewChatOwnerRoute() : options.route+ const capturedRoute =+ options?.route !== undefined ? options.route : resolveNewChatOwnerRoute(options?.profile)+const workspaceScope = options?.workspaceScope ?? { workspaceMode: 'sessions' }const cwd =@@ -823,7 +828,7 @@ export function useSessionActions({const runtimeInfo = applyRuntimeInfo(created.info, { foreground: false })updateSessionState(created.session_id, state => (runtimeInfo ? { ...state, ...runtimeInfo } : state), stored)- openSessionTile(stored, dir, undefined, undefined, workspaceScope)+ openSessionTile(stored, dir, options?.anchor, options?.before, workspaceScope)patchSessionTile(stored, { runtimeId: created.session_id })if (dir === 'center' && runtimeInfo?.cwd) {diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.test.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.test.tsxindex e1d4b5d56df..548e714adf3 100644--- a/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.test.tsx+++ b/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.test.tsx@@ -5,6 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { registry } from '@/contrib/registry'import type { GroupNode } from '../model'+import { $treeDragging, NEW_SESSION_DRAG, SESSION_TILE_DRAG } from '../store'import { TreeGroup } from './tree-group'@@ -75,4 +76,78 @@ describe('TreeGroup', () => {expect(toggle('Restore').querySelector('i')!.className).toContain('codicon-chevron-up')})++ // The invariant behind the shared eligibility predicate+ // (hostsSessionDropTarget): a session or new-session drag must paint the+ // SAME zones either drag resolver would accept, and stay dark everywhere+ // else. Standing chrome (terminal) is always dark; a zone hosting a chat+ // strip (workspace) paints for both sentinels; with no session-drag active+ // nothing paints even over an eligible zone.+ describe('session-drop overlay eligibility (one truth with the resolvers)', () => {+ const groupFor = (panes: string[], id = 'zone-a'): GroupNode => ({+ active: panes[0]!,+ id,+ minimized: false,+ panes,+ type: 'group'+ })++ const sheet = () => globalThis.document.querySelector('[data-tree-group="zone-a"] .pointer-events-none.absolute')++ async function withDragging(dragging: null | string, run: () => void) {+ await act(async () => {+ $treeDragging.set(dragging)+ })++ try {+ run()+ } finally {+ await act(async () => {+ $treeDragging.set(null)+ })+ }+ }++ it('stays dark over standing chrome (terminal) during a new-session drag', async () => {+ disposePane = registry.register({+ area: 'panes',+ data: { height: '12rem' },+ id: 'terminal',+ render: () => <div>Terminal</div>,+ title: 'Terminal'+ })+ vi.stubGlobal('CSS', { escape: (value: string) => value })++ render(<TreeGroup node={terminalGroup(false)} parentAxis="column" />)++ await withDragging(NEW_SESSION_DRAG, () => {+ expect(sheet()).toBeNull()+ })+ })++ it('lights a chat-strip zone for BOTH session and new-session drags, and only then', async () => {+ disposePane = registry.register({+ area: 'panes',+ data: {},+ id: 'workspace',+ render: () => <div>Chat</div>,+ title: 'Hermes'+ })+ vi.stubGlobal('CSS', { escape: (value: string) => value })++ render(<TreeGroup node={groupFor(['workspace'])} parentAxis="column" />)++ await withDragging(null, () => {+ expect(sheet()).toBeNull()+ })++ await withDragging(SESSION_TILE_DRAG, () => {+ expect(sheet()).not.toBeNull()+ })++ await withDragging(NEW_SESSION_DRAG, () => {+ expect(sheet()).not.toBeNull()+ })+ })+ })})diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsxindex d5f9428a4ca..234cbdfce75 100644--- a/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsx+++ b/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsx@@ -59,9 +59,10 @@ import {closeTreeTabsToRight,collapseTreePane,hideOnlyZoneTabs,+ hostsSessionDropTarget,isCollapsePane,- isMainStripPane,isSessionStripPane,+ NEW_SESSION_DRAG,noteActiveTreeGroup,reloadTreePane,restoreTreePane,@@ -850,10 +851,15 @@ function ZoneDropOverlay({ node }: { node: GroupNode }) {// than painting an idle outline the drop would only refuse. Same test// `tileZoneHost` (session-drag.ts) resolves the drop with, so what lights// up and what commits cannot disagree.- const sessionDrag = dragging === SESSION_TILE_DRAG+ //+ // A NEW-session drag (the "New session" row, the projects' "+" buttons, and+ // the "New project" +) shares the same eligibility contract via the one+ // shared predicate — a fresh session is a chat, so it lands exactly where an+ // existing one may dock. Overlay and resolvers cannot disagree.+ const sessionDrag = dragging === SESSION_TILE_DRAG || dragging === NEW_SESSION_DRAGconst chatZone = node.panes.some(isSessionStripPane)- if (sessionDrag && !chatZone && !node.panes.some(isMainStripPane)) {+ if (sessionDrag && !hostsSessionDropTarget(node.panes)) {return null}diff --git a/apps/desktop/src/components/pane-shell/tree/store.ts b/apps/desktop/src/components/pane-shell/tree/store.tsindex 07e9ed09f70..65647eea765 100644--- a/apps/desktop/src/components/pane-shell/tree/store.ts+++ b/apps/desktop/src/components/pane-shell/tree/store.ts@@ -98,6 +98,15 @@ export const $treeDragging = atom<string | null>(null)* overlay renders its normal targets, scoped to session-hosting zones. */export const SESSION_TILE_DRAG = '__session-tile-drag__'+/** Sentinel `$treeDragging` value for a NEW-session drag (the sidebar's+ * "New session" row dragged into a zone). It reuses the SAME zone overlay as+ * a session drag EXCEPT the "link to chat" affordance never lights: a session+ * that doesn't exist yet can't be `@session`-linked, so a center drop stacks a+ * fresh tab instead. Keeping this distinct from SESSION_TILE_DRAG is what lets+ * the overlay's `sessionDrag` checks (which gate the link affordance) stay+ * false here with zero edits to the hot overlay paths. */+export const NEW_SESSION_DRAG = '__new-session-drag__'+/*** Panes hidden by app chrome toggles (titlebar sidebar / right-sidebar* buttons). The tree KEEPS the zone and its mounted content; a zone whose@@ -501,6 +510,16 @@ export const isMainStripPane = (paneId: string): boolean =>(registry.getArea('panes').find(c => c.id === paneId)?.data as { placement?: string } | undefined)?.placement ==='main'+/** Whether a zone may receive a SESSION drop — an existing session dragged+ * from the sidebar, or a brand-new one dropped from a create-drag ("New+ * session" row, project "+" buttons, "New project" +). Any zone hosting a+ * chat strip or another main tile qualifies; standing side chrome never does.+ * The resolvers (session-drag.ts / new-session-drag.ts) and the zone overlay+ * (tree-group.tsx) share this one truth, so every painted zone can commit+ * and every denied zone stays dark — the two cannot drift apart again. */+export const hostsSessionDropTarget = (paneIds: readonly string[]): boolean =>+ paneIds.some(isSessionStripPane) || paneIds.some(isMainStripPane)+/** The zone the session-tab verbs (⌘T / ⌘⇧T / the strip's "+") act on: the* first of hovered / focused / workspace that hosts a chat strip. Same ladder* ⌘1…⌘9 indexes, so the number keys and the tab verbs can't disagree aboutdiff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.tsindex cf903e120e9..b608f165f0f 100644--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@ -319,14 +319,14 @@ function profilePickConnectionId(profile?: string): null | string {* the owner hint, the optimistic row and every later session-scoped RPC name* the same registry entry. A legacy profile-only activation yields null.*/-export function resolveNewChatOwnerRoute(): AgentProfileRoute | null {+export function resolveNewChatOwnerRoute(forProfile?: string): AgentProfileRoute | null {const explicit = $newChatRoute.get()- if (explicit) {+ if (explicit && (!forProfile || normalizeProfileKey(explicit.profile) === normalizeProfileKey(forProfile))) {return explicit}- const intentProfile = $newChatProfile.get()+ const intentProfile = forProfile ? normalizeProfileKey(forProfile) : $newChatProfile.get()const connectionId = ((intentProfilediff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.tsindex 9730ae6b082..603b9bc35b5 100644--- a/apps/desktop/src/store/projects.ts+++ b/apps/desktop/src/store/projects.ts@@ -1,5 +1,6 @@import { atom } from 'nanostores'+import type { NewSessionPlacement } from '@/app/chat/new-session-drag'import {liveSessionProjectId,NO_PROJECT_ID,@@ -756,6 +757,10 @@ export interface CreateProjectInput {use?: boolean// Free-text project idea; written to IDEA.md at the primary folder on create.idea?: string+ /** Where a "New project" DRAG dropped the project (tab-strip slot / pane+ * edge / pane center). The completion side opens the created project's+ * fresh session draft exactly there; absent = the plain-click behavior. */+ dropPlacement?: NewSessionPlacement}// Generate a project idea via the stateless llm.oneshot RPC (inherits the live@@ -906,6 +911,16 @@ export async function createProject(input: CreateProjectInput): Promise<ProjectI$activeProjectId.set(created.id)}+ // A "New project" DRAG created this: hand the placement to the completion+ // side so the project's fresh session draft opens exactly where it was+ // dropped (tab-strip slot / pane edge / pane center). The plain click+ // path has no placement and keeps its existing behavior.+ const rootPath = created.primary_path ?? created.folders?.[0]?.path ?? input.primaryPath++ if (input.dropPlacement && rootPath) {+ $newProjectSessionRequest.set({ path: rootPath, placement: input.dropPlacement })+ }+setSidebarAgentsGrouped(true)}@@ -1104,6 +1119,12 @@ export function openProjectCreate(): void {$projectDialog.set({ mode: 'create' })}+/** Clear the armed "New project" drag placement — on dialog close, so a later+ * plain-click create can never inherit a stale arm. */+export function clearNewProjectDropPlacement(): void {+ $newProjectDropPlacement.set(null)+}+export function openProjectRename(project: { id: string; name: string }): void {$projectDialog.set({ mode: 'rename', name: project.name, projectId: project.id })}@@ -1225,6 +1246,28 @@ export interface StartWorkSessionRequest {export const $startWorkSessionRequest = atom<StartWorkSessionRequest | null>(null)+// ── "New project" drag placement ─────────────────────────────────────────────+// Dragging the project-overview header's "New project" + onto a chat zone arms+// WHERE the project should start; the dialog flow consumes it on create. Two+// atoms, mirroring $startWorkSessionRequest's token pattern:+//+// - `$newProjectDropPlacement` holds the last armed placement while the+// project dialog is open. The dialog submit reads it when its `createProject`+// succeeds and forwards it as `CreateProjectInput.dropPlacement`. Cleared on+// dialog close so a later plain-click create never inherits a stale arm.+// - `$newProjectSessionRequest` is the consume-once completion signal: the+// controller effect (ContribWiring) watches it, opens the created project's+// fresh session draft at the recorded anchor/slot, and drops the request.+export const $newProjectDropPlacement = atom<NewSessionPlacement | null>(null)++export interface NewProjectSessionRequest {+ /** The created project's root cwd — the fresh draft starts here. */+ path: string+ placement: NewSessionPlacement+}++export const $newProjectSessionRequest = atom<NewProjectSessionRequest | null>(null)+// The "make a new worktree" intent, from the keyboard or a menu. One dialog is// mounted, in the sidebar beside ProjectDialog, and it reads this atom. This// mirrors $projectDialog. This atom was a monotonic token that every mounted