From 1383db4563df83c68f157e49908c08a739a6f539 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Mon, 26 Oct 2026 00:05:38 -0400 Subject: [PATCH 1/5] fix(web): a Viewer or one-thread Collaborator isn't offered New thread, Fork or Add project A device holds its person's highest level's permissions anywhere on the server, and upstream offers a new thread to every connection, so a Viewer, a Viewer of one thread who writes to another, and a Collaborator on one thread were offered New thread, Fork from this response, Add project and a thread's branch changes, which the server then refused. One J5 rule, sharingAllowsStart in client-runtime, says where a person may start something: a thread or a fork takes the project's level, a project of its own a level at server scope. The web reads it through useCanStartIn, useCanAddProject and useCanForkThread (and readCanStartThreadIn outside a render), called beside each upstream check: the sidebars' New thread buttons and menus, the command palette, the New thread keybindings, the scratch doors, the fork button, and the Add project flow's submit. The git controls' thread-branch changes read useCanOperateThread. Each control is hidden or disabled as that surface already does. FORK.md case 85. Closes #640, closes #641. Co-Authored-By: Claude Opus 5.5 --- FORK.md | 28 +++++++-- .../BranchToolbarBranchSelector.tsx | 3 +- apps/web/src/components/CommandPalette.tsx | 21 ++++--- .../GitActionsControl.lifecycle.test.ts | 7 +++ .../src/components/GitActionsControl.test.ts | 7 +++ apps/web/src/components/GitActionsControl.tsx | 6 +- apps/web/src/components/LegacySidebar.tsx | 55 ++++++++++------- apps/web/src/components/Sidebar.tsx | 7 ++- .../src/components/chat/MessagesTimeline.tsx | 7 ++- apps/web/src/hooks/useScratchProject.ts | 13 +++- apps/web/src/j5/sharing/access.ts | 60 ++++++++++++++++++- apps/web/src/j5/sharing/sharingMenu.test.ts | 31 ++++++++-- apps/web/src/j5/sharing/sharingMenu.ts | 24 ++++++-- apps/web/src/j5/sharing/threadOperability.ts | 27 ++++++++- apps/web/src/lib/chatThreadActions.ts | 3 +- .../client-runtime/src/j5/sharing.test.ts | 50 ++++++++++++++++ packages/client-runtime/src/j5/sharing.ts | 19 ++++++ 17 files changed, 312 insertions(+), 56 deletions(-) diff --git a/FORK.md b/FORK.md index 72555b2960605..a155af198379d 100644 --- a/FORK.md +++ b/FORK.md @@ -76,7 +76,7 @@ These files exist upstream, but J5 owns its copy outright and they are not integ ### Sanctioned appended integration cases -Against upstream pin `70d60e03a7a35c6fa131825bbfa05ec893e69912`, the inventory has 85 entries: 1–84 plus 15b. Sixteen are retired and keep their numbers (10–14, 15b, 16–18, 20, 27–29, 54, 55, 61), and 19 and 39 are retired except for a remainder. Existing numbers never change; a new case takes the next number. Line coordinates and landing SHAs below describe historical integrations; use named symbols and tests after upstream movement. Branding has its own inventory in `BRANDING.md`; temporary defect patches are listed separately below. +Against upstream pin `70d60e03a7a35c6fa131825bbfa05ec893e69912`, the inventory has 86 entries: 1–85 plus 15b. Sixteen are retired and keep their numbers (10–14, 15b, 16–18, 20, 27–29, 54, 55, 61), and 19 and 39 are retired except for a remainder. Existing numbers never change; a new case takes the next number. Line coordinates and landing SHAs below describe historical integrations; use named symbols and tests after upstream movement. Branding has its own inventory in `BRANDING.md`; temporary defect patches are listed separately below. 1. A1's independent communication-ledger migration lane: in `apps/server/src/persistence/Sqlite.ts`, `layerSetup` runs `runJ5CompatibleUpstreamMigrations` and then `runJ5A2AMigrations` where upstream calls `runMigrations()`, before upstream's `PRAGMA optimize`. Upstream's `layerConfig` has already run `initializeV2Database`, which copies `state.sqlite` to `statev2.sqlite`, so both run only against `statev2.sqlite`. J5 adopts that copy-on-first-start unchanged (Jackson's 2026-09-24 decision #2): an existing `statev2.sqlite` wins and `state.sqlite` is never recopied or written again, so the cutover is one-way: writes after the first V2 boot are invisible to an older binary. Snapshot before the upgrade, and roll back across it by stopping writers and moving `statev2.sqlite` aside (`docs/j5/runbooks/dogfood-runtime.md`); never run old and new binaries against the two files. `layerFromPath` calls one J5 step, `snapshotBeforeMigrations` (`apps/server/src/j5/persistence/MigrationSnapshot.ts`), before it builds the SQL layer, so every file-backed open is covered. When the database has migration history and either lane has a migration pending (upstream's `effect_sql_migrations` against upstream's manifest, or `j5_a2a_migrations` against J5's ledger list), it is first copied with `VACUUM INTO`, through a read-only connection, to `statev2.pre-migration-u-j.sqlite` beside it, named for the newest migration each lane had recorded. The copy is synchronous and does not use `node:sqlite`'s `backup()`: on the Node 26 that release executables embed, `backup()` rejects the one-step rate Node 24 accepts and its promise settles only when another event wakes the loop, which stopped the first nightly from starting. The snapshot is a compacted copy in rollback-journal mode; the server sets WAL again when it opens a restored one. A database with no history, or with nothing pending, is not copied. The newest three snapshots are kept (`MIGRATION_SNAPSHOTS_KEPT`) and older ones deleted. This is the roll-forward policy's emergency exit (issue #507): J5 adds no refusal to start on a database newer than the build, as upstream adds none for that case. Upstream refuses only a history that would skip one of V2's own migrations (`assertV2MigrationsCanRun` in `Migrations.ts`), and a second server on the same home (`apps/server/src/serverOwnership.ts`, exit 78), whose lock `layerMakeServer` takes before anything opens the database, so before the snapshot. A failed copy dies there, so the server does not start and nothing migrates. It dies rather than fails so the layer's error type, which upstream's tests name, stays upstream's. `MigrationSnapshot.test.ts` covers it. The `j5_run_observability_migrations` lane (one index) is not consulted. J5 tooling (`fleet-load.ts`, `devDeliverySeed.ts`, `dogfood-snapshot.sh`, `dogfood-local.sh`) targets `statev2.sqlite`; `apps/server/src/j5/persistence/StateV2Cutover.test.ts` covers the copy, no-recopy and failed-first-boot retry. Case 31 defines the compatibility wrapper; J5's own migration IDs remain in separate tracking tables and run after upstream migration completion. Upstream's `Sqlite.test.ts` test "collects planner statistics for an existing database on open" asserts the row count of the statistic only: with J5's tables in the database, `PRAGMA optimize`'s analysis limit makes the per-value estimate approximate (`1000 96` where upstream expects `1000 100`). 2. The authenticated J5 MCP registration seam: the `layer` of `apps/server/src/mcp/McpHttpServer.ts` calls `layerJ5Toolkits(toolkitRegistration)` (`apps/server/src/j5/a2a/mcp/registration.ts`) in place of upstream's orchestrator, thread, attachment, project and environment registrations. Upstream's preview, preview-controls, worktree, pull-request, device and html toolkits are registered whole, as upstream registers them. Upstream's lint rule `no-raw-mcp-registration` allows MCP registration only in `McpHttpServer.ts`, so J5 registers through the `toolkitRegistration` function that file passes in. `layerJ5Toolkits` registers J5's own tools and the admitted part of those five upstream toolkits. `upstreamCatalog.ts` selects the admitted tools one by one and runs them on upstream's own handlers through `handlersFor`, which is one documented cast. Upstream's `McpServer.toolkit` asks for every tool's declared dependencies at registration, so J5's environment toolkit registration (`registration.ts`) provides `ThreadCommandExecutor.layer`, as upstream's own does. `apps/server/src/mcp/McpInvocationContext.ts` exports `ALL_MCP_CAPABILITIES` and adds the `artifacts` capability that case 33's tools check; nothing imports the export at pin `70d60e03a7`. @@ -451,6 +451,18 @@ migrations after upstream migrations. 84. An agent's steer waits for a Claude turn's running tool calls (register D4, Bryant 2026-10-22). Upstream's `steerTurn` in `apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts` offers every steer with SDK priority `"now"`, which cancels running tool calls. J5-owned leaf `apps/server/src/j5/a2a/claudeAgentSteers.ts` sends a steer that isn't a person's with `"next"` instead: Claude Code lets the tool calls finish and adds the message at the next tool result. A person's steer keeps `"now"` and upstream's capability flags. A late steer can still be queued at the first result, so the leaf follows its `command_lifecycle` frames and holds a clean completion until the turn consuming the steer returns its result. Folded commands share that result. Failed results are never held; upstream handles a person's aborting steer itself. A CLI that reports no lifecycle frames never holds a turn, and a later native turn follows upstream's wake-turn path. Tracking uses a `Map` by provider turn and a `WeakSet` of queries reporting lifecycle. `SilenceDetector` releases tracked steers when a run ends without a clean SDK result, before its membership gate. It sends no unread-after-Stop notice; that design is deferred to #694. The adapter carries four hooks: the leaf import; `j5ObserveClaudeSteer` at the top of `handleSdkMessage`; `j5ClaudeSteerHoldsResult` beside upstream's `isClaudeActiveSteeringAbortResult` in the steered-result branch, where held usage joins `steeredSegmentUsage`; and `j5ClaudeSteerFields` plus `j5OfferClaudeSteer` around the offer in `steerTurn`. J5 delivery's `peerSteeringRun` selects running Claude turns by driver (case 26). Tests: `j5/a2a/claudeAgentSteers.test.ts` covers priority, lifecycle tracking, failed offers and cleanup; `j5/a2a/claudeAgentSteers.integration.test.ts` exercises the real adapter and orchestrator with a scripted SDK stream for mid-tool delivery, a late steer sharing one billed provider turn, Stop while held, and a person's `"now"` steer; `j5/a2a/SilenceDetector.test.ts` checks terminal cleanup without an unread notice. The hold relies on the `@internal` `command_lifecycle` contract of the user's own, unpinned `claude` binary (`provider/Drivers/ClaudeExecutable.ts`), not just the SDK version. For a fresh uuid user message, the assumptions are that the CLI emits `queued`, then consumption or cancellation frames, and a result for the consuming turn; J5 and upstream do not withdraw that queued message, and Stop closes the query. Check those assumptions at Claude Code upgrades as well as upstream advances, including cancellation sources and the four hooks. A steer racing Stop can still run a tool before the process closes (retired D5). Retire this case when upstream delivers agent steers without cancelling tools. If upstream #21158 lands, check that its capability guard does not turn J5's Claude peer steers back into queued turns. +85. Upstream's doors to a new thread, a fork and a new project follow the person's level, as do a thread's branch controls ([#640](https://github.com/Jacksondr5/j5code/issues/640), [#641](https://github.com/Jacksondr5/j5code/issues/641), register D33, Jackson's 2026-10-25 approval of one J5 check beside each upstream check). Upstream offers a new thread to every connection, a read-only one included, as local navigation (`threadActionRequiresOperate` leaves "New thread on " to it), and decides the rest by server-wide permissions, which a device holds at its person's highest level anywhere (case 70). So a Viewer, a Viewer of one thread who writes to another, and a Collaborator on one thread were offered doors the server refuses: a thread or a fork needs the project, and a project needs a level at server scope (case 78's `NARROWED_COMMAND_SCOPES`). The rule is J5-owned `sharingAllowsStart` in `packages/client-runtime/src/j5/sharing.ts`: a thread or a fork takes the project's level (`projectLevelFor`), a project of its own a level at server scope, and a level on one thread starts nothing. The web reads it through `useCanStartIn`, `useCanAddProject` and `useCanForkThread` in `apps/web/src/j5/sharing/access.ts`, and outside a render through `readCanStartThreadIn` in `threadOperability.ts`; a server that has not answered withholds nothing. Each upstream file gains one import and the call beside its own check, and each control is hidden or disabled as that surface already does for what a connection lacks: + + - `apps/web/src/components/Sidebar.tsx`: one hook call, and the header's New thread button is disabled when no listed project can take a thread (`newThreadDisabled`, which read `projects.length === 0`). + - `apps/web/src/components/LegacySidebar.tsx`: one hook call in `SidebarProjectItem`; a project row's hover New thread button is shown only when one of the group's projects can take a thread, as the rows hide the actions a connection lacks, and its thread menu's "New thread on " is disabled by `readCanStartThreadIn`. The newer sidebar's and the thread view's menus get the same from case 71's `withSharingMenuItems` (`sharingMenu.ts`), with no further upstream edit. + - `apps/web/src/components/CommandPalette.tsx`: one hook call; "New thread in…" lists only projects that can take a thread and is left out when none can, and "New thread in " is offered only when that project can. `canCreateProject` and `canCreateClonedProject` read `useCanAddProject`, which holds upstream's "Operate tasks" too, in place of `useEnvironmentScope(…, AuthOrchestrationOperateScope)`, so the Add project flow's submit is disabled with upstream's "This connection cannot add projects." + - `apps/web/src/lib/chatThreadActions.ts`: `startNewThreadFromContext` also returns `false` when `readCanStartThreadIn` refuses the context's project, so the `chat.new` and `chat.newLocal` keybindings and the sidebar's Shift+click do nothing there, as upstream's keybindings do for a permission the connection lacks. + - `apps/web/src/hooks/useScratchProject.ts`: one hook call; `scratchEnvironmentId` offers a server only where a project can be added, so "New thread without a project", its keybinding and the other scratch doors leave out a server that refuses `projects.openScratch` to a narrowed session. + - `apps/web/src/components/chat/MessagesTimeline.tsx`: `AssistantForkButton` calls `useCanForkThread` beside `canForkProjectedAssistantItem` and returns `null` on either, as it did on the one. + - `apps/web/src/components/GitActionsControl.tsx` and `BranchToolbarBranchSelector.tsx`: `canOperateThread` is `useCanOperateThread(…)` in place of upstream's server-wide "Operate tasks", so a Viewer of the thread is not offered a change to the thread's branch. `GitActionsControl.test.ts` and `GitActionsControl.lifecycle.test.ts` mock the J5 hook as that permission (one `vi.mock` each). + + Folder actions (commit, push, pull, Open in editor) are left to upstream's permissions: the server allows them to anyone who holds Collaborator at any scope (case 69, Jackson 2026-10-17), and a Viewer everywhere does not hold them. Mobile is not covered, with the rest of sharing on mobile ([#609](https://github.com/Jacksondr5/j5code/issues/609)). Proof: `packages/client-runtime/src/j5/sharing.test.ts`, "what a connection may start", and `apps/web/src/j5/sharing/sharingMenu.test.ts`, "a new thread from the thread menu". On a pin advance: if upstream adds a door to a new thread, a fork or a project, add the call beside it; if upstream starts gating a new thread on its own permission, keep J5's call beside upstream's; if upstream renames `newThreadDisabled`, `startNewThreadFromContext`, `scratchEnvironmentId`, `canCreateProject` or `AssistantForkButton`, move the call with it. + ## Pin and upstream advance runbook Current pin: `70d60e03a7a35c6fa131825bbfa05ec893e69912`, upstream's nightly tag `v0.1.1-nightly.20261017.3238` on `main` (frozen 2026-10-17). The previous pin was `29980a31409234b676f97bd477c4e46fdb61a929`, from upstream `main`. @@ -790,16 +802,16 @@ explicitly marked. | `apps/web/src/environments/primary/auth.ts` | N | 70 | | `apps/web/src/components/CommandPalette.logic.test.ts` | R | 34 | | `apps/web/src/components/CommandPalette.logic.ts` | R | 34 | -| `apps/web/src/components/CommandPalette.tsx` | A | 42, 71, 75 | +| `apps/web/src/components/CommandPalette.tsx` | A | 42, 71, 75, 85 | | `apps/web/src/components/ConfirmDialogHost.tsx` | R | 22 | -| `apps/web/src/components/LegacySidebar.tsx` | R | 21, 22 | +| `apps/web/src/components/LegacySidebar.tsx` | A | 21, 22, 85 | | `apps/web/src/components/Sidebar.logic.test.ts` | R | 21 | | `apps/web/src/components/Sidebar.logic.ts` | R | 21 | -| `apps/web/src/components/Sidebar.tsx` | A | 21–23, 71, 73 | +| `apps/web/src/components/Sidebar.tsx` | A | 21–23, 71, 73, 85 | | `apps/web/src/components/chat/ChatComposer.tsx` | A | Saved-agent mentions, Role library, 45, 49, 73 | | `apps/web/src/components/chat/MessagesTimeline.test.tsx` | N | B | | `apps/web/src/components/chat/timelineMinimapItems.ts` | A | 24 | -| `apps/web/src/components/chat/MessagesTimeline.tsx` | A | B, 7, 24, 80 | +| `apps/web/src/components/chat/MessagesTimeline.tsx` | A | B, 7, 24, 80, 85 | | `apps/web/src/components/chat/QueuedRunsControl.tsx` | A | 24, 80 | | `apps/web/src/components/sidebar/SidebarChrome.tsx` | A | 6, 33, 75, B | | `apps/web/src/onboarding/firstRun.ts` | N | 75 | @@ -820,6 +832,12 @@ explicitly marked. | `apps/web/src/routes/welcome.tsx` | N | 73 | | `apps/web/src/components/PermissionUpdateNotice.tsx` | N | 73 | | `apps/web/src/components/PermissionUpdateNotice.test.tsx` | N | 73 | +| `apps/web/src/components/GitActionsControl.tsx` | N | 85 | +| `apps/web/src/components/GitActionsControl.test.ts` | N | 85 | +| `apps/web/src/components/GitActionsControl.lifecycle.test.ts` | N | 85 | +| `apps/web/src/components/BranchToolbarBranchSelector.tsx` | N | 85 | +| `apps/web/src/lib/chatThreadActions.ts` | N | 85 | +| `apps/web/src/hooks/useScratchProject.ts` | N | 85 | | `apps/web/src/components/chat/ComposerPendingUserInputPanel.tsx` | N | 80 | | `apps/web/src/routes/pair.tsx` | N | 73 | | `apps/web/src/routes/__root.tsx` | N | 71, 73 | diff --git a/apps/web/src/components/BranchToolbarBranchSelector.tsx b/apps/web/src/components/BranchToolbarBranchSelector.tsx index 5448358fefe0a..e134c5ebc0100 100644 --- a/apps/web/src/components/BranchToolbarBranchSelector.tsx +++ b/apps/web/src/components/BranchToolbarBranchSelector.tsx @@ -70,6 +70,7 @@ import { ComposerControl } from "./chat/ComposerControl"; import { MiddleTruncate } from "./ui/middle-truncate"; import { BranchPicker, BranchPickerRefItem } from "./BranchPicker"; import { stackedThreadToast, toastManager } from "./ui/toast"; +import { useCanOperateThread } from "../j5/sharing/access"; export interface BranchToolbarBranchSelectorHandle { open: () => void; @@ -116,7 +117,7 @@ export function BranchToolbarBranchSelector({ }: BranchToolbarBranchSelectorProps) { const composerFloatingLayerProps = useComposerMenuProps(); const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope); - const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); + const canOperateThread = useCanOperateThread(environmentId, threadId); const stopThreadSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop"); const updateThreadMetadata = useAtomCommand( threadEnvironment.updateMetadata, diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 99e2ca4567de1..e8f12473f1516 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -2,6 +2,7 @@ import { useHighlightsPaletteItems } from "../j5/highlights/highlightsPalette"; import { useSharingPaletteItems } from "../j5/sharing/sharingPalette"; +import { useCanAddProject, useCanStartIn } from "../j5/sharing/access"; import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; @@ -914,6 +915,7 @@ function OpenCommandPaletteDialog(props: { defaultProjectRef, handleNewThread, }); + const canStartIn = useCanStartIn(); const projectPickerEntries = buildSidebarProjectPickerEntries({ groups: projectGroups, preferredProjectRef: contextualProjectRef, @@ -973,7 +975,7 @@ function OpenCommandPaletteDialog(props: { }) ?? null; const browseEnvironmentId = sourcePicker?.environmentId ?? addProjectEnvironmentId ?? defaultAddProjectEnvironmentId; - const canCreateProject = useEnvironmentScope(browseEnvironmentId, AuthOrchestrationOperateScope); + const canCreateProject = useCanAddProject(browseEnvironmentId); const browseEnvironment = environments.find((environment) => environment.environmentId === browseEnvironmentId) ?? null; const browseEnvironmentIsDesktopLocal = @@ -1196,7 +1198,9 @@ function OpenCommandPaletteDialog(props: { isScratchProject(project, scratchWorkspaceRootFor(project.environmentId)); const projectItems = enumerateCommandPaletteItems( buildProjectActionItems({ - projects: pickerProjects.filter((project) => !isScratch(project)), + projects: pickerProjects.filter( + (project) => !isScratch(project) && canStartIn(project.environmentId, project.id), + ), valuePrefix: "new-thread-in", searchTerms: (project) => { const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`); @@ -1654,12 +1658,16 @@ function OpenCommandPaletteDialog(props: { }); const highlightsPaletteItems = useHighlightsPaletteItems(); const actionItems: Array = []; - if (projects.length > 0) { + if (projects.length > 0 && projectThreadItems.length > 0) { const activeProjectTitle = projectPickerEntries.find((entry) => entry.isPreferred)?.group.displayName ?? (currentProjectId ? (projectTitleById.get(currentProjectId) ?? null) : null); - if (activeProjectTitle) { + if ( + activeProjectTitle && + contextualProjectRef !== null && + canStartIn(contextualProjectRef.environmentId, contextualProjectRef.projectId) + ) { actionItems.push({ kind: "action", value: "action:new-thread", @@ -2894,10 +2902,7 @@ function OpenCommandPaletteDialog(props: { addProjectCloneFlow?.environmentId ?? null, AuthSourceControlWriteScope, ); - const canCreateClonedProject = useEnvironmentScope( - addProjectCloneFlow?.environmentId ?? null, - AuthOrchestrationOperateScope, - ); + const canCreateClonedProject = useCanAddProject(addProjectCloneFlow?.environmentId ?? null); const canCloneProject = canWriteSourceControl && canCreateClonedProject; const isCloneDestinationStep = addProjectCloneFlow?.step === "confirm"; const canSubmitBrowsePath = diff --git a/apps/web/src/components/GitActionsControl.lifecycle.test.ts b/apps/web/src/components/GitActionsControl.lifecycle.test.ts index 84d5b1b4271f9..2dc4e856249af 100644 --- a/apps/web/src/components/GitActionsControl.lifecycle.test.ts +++ b/apps/web/src/components/GitActionsControl.lifecycle.test.ts @@ -26,6 +26,13 @@ vi.mock("~/state/session", () => ({ readEnvironmentScope: (environmentId: unknown, scope: string) => (environmentId === "environment" ? state.scopes : state.primaryScopes).has(scope), })); +// J5 (case 73): the thread's level is J5's; these tests hold the session's permission alone. +vi.mock("~/j5/sharing/access", () => ({ + useCanOperateThread: (environmentId: unknown) => + (environmentId === "environment" ? state.scopes : state.primaryScopes).has( + "orchestration:operate", + ), +})); vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command })); vi.mock("~/state/server", () => ({ serverEnvironment: { configValueAtom: () => null } })); vi.mock("~/state/sourceControl", () => ({ sourceControlEnvironment: { discovery: () => null } })); diff --git a/apps/web/src/components/GitActionsControl.test.ts b/apps/web/src/components/GitActionsControl.test.ts index 1865117965403..26e193d2495b8 100644 --- a/apps/web/src/components/GitActionsControl.test.ts +++ b/apps/web/src/components/GitActionsControl.test.ts @@ -46,6 +46,13 @@ vi.mock("~/state/session", () => ({ readEnvironmentScope: (environmentId: unknown, scope: string) => (environmentId === "environment" ? state.scopes : state.primaryScopes).has(scope), })); +// J5 (case 73): the thread's level is J5's; these tests hold the session's permission alone. +vi.mock("~/j5/sharing/access", () => ({ + useCanOperateThread: (environmentId: unknown) => + (environmentId === "environment" ? state.scopes : state.primaryScopes).has( + "orchestration:operate", + ), +})); vi.mock("~/state/use-atom-command", () => ({ useAtomCommand: (command: unknown) => command })); vi.mock("~/state/server", () => ({ serverEnvironment: { configValueAtom: () => null } })); vi.mock("~/state/sourceControl", () => ({ sourceControlEnvironment: {} })); diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index d72fb0f7e6a93..65a75f423cf66 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -99,6 +99,7 @@ import { } from "~/lib/sourceControlActions"; import { useThreadProjection, useThreadShell } from "~/state/entities"; import { readEnvironmentScope, useEnvironmentScope } from "~/state/session"; +import { useCanOperateThread } from "~/j5/sharing/access"; import { useEnvironmentQuery } from "~/state/query"; import { serverEnvironment } from "~/state/server"; import { sourceControlEnvironment } from "~/state/sourceControl"; @@ -1003,7 +1004,10 @@ export default function GitActionsControl({ activeEnvironmentId, AuthSourceControlWriteScope, ); - const canOperateThread = useEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope); + const canOperateThread = useCanOperateThread( + activeEnvironmentId, + activeThreadRef?.threadId ?? null, + ); const serverConfig = useAtomValue(serverEnvironment.configValueAtom(activeEnvironmentId)); const openInPreferredEditor = useOpenInPreferredEditor( activeEnvironmentId, diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx index bdae27c5a247a..65a05960841c4 100644 --- a/apps/web/src/components/LegacySidebar.tsx +++ b/apps/web/src/components/LegacySidebar.tsx @@ -127,6 +127,8 @@ import { useDesktopUpdateState } from "../state/desktopUpdate"; import { useThreadActions } from "../hooks/useThreadActions"; import { archiveWithPreflight } from "../j5/a2a/archiveFlow"; +import { useCanStartIn } from "../j5/sharing/access"; +import { readCanStartThreadIn } from "../j5/sharing/threadOperability"; import { projectEnvironment } from "../state/projects"; import { threadEnvironment, useEnvironmentThread } from "../state/threads"; import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; @@ -1174,6 +1176,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec isManualProjectSorting, dragHandleProps, } = props; + const canStartIn = useCanStartIn(); const environmentMachine = project.allRemoteMembersAreWsl ? "linux" : project.allRemoteMembersAreDesktopLocal @@ -2328,7 +2331,15 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec const clicked = await api.contextMenu.show( [ ...(thread.branch - ? [{ id: "new-thread-on-branch", label: `New thread on ${thread.branch}` }] + ? [ + { + id: "new-thread-on-branch", + label: `New thread on ${thread.branch}`, + disabled: !readCanStartThreadIn( + scopeProjectRef(thread.environmentId, thread.projectId), + ), + }, + ] : []), { id: "rename", label: "Rename thread", disabled: !canOperateThread }, { id: "mark-unread", label: "Mark unread" }, @@ -2528,26 +2539,28 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec )} - - - - - } - /> - - {newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"} - - + {project.memberProjects.some((member) => canStartIn(member.environmentId, member.id)) ? ( + + + + + } + /> + + {newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"} + + + ) : null} s.clearSelection); const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread); @@ -4645,7 +4646,9 @@ export default function Sidebar() { } onNewProject={openAddProjectCommandPalette} onNewThread={handleNewThreadClick} - newThreadDisabled={projects.length === 0} + newThreadDisabled={ + !projects.some((project) => canStartIn(project.environmentId, project.id)) + } newThreadShortcutLabel={newThreadShortcutLabel} newThreadInProjectShortcutLabel={newThreadInProjectShortcutLabel} showNewThreadInProjectHint={projectGroups.length > 1} diff --git a/apps/web/src/components/chat/MessagesTimeline.tsx b/apps/web/src/components/chat/MessagesTimeline.tsx index 9c37d9a6c13bb..1f45b2dc334d0 100644 --- a/apps/web/src/components/chat/MessagesTimeline.tsx +++ b/apps/web/src/components/chat/MessagesTimeline.tsx @@ -128,6 +128,7 @@ import { useSharedConversationEntries, useSharedMessageAuthor, } from "../../j5/sharing/sharedTimeline"; +import { useCanForkThread } from "../../j5/sharing/access"; import { ThreadContextChip } from "../ThreadContextChip"; import { participantIdsForThreadA2ADelivery, @@ -2740,8 +2741,12 @@ function AssistantForkButton({ projectedItem, capabilities: support.providerSession?.capabilities, }); + const canStartFork = useCanForkThread( + ctx.activeThreadEnvironmentId, + projectedItem.sourceThreadId, + ); - if (!canFork || projectedItem.item.runId === null) return null; + if (!canFork || !canStartFork || projectedItem.item.runId === null) return null; const runId = projectedItem.item.runId; return ( diff --git a/apps/web/src/hooks/useScratchProject.ts b/apps/web/src/hooks/useScratchProject.ts index 5ba47ab852988..99b7c55d1b317 100644 --- a/apps/web/src/hooks/useScratchProject.ts +++ b/apps/web/src/hooks/useScratchProject.ts @@ -9,6 +9,7 @@ import type { EnvironmentId } from "@t3tools/contracts"; import { useCallback } from "react"; import { stackedThreadToast, toastManager } from "~/components/ui/toast"; +import { useCanStartIn } from "~/j5/sharing/access"; import { useEnvironments } from "~/state/environments"; import { projectEnvironment } from "~/state/projects"; import { useAtomCommand } from "~/state/use-atom-command"; @@ -28,6 +29,7 @@ export function useScratchProject() { const { environments } = useEnvironments(); const openScratch = useAtomCommand(projectEnvironment.openScratch, { reportFailure: false }); const handleNewThread = useNewThreadHandler(); + const canStartIn = useCanStartIn(); const scratchWorkspaceRootFor = useCallback( (environmentId: EnvironmentId | null): string | null => { @@ -42,13 +44,18 @@ export function useScratchProject() { const scratchEnvironmentId = useCallback( (current: EnvironmentId | null): EnvironmentId | null => { - if (current !== null) return scratchWorkspaceRootFor(current) !== null ? current : null; + if (current !== null) + return scratchWorkspaceRootFor(current) !== null && canStartIn(current, null) + ? current + : null; const offering = environments.filter( - (entry) => scratchWorkspaceRootFor(entry.environmentId) !== null, + (entry) => + scratchWorkspaceRootFor(entry.environmentId) !== null && + canStartIn(entry.environmentId, null), ); return offering.length === 1 ? (offering[0]?.environmentId ?? null) : null; }, - [environments, scratchWorkspaceRootFor], + [canStartIn, environments, scratchWorkspaceRootFor], ); const openScratchProject = useCallback( diff --git a/apps/web/src/j5/sharing/access.ts b/apps/web/src/j5/sharing/access.ts index e0da29445e17c..6b113c4fbddd8 100644 --- a/apps/web/src/j5/sharing/access.ts +++ b/apps/web/src/j5/sharing/access.ts @@ -4,12 +4,14 @@ import { isOwnerAccess, reachesServer, sharingAllowsOperate, + sharingAllowsStart, threadLevelInProject, type KnownConnectionAccess, } from "@t3tools/client-runtime/j5/sharing"; import { AuthOrchestrationOperateScope, type EnvironmentId, + type ProjectId, type ScopedThreadRef, type ThreadId, } from "@t3tools/contracts"; @@ -25,7 +27,7 @@ import { useEnvironmentScope } from "../../state/session"; import { j5Sharing } from "../state"; import { ownerSomewhereState } from "./settingsAccess.logic"; import { provideSharingMenuAccess } from "./sharingMenu"; -import { provideSharingThreadOperability } from "./threadOperability"; +import { provideSharingStart, provideSharingThreadOperability } from "./threadOperability"; export { j5Sharing }; @@ -106,6 +108,57 @@ export function useCanOperateThread( return permitted && sharingAllowsOperate({ access, level }); } +// Where this connection may start something, read across every server at once so that a list of +// projects asks one atom. A server not yet in the catalog, or not yet answered, withholds nothing. +const startsAtom = Atom.make((get) => { + const accessById = new Map(); + for (const id of get(environmentCatalog.catalogValueAtom).entries.keys()) { + accessById.set(id, get(j5Sharing.connectionAccess(id))); + } + return (environmentId: EnvironmentId, projectId: ProjectId | null) => + sharingAllowsStart(accessById.get(environmentId) ?? null, projectId); +}).pipe(Atom.withLabel("j5:access:starts")); + +/** + * Whether this connection's person may start a thread in a project, or, given no project, add one + * to the server. Upstream offers a new thread to any connection, as a draft only sending makes + * real; its New thread doors ask this, so a Viewer, or a Collaborator on one thread, is not + * offered a thread the server would refuse. + */ +export function useCanStartIn(): ( + environmentId: EnvironmentId, + projectId: ProjectId | null, +) => boolean { + return useAtomValue(startsAtom); +} + +/** + * Whether this connection may add a project to the server: upstream's server-wide "Operate tasks", + * which upstream's Add project flow asks, and a Collaborator's or Owner's level at server scope. + */ +export function useCanAddProject(environmentId: EnvironmentId | null): boolean { + const permitted = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); + const starts = useCanStartIn(); + return permitted && environmentId !== null && starts(environmentId, null); +} + +/** + * Whether this connection may fork a thread: a fork is a new thread in the thread's project, so + * the project's level decides, not the thread's. A thread this client has no shell for is asked + * of the server's level. + */ +export function useCanForkThread( + environmentId: EnvironmentId | null, + threadId: ThreadId | null, +): boolean { + const starts = useCanStartIn(); + const projectId = + useThreadShell( + environmentId === null || threadId === null ? null : scopeThreadRef(environmentId, threadId), + )?.projectId ?? null; + return environmentId !== null && starts(environmentId, projectId); +} + // Upstream's thread action menu asks through `threadOperability.ts` and `sharingMenu.ts`, which // hold none of this module's imports; the open thread's view already holds the level, so these // reads ask nothing. @@ -128,12 +181,17 @@ provideSharingThreadOperability((thread) => }), ); +provideSharingStart((environmentId, projectId) => + appAtomRegistry.get(startsAtom)(environmentId, projectId), +); + provideSharingMenuAccess((thread) => { const access = appAtomRegistry.get(j5Sharing.connectionAccess(thread.environmentId)); if (access === null || access.kind === "service") return null; return { owner: isOwnerAccess(access), level: readThreadLevelInProject(thread), + startsInProject: sharingAllowsStart(access, readThreadShell(thread)?.projectId ?? null), holdsThread: access.kind === "person" && !access.firstOwner && diff --git a/apps/web/src/j5/sharing/sharingMenu.test.ts b/apps/web/src/j5/sharing/sharingMenu.test.ts index bbe4cdbd05240..84b0ef8e99d6a 100644 --- a/apps/web/src/j5/sharing/sharingMenu.test.ts +++ b/apps/web/src/j5/sharing/sharingMenu.test.ts @@ -39,7 +39,7 @@ describe("the thread menu for an Owner", () => { labels( sharingMenuItems( upstream, - { owner: true, level: "owner", holdsThread: true }, + { owner: true, level: "owner", holdsThread: true, startsInProject: true }, { canShare: false }, ), ), @@ -67,7 +67,7 @@ describe("the thread menu for someone who is not an Owner", () => { it("leaves out archiving, deleting and project settings for a Collaborator", () => { const items = sharingMenuItems( upstream, - { owner: false, level: "collaborator", holdsThread: false }, + { owner: false, level: "collaborator", holdsThread: false, startsInProject: true }, { canShare: false }, ); expect(labels(items)).toEqual(["Rename thread", "Mark unread", "Copy", "Share thread…"]); @@ -79,7 +79,7 @@ describe("the thread menu for someone who is not an Owner", () => { labels( sharingMenuItems( upstream, - { owner: false, level: "collaborator", holdsThread: true }, + { owner: false, level: "collaborator", holdsThread: true, startsInProject: true }, { canShare: false }, ), ), @@ -91,7 +91,7 @@ describe("the thread menu for someone who is not an Owner", () => { labels( sharingMenuItems( upstream, - { owner: false, level: "viewer", holdsThread: true }, + { owner: false, level: "viewer", holdsThread: true, startsInProject: false }, { canShare: false }, ), ), @@ -103,7 +103,7 @@ describe("the thread menu for someone who is not an Owner", () => { labels( sharingMenuItems( upstream, - { owner: false, level: "viewer", holdsThread: false }, + { owner: false, level: "viewer", holdsThread: false, startsInProject: false }, { canShare: false }, ), ), @@ -111,6 +111,27 @@ describe("the thread menu for someone who is not an Owner", () => { }); }); +describe("a new thread from the thread menu", () => { + const withBranch: ReadonlyArray> = [ + { id: "new-thread-on-branch", label: "New thread on main" }, + ...upstream, + ]; + const newThread = (startsInProject: boolean) => + sharingMenuItems( + withBranch, + { owner: false, level: "collaborator", holdsThread: true, startsInProject }, + { canShare: false }, + ).find((item) => item.id === "new-thread-on-branch"); + + it("is disabled for a thread's Collaborator, who cannot start one in its project", () => { + expect(newThread(false)?.disabled).toBe(true); + }); + + it("is left as upstream built it for someone who can", () => { + expect(newThread(true)?.disabled).toBeUndefined(); + }); +}); + describe("running an item J5 added", () => { const thread = { environmentId: "env-1", threadId: "thread-1" } as ScopedThreadRef; diff --git a/apps/web/src/j5/sharing/sharingMenu.ts b/apps/web/src/j5/sharing/sharingMenu.ts index 6759586d47c04..0efc6abdba8ea 100644 --- a/apps/web/src/j5/sharing/sharingMenu.ts +++ b/apps/web/src/j5/sharing/sharingMenu.ts @@ -14,14 +14,15 @@ export type SharingMenuActionId = typeof SHARE_THREAD | typeof LEAVE_THREAD; /** * What the thread's server says of the person: whether they own it, their level over the thread, - * and whether they hold a level on the thread itself, which is what they can leave, whatever - * their device may manage. The first owner leaves nothing. `null` while the server has not - * answered, or for a session that is no person's. + * whether they hold a level on the thread itself, which is what they can leave, whatever their + * device may manage, and whether they may start a thread in its project. The first owner leaves + * nothing. `null` while the server has not answered, or for a session that is no person's. */ export interface SharingMenuAccess { readonly owner: boolean; readonly level: PersonLevel | null; readonly holdsThread: boolean; + readonly startsInProject: boolean; } // `access.ts`, which owns the connection runtime, hands the read over when it loads; until then @@ -39,13 +40,18 @@ export function provideSharingMenuAccess( // marker included, which is one value for everyone on the thread (Shared conversations AC19). const OWNERS_ONLY: ReadonlySet = new Set(["archive", "delete", "project-settings"]); const NOT_A_VIEWERS: ReadonlySet = new Set(["mark-unread"]); +// Upstream offers a new thread to a connection that writes nothing, as local navigation; a person +// who cannot start one in the thread's project is shown it disabled, as upstream shows an action a +// connection lacks (AC14). +const STARTS_A_THREAD: ReadonlySet = new Set(["new-thread-on-branch"]); /** * Upstream's thread menu as People and access changes it. "Share thread…" goes after "Copy" * (AC34), disabled on a device without "Manage access", as upstream shows an action a device * lacks. For someone who is not an Owner, the items that are Owners' go, and "Leave thread" takes - * Archive's place when they hold a level on the thread itself (AC48). Upstream's own list is left - * as it was built. + * Archive's place when they hold a level on the thread itself (AC48). "New thread on " is + * disabled for someone who cannot start a thread in the project. Upstream's own list is left as it + * was built. */ export function withSharingMenuItems( items: ReadonlyArray>, @@ -72,7 +78,13 @@ export function sharingMenuItems( access !== null && ((!access.owner && OWNERS_ONLY.has(item.id)) || (access.level === "viewer" && NOT_A_VIEWERS.has(item.id))); - const kept = items.filter((item) => !removed(item)); + const kept = items + .filter((item) => !removed(item)) + .map((item) => + access !== null && !access.startsInProject && STARTS_A_THREAD.has(item.id) + ? { ...item, disabled: true } + : item, + ); const copy = kept.findIndex((item) => item.id === "copy"); const withShare: ReadonlyArray> = copy === -1 ? [...kept, share] : [...kept.slice(0, copy + 1), share, ...kept.slice(copy + 1)]; diff --git a/apps/web/src/j5/sharing/threadOperability.ts b/apps/web/src/j5/sharing/threadOperability.ts index 944170ddedb8f..fcb1f1e49e41d 100644 --- a/apps/web/src/j5/sharing/threadOperability.ts +++ b/apps/web/src/j5/sharing/threadOperability.ts @@ -1,4 +1,10 @@ -import { AuthOrchestrationOperateScope, type ScopedThreadRef } from "@t3tools/contracts"; +import { + AuthOrchestrationOperateScope, + type EnvironmentId, + type ProjectId, + type ScopedProjectRef, + type ScopedThreadRef, +} from "@t3tools/contracts"; import { readEnvironmentScope } from "../../state/session"; @@ -22,3 +28,22 @@ export function readCanOperateThread(thread: ScopedThreadRef): boolean { sharingAllowsOperate(thread) ); } + +// `useCanStartIn`'s answer, handed over by `access.ts` in the same way. Upstream offers a new +// thread to any connection, so until then nothing is withheld. +let sharingAllowsStart: ( + environmentId: EnvironmentId, + projectId: ProjectId | null, +) => boolean = () => true; + +/** Called once by `access.ts` with the read behind `useCanStartIn`. */ +export function provideSharingStart( + read: (environmentId: EnvironmentId, projectId: ProjectId | null) => boolean, +) { + sharingAllowsStart = read; +} + +/** `useCanStartIn` for one project, for code that runs outside a render. */ +export function readCanStartThreadIn(project: ScopedProjectRef): boolean { + return sharingAllowsStart(project.environmentId, project.projectId); +} diff --git a/apps/web/src/lib/chatThreadActions.ts b/apps/web/src/lib/chatThreadActions.ts index ac5412c239753..768c7e500af0a 100644 --- a/apps/web/src/lib/chatThreadActions.ts +++ b/apps/web/src/lib/chatThreadActions.ts @@ -6,6 +6,7 @@ import type { ScopedProjectRef, } from "@t3tools/contracts"; import type { ComposerThreadDraftState, DraftThreadEnvMode } from "../composerDraftStore"; +import { readCanStartThreadIn } from "../j5/sharing/threadOperability"; type ComposerModelSelectionState = Pick< ComposerThreadDraftState, @@ -86,7 +87,7 @@ export async function startNewThreadFromContext( context: ChatThreadActionContext, ): Promise { const projectRef = resolveThreadActionProjectRef(context); - if (!projectRef) { + if (!projectRef || !readCanStartThreadIn(projectRef)) { return false; } diff --git a/packages/client-runtime/src/j5/sharing.test.ts b/packages/client-runtime/src/j5/sharing.test.ts index 991ac73707619..14a8ec3ef7124 100644 --- a/packages/client-runtime/src/j5/sharing.test.ts +++ b/packages/client-runtime/src/j5/sharing.test.ts @@ -30,6 +30,7 @@ import { projectLevelFor, reachesServer, sharingAllowsOperate, + sharingAllowsStart, threadLevelFor, threadLevelInProject, } from "./sharing.ts"; @@ -254,6 +255,55 @@ describe("what a connection may do with a thread it is starting", () => { }); }); +describe("what a connection may start", () => { + const PROJECT = ProjectId.make("project:shared"); + const THREAD = ThreadId.make("thread:one"); + + it("lets a thread's Collaborator start no thread, fork or project", () => { + const access = person([{ scope: { kind: "thread", threadId: THREAD }, level: "collaborator" }]); + expect(sharingAllowsStart(access, PROJECT)).toBe(false); + expect(sharingAllowsStart(access, null)).toBe(false); + }); + + it("lets a project's Collaborator start threads there and add no project", () => { + const access = person([ + { scope: { kind: "server" }, level: "viewer" }, + { scope: { kind: "project", projectId: PROJECT }, level: "collaborator" }, + ]); + expect(sharingAllowsStart(access, PROJECT)).toBe(true); + expect(sharingAllowsStart(access, "project:other")).toBe(false); + expect(sharingAllowsStart(access, null)).toBe(false); + }); + + it("lets a Viewer here who writes to another thread start nothing here", () => { + const access = person([ + { scope: { kind: "project", projectId: PROJECT }, level: "viewer" }, + { scope: { kind: "thread", threadId: THREAD }, level: "collaborator" }, + ]); + expect(sharingAllowsStart(access, PROJECT)).toBe(false); + }); + + it("lets a server's Viewer start nothing anywhere", () => { + expect(sharingAllowsStart(SERVER_VIEWER, PROJECT)).toBe(false); + expect(sharingAllowsStart(SERVER_VIEWER, null)).toBe(false); + }); + + it("lets a server's Collaborator or Owner, or a service, start anything", () => { + const collaborator = person([{ scope: { kind: "server" }, level: "collaborator" }], { + wide: true, + }); + for (const access of [collaborator, OWNER, { kind: "service" } as const]) { + expect(sharingAllowsStart(access, PROJECT)).toBe(true); + expect(sharingAllowsStart(access, null)).toBe(true); + } + }); + + it("withholds nothing before the server answers, and everything from an unplaced device", () => { + expect(sharingAllowsStart(null, null)).toBe(true); + expect(sharingAllowsStart({ kind: "unknown" }, PROJECT)).toBe(false); + }); +}); + describe("a connection that holds two threads of a server", () => { it.effect("reads one thread and writes to another on the same server", () => Effect.gen(function* () { diff --git a/packages/client-runtime/src/j5/sharing.ts b/packages/client-runtime/src/j5/sharing.ts index 4c7e5a77fe816..c50273c3e48e5 100644 --- a/packages/client-runtime/src/j5/sharing.ts +++ b/packages/client-runtime/src/j5/sharing.ts @@ -113,6 +113,25 @@ export const sharingAllowsOperate = (input: { readonly level: PersonLevel | null; }): boolean => input.access === null || levelReaches(input.level, "collaborator"); +/** + * Whether a connection may start something new on its server: a thread, or a fork, in a project, + * which the project's level decides (People and access AC14), or, given no project, a project of + * its own, which only a level at server scope reaches (AC19). A level on one thread starts nothing. + */ +export const sharingAllowsStart = ( + access: KnownConnectionAccess, + projectId: string | null, +): boolean => + sharingAllowsOperate({ + access, + level: + projectId !== null + ? projectLevelFor(access, projectId) + : access?.kind === "service" + ? "owner" + : serverLevelOf(access), + }); + const asksThreadLevel = (access: KnownConnectionAccess) => access?.kind === "person" && !access.wide; From e7029d0b47975f74d56b451151510178457aee3d Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Mon, 26 Oct 2026 00:08:01 -0400 Subject: [PATCH 2/5] docs(j5): register D33 records that upstream's new-thread doors follow the person's level Co-Authored-By: Claude Opus 5.5 --- docs/j5/product/upstream.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/j5/product/upstream.md b/docs/j5/product/upstream.md index 85effb0af960a..5760ab3c07c5b 100644 --- a/docs/j5/product/upstream.md +++ b/docs/j5/product/upstream.md @@ -385,6 +385,7 @@ Each advance checks for new upstream reads of `T3CODE_HOME` or `.t3` paths and n - feeds that carry many threads are filtered where they are produced; - the configuration, the lifecycle welcome and the sidebar are given in a reduced form that names nothing of the host; - requests keyed by a folder the client names are refused to a Viewer; + - upstream's doors to a new thread, a fork and a new project, and a thread's branch controls, are offered only where the person's level lets them start or write; upstream offers them to every connection, a read-only one included; - for now a Viewer is listed a thread's preview tabs and does not watch them, since upstream's preview events cover the whole server ([#540](https://github.com/Jacksondr5/j5code/issues/540)). - **A link is J5's own token**, on a route that takes no sign-in. When it is used, it mints one of upstream's single-use pairing links for that device. It lasts as long as the Owner chose, from an hour to thirty days. A device already paired as one person that opens a link for another is refused before upstream exchanges it, since upstream would replace that browser's session. - **Upstream's own pairing** pairs a device for a person: the startup link, the desktop app and T3 Connect for the first owner, a Connections link for the person whose device made it, and the CLI as divergence D36 says. @@ -608,3 +609,4 @@ J5 kept a run from resuming after a usage-limit reset when the person had presse - 2026-10-24 — D33: lowering or removing an Owner ends the MCP clients that Owner approved, and only those (Jackson; [#639](https://github.com/Jacksondr5/j5code/issues/639)). - 2026-10-25 — D19: a copied prompt link points at j5.codes/new, which opens it in J5's apps or on the person's own server (Jackson's 2026-10-24 decision; [#633](https://github.com/Jacksondr5/j5code/issues/633)). - 2026-10-25 — D4: a delivery to an agent stopped on a usage limit waits unsent until the agent continues, whether or not its queue is held, where it used to be handed over unless messages were held there; deliveries waiting unsent go together, in send order, when a run starts on the agent, where each used to wait for its own recheck (Jackson, 2026-10-24, [#718](https://github.com/Jacksondr5/j5code/issues/718)). +- 2026-10-26 — D33: a Viewer, or a Collaborator on one thread, isn't offered a new thread, a fork or a new project where their level refuses it (Jackson's 2026-10-25 approval; [#640](https://github.com/Jacksondr5/j5code/issues/640), [#641](https://github.com/Jacksondr5/j5code/issues/641)). From 65a78ffc7fa01f016acb706ecfc581f03819d112 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Mon, 26 Oct 2026 00:21:22 -0400 Subject: [PATCH 3/5] fix(web): grouped projects, New project and editor buttons follow the start rule - GitActionsControl keeps upstream's permission for the commit dialog's Open in editor buttons; only branch changes read the thread's level. - The New project flow's Create is disabled where the person cannot add a project, with upstream's "This connection cannot add projects." - A grouped project offers a new thread by a checkout that can take one: the palette narrows each group before upstream picks its checkout (startableProjectPicker), and the legacy sidebar's checkout chooser disables checkouts that cannot. - Rows and buttons read one boolean (useCanStartInAny, useCanAddProject, useCanForkThread by the one server's access), so an unrelated access refresh no longer re-renders every project row and fork button. - The legacy row hides its New thread button with `hidden` on upstream's positioning div instead of wrapping the block. - D33 states upstream's baseline accurately; FORK.md case 85 lists each file's actual edits. Co-Authored-By: Claude Opus 5.5 --- FORK.md | 23 ++--- apps/web/src/components/CommandPalette.tsx | 21 +++-- apps/web/src/components/GitActionsControl.tsx | 6 +- apps/web/src/components/LegacySidebar.tsx | 50 +++++------ apps/web/src/components/Sidebar.tsx | 8 +- apps/web/src/j5/sharing/access.ts | 25 +++++- .../src/j5/sharing/startableProjects.test.ts | 83 +++++++++++++++++++ apps/web/src/j5/sharing/startableProjects.ts | 53 ++++++++++++ docs/j5/product/upstream.md | 2 +- 9 files changed, 218 insertions(+), 53 deletions(-) create mode 100644 apps/web/src/j5/sharing/startableProjects.test.ts create mode 100644 apps/web/src/j5/sharing/startableProjects.ts diff --git a/FORK.md b/FORK.md index a155af198379d..237e814f8f361 100644 --- a/FORK.md +++ b/FORK.md @@ -451,17 +451,18 @@ migrations after upstream migrations. 84. An agent's steer waits for a Claude turn's running tool calls (register D4, Bryant 2026-10-22). Upstream's `steerTurn` in `apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts` offers every steer with SDK priority `"now"`, which cancels running tool calls. J5-owned leaf `apps/server/src/j5/a2a/claudeAgentSteers.ts` sends a steer that isn't a person's with `"next"` instead: Claude Code lets the tool calls finish and adds the message at the next tool result. A person's steer keeps `"now"` and upstream's capability flags. A late steer can still be queued at the first result, so the leaf follows its `command_lifecycle` frames and holds a clean completion until the turn consuming the steer returns its result. Folded commands share that result. Failed results are never held; upstream handles a person's aborting steer itself. A CLI that reports no lifecycle frames never holds a turn, and a later native turn follows upstream's wake-turn path. Tracking uses a `Map` by provider turn and a `WeakSet` of queries reporting lifecycle. `SilenceDetector` releases tracked steers when a run ends without a clean SDK result, before its membership gate. It sends no unread-after-Stop notice; that design is deferred to #694. The adapter carries four hooks: the leaf import; `j5ObserveClaudeSteer` at the top of `handleSdkMessage`; `j5ClaudeSteerHoldsResult` beside upstream's `isClaudeActiveSteeringAbortResult` in the steered-result branch, where held usage joins `steeredSegmentUsage`; and `j5ClaudeSteerFields` plus `j5OfferClaudeSteer` around the offer in `steerTurn`. J5 delivery's `peerSteeringRun` selects running Claude turns by driver (case 26). Tests: `j5/a2a/claudeAgentSteers.test.ts` covers priority, lifecycle tracking, failed offers and cleanup; `j5/a2a/claudeAgentSteers.integration.test.ts` exercises the real adapter and orchestrator with a scripted SDK stream for mid-tool delivery, a late steer sharing one billed provider turn, Stop while held, and a person's `"now"` steer; `j5/a2a/SilenceDetector.test.ts` checks terminal cleanup without an unread notice. The hold relies on the `@internal` `command_lifecycle` contract of the user's own, unpinned `claude` binary (`provider/Drivers/ClaudeExecutable.ts`), not just the SDK version. For a fresh uuid user message, the assumptions are that the CLI emits `queued`, then consumption or cancellation frames, and a result for the consuming turn; J5 and upstream do not withdraw that queued message, and Stop closes the query. Check those assumptions at Claude Code upgrades as well as upstream advances, including cancellation sources and the four hooks. A steer racing Stop can still run a tool before the process closes (retired D5). Retire this case when upstream delivers agent steers without cancelling tools. If upstream #21158 lands, check that its capability guard does not turn J5's Claude peer steers back into queued turns. -85. Upstream's doors to a new thread, a fork and a new project follow the person's level, as do a thread's branch controls ([#640](https://github.com/Jacksondr5/j5code/issues/640), [#641](https://github.com/Jacksondr5/j5code/issues/641), register D33, Jackson's 2026-10-25 approval of one J5 check beside each upstream check). Upstream offers a new thread to every connection, a read-only one included, as local navigation (`threadActionRequiresOperate` leaves "New thread on " to it), and decides the rest by server-wide permissions, which a device holds at its person's highest level anywhere (case 70). So a Viewer, a Viewer of one thread who writes to another, and a Collaborator on one thread were offered doors the server refuses: a thread or a fork needs the project, and a project needs a level at server scope (case 78's `NARROWED_COMMAND_SCOPES`). The rule is J5-owned `sharingAllowsStart` in `packages/client-runtime/src/j5/sharing.ts`: a thread or a fork takes the project's level (`projectLevelFor`), a project of its own a level at server scope, and a level on one thread starts nothing. The web reads it through `useCanStartIn`, `useCanAddProject` and `useCanForkThread` in `apps/web/src/j5/sharing/access.ts`, and outside a render through `readCanStartThreadIn` in `threadOperability.ts`; a server that has not answered withholds nothing. Each upstream file gains one import and the call beside its own check, and each control is hidden or disabled as that surface already does for what a connection lacks: - - - `apps/web/src/components/Sidebar.tsx`: one hook call, and the header's New thread button is disabled when no listed project can take a thread (`newThreadDisabled`, which read `projects.length === 0`). - - `apps/web/src/components/LegacySidebar.tsx`: one hook call in `SidebarProjectItem`; a project row's hover New thread button is shown only when one of the group's projects can take a thread, as the rows hide the actions a connection lacks, and its thread menu's "New thread on " is disabled by `readCanStartThreadIn`. The newer sidebar's and the thread view's menus get the same from case 71's `withSharingMenuItems` (`sharingMenu.ts`), with no further upstream edit. - - `apps/web/src/components/CommandPalette.tsx`: one hook call; "New thread in…" lists only projects that can take a thread and is left out when none can, and "New thread in " is offered only when that project can. `canCreateProject` and `canCreateClonedProject` read `useCanAddProject`, which holds upstream's "Operate tasks" too, in place of `useEnvironmentScope(…, AuthOrchestrationOperateScope)`, so the Add project flow's submit is disabled with upstream's "This connection cannot add projects." - - `apps/web/src/lib/chatThreadActions.ts`: `startNewThreadFromContext` also returns `false` when `readCanStartThreadIn` refuses the context's project, so the `chat.new` and `chat.newLocal` keybindings and the sidebar's Shift+click do nothing there, as upstream's keybindings do for a permission the connection lacks. - - `apps/web/src/hooks/useScratchProject.ts`: one hook call; `scratchEnvironmentId` offers a server only where a project can be added, so "New thread without a project", its keybinding and the other scratch doors leave out a server that refuses `projects.openScratch` to a narrowed session. - - `apps/web/src/components/chat/MessagesTimeline.tsx`: `AssistantForkButton` calls `useCanForkThread` beside `canForkProjectedAssistantItem` and returns `null` on either, as it did on the one. - - `apps/web/src/components/GitActionsControl.tsx` and `BranchToolbarBranchSelector.tsx`: `canOperateThread` is `useCanOperateThread(…)` in place of upstream's server-wide "Operate tasks", so a Viewer of the thread is not offered a change to the thread's branch. `GitActionsControl.test.ts` and `GitActionsControl.lifecycle.test.ts` mock the J5 hook as that permission (one `vi.mock` each). - - Folder actions (commit, push, pull, Open in editor) are left to upstream's permissions: the server allows them to anyone who holds Collaborator at any scope (case 69, Jackson 2026-10-17), and a Viewer everywhere does not hold them. Mobile is not covered, with the rest of sharing on mobile ([#609](https://github.com/Jacksondr5/j5code/issues/609)). Proof: `packages/client-runtime/src/j5/sharing.test.ts`, "what a connection may start", and `apps/web/src/j5/sharing/sharingMenu.test.ts`, "a new thread from the thread menu". On a pin advance: if upstream adds a door to a new thread, a fork or a project, add the call beside it; if upstream starts gating a new thread on its own permission, keep J5's call beside upstream's; if upstream renames `newThreadDisabled`, `startNewThreadFromContext`, `scratchEnvironmentId`, `canCreateProject` or `AssistantForkButton`, move the call with it. +85. Upstream's doors to a new thread, a fork and a new project follow the person's level, as do a thread's branch controls ([#640](https://github.com/Jacksondr5/j5code/issues/640), [#641](https://github.com/Jacksondr5/j5code/issues/641), register D33, Jackson's 2026-10-25 approval of one J5 check beside each upstream check). Upstream offers a new thread or a fork to every connection, a read-only one included, as local navigation (`threadActionRequiresOperate` leaves "New thread on " to it), and decides Add project and branch changes by server-wide permissions, which a device holds at its person's highest level anywhere (case 70). So a Viewer, a Viewer of one thread who writes to another, and a Collaborator on one thread were offered doors the server refuses: a thread or a fork needs the project, and a project needs a level at server scope (case 78's `NARROWED_COMMAND_SCOPES`). The rule is J5-owned `sharingAllowsStart` in `packages/client-runtime/src/j5/sharing.ts`: a thread or a fork takes the project's level (`projectLevelFor`), a project of its own a level at server scope, and a level on one thread starts nothing. The web reads it in `apps/web/src/j5/sharing/access.ts` through `useCanStartIn` (one function over every project, for lists), `useCanStartInAny` (one boolean for a row or a button, which renders again only when that answer changes), `useCanAddProject` and `useCanForkThread`; outside a render through `readCanStartThreadIn` in `threadOperability.ts`; and, for the palette's grouped projects, through `startableProjectPicker` in `startableProjects.ts`, which keeps only a group's checkouts that can take a thread before upstream's `buildSidebarProjectPickerEntries` picks one. A server that has not answered withholds nothing. Each control is hidden or disabled as that surface already does for what a connection lacks: + + - `apps/web/src/components/Sidebar.tsx`: adds `useCanStartInAny` to its existing `access.ts` import and calls it over `projects`; the header's `newThreadDisabled` reads it, where it read `projects.length === 0`. + - `apps/web/src/components/LegacySidebar.tsx`: imports `useCanStartInAny` and `readCanStartThreadIn`. `SidebarProjectItem` calls `useCanStartInAny(project.memberProjects)`, and the row's hover New thread button's positioning `
` takes `hidden` when no checkout in the group can take a thread, as the rows hide the actions a connection lacks. In `handleCreateThreadClick`'s checkout chooser, and in the thread menu's "New thread on ", an item is `disabled` by `readCanStartThreadIn`, as the menu disables Rename. The newer sidebar's and the thread view's menus get "New thread on " from case 71's `withSharingMenuItems` (`sharingMenu.ts`), with no further upstream edit. + - `apps/web/src/components/CommandPalette.tsx`: imports `useCanAddProject`, `useCanStartIn` and `startableProjectPicker`, and calls the last two after `contextualProjectRef`. "New thread in…" lists `startPicker.projects` in place of `pickerProjects` and reads its groups from `startPicker.groupByTargetKey` (search terms and the click's checkout), and it is left out when it lists nothing; "New thread in " is offered only when the contextual project can take a thread. `canCreateProject` and `canCreateClonedProject` read `useCanAddProject`, which holds upstream's "Operate tasks" too, in place of `useEnvironmentScope(…, AuthOrchestrationOperateScope)`, so the browse and clone submits are disabled with upstream's "This connection cannot add projects." The New project flow's `canSubmitNewProject`, which upstream gates on no permission, also requires `canCreateProject`, and its Create tooltip says the same. + - `apps/web/src/lib/chatThreadActions.ts`: imports `readCanStartThreadIn`; `startNewThreadFromContext` also returns `false` when it refuses the context's project, so the `chat.new` and `chat.newLocal` keybindings and the sidebar's Shift+click do nothing there, as upstream's keybindings do for a permission the connection lacks. + - `apps/web/src/hooks/useScratchProject.ts`: imports and calls `useCanStartIn`; `scratchEnvironmentId` offers a server only where a project can be added, so "New thread without a project", its keybinding and the other scratch doors leave out a server that refuses `projects.openScratch` to a narrowed session. + - `apps/web/src/components/chat/MessagesTimeline.tsx`: imports `useCanForkThread`; `AssistantForkButton` calls it beside `canForkProjectedAssistantItem` and returns `null` on either, as it did on the one. + - `apps/web/src/components/BranchToolbarBranchSelector.tsx`: imports `useCanOperateThread`; `canOperateThread`, which gates only the branch change, is `useCanOperateThread(environmentId, threadId)` in place of upstream's server-wide "Operate tasks". + - `apps/web/src/components/GitActionsControl.tsx`: imports `useCanOperateThread` and adds `canOperateThisThread` beside upstream's `canOperateThread`; `canChangeThreadBranch` ("Commit on new branch" and "Check out feature branch & continue") reads it in place of `canOperateThread`. Upstream's `canOperateThread` still gates the commit dialog's Open in editor buttons. `GitActionsControl.test.ts` and `GitActionsControl.lifecycle.test.ts` mock the J5 hook as that permission (one `vi.mock` each). + + Folder actions (commit, push, pull, Open in editor) are left to upstream's permissions: the server allows them to anyone who holds Collaborator at any scope (case 69, Jackson 2026-10-17), and a Viewer everywhere does not hold them. Mobile is not covered, with the rest of sharing on mobile ([#609](https://github.com/Jacksondr5/j5code/issues/609)). Proof: `packages/client-runtime/src/j5/sharing.test.ts`, "what a connection may start"; `apps/web/src/j5/sharing/sharingMenu.test.ts`, "a new thread from the thread menu"; and `apps/web/src/j5/sharing/startableProjects.test.ts`. On a pin advance: if upstream adds a door to a new thread, a fork or a project, add the call beside it; if upstream starts gating a new thread on its own permission, keep J5's call beside upstream's; if upstream renames `newThreadDisabled`, `handleCreateThreadClick`, `startNewThreadFromContext`, `scratchEnvironmentId`, `canCreateProject`, `canSubmitNewProject`, `canChangeThreadBranch` or `AssistantForkButton`, or changes how `buildSidebarProjectPickerEntries` picks a group's checkout, move the call with it. ## Pin and upstream advance runbook diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index e8f12473f1516..3eb9c11e18df7 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -3,6 +3,7 @@ import { useHighlightsPaletteItems } from "../j5/highlights/highlightsPalette"; import { useSharingPaletteItems } from "../j5/sharing/sharingPalette"; import { useCanAddProject, useCanStartIn } from "../j5/sharing/access"; +import { startableProjectPicker } from "../j5/sharing/startableProjects"; import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; @@ -916,6 +917,11 @@ function OpenCommandPaletteDialog(props: { handleNewThread, }); const canStartIn = useCanStartIn(); + const startPicker = startableProjectPicker({ + groups: projectGroups, + preferredProjectRef: contextualProjectRef, + canStartIn, + }); const projectPickerEntries = buildSidebarProjectPickerEntries({ groups: projectGroups, preferredProjectRef: contextualProjectRef, @@ -1198,12 +1204,10 @@ function OpenCommandPaletteDialog(props: { isScratchProject(project, scratchWorkspaceRootFor(project.environmentId)); const projectItems = enumerateCommandPaletteItems( buildProjectActionItems({ - projects: pickerProjects.filter( - (project) => !isScratch(project) && canStartIn(project.environmentId, project.id), - ), + projects: startPicker.projects.filter((project) => !isScratch(project)), valuePrefix: "new-thread-in", searchTerms: (project) => { - const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`); + const group = startPicker.groupByTargetKey.get(`${project.environmentId}:${project.id}`); const location = projectEnvironmentLocationById.get(project.environmentId); return [ ...(group?.memberProjects.flatMap((member) => [member.title, member.workspaceRoot]) ?? @@ -1236,7 +1240,7 @@ function OpenCommandPaletteDialog(props: { }, icon: projectFaviconIcon, runProject: async (project) => { - const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`); + const group = startPicker.groupByTargetKey.get(`${project.environmentId}:${project.id}`); const contextualRefBelongsToGroup = contextualProjectRef !== null && group?.memberProjectRefs.some( @@ -2403,6 +2407,7 @@ function OpenCommandPaletteDialog(props: { newProjectFlow !== null && newProjectName.length > 0 && !isCreatingNewProject && + canCreateProject && canCreateProjectInEnvironment(browseEnvironment?.connection.phase); async function submitNewProject(): Promise { @@ -3237,7 +3242,11 @@ function OpenCommandPaletteDialog(props: { {createShortcutLabel} - {`Create (${createShortcutLabel})`} + + {canCreateProject + ? `Create (${createShortcutLabel})` + : "This connection cannot add projects."} + ) : addProjectCloneFlow?.step === "repository" ? ( diff --git a/apps/web/src/components/GitActionsControl.tsx b/apps/web/src/components/GitActionsControl.tsx index 65a75f423cf66..d6a46f79421c3 100644 --- a/apps/web/src/components/GitActionsControl.tsx +++ b/apps/web/src/components/GitActionsControl.tsx @@ -1004,7 +1004,8 @@ export default function GitActionsControl({ activeEnvironmentId, AuthSourceControlWriteScope, ); - const canOperateThread = useCanOperateThread( + const canOperateThread = useEnvironmentScope(activeEnvironmentId, AuthOrchestrationOperateScope); + const canOperateThisThread = useCanOperateThread( activeEnvironmentId, activeThreadRef?.threadId ?? null, ); @@ -1032,7 +1033,8 @@ export default function GitActionsControl({ const activeServerThread = activeServerThreadShell ?? activeServerThreadProjection?.projection.thread ?? null; const isLocalDraftThread = activeDraftThread !== null && activeServerThread === null; - const canChangeThreadBranch = canWriteSourceControl && (isLocalDraftThread || canOperateThread); + const canChangeThreadBranch = + canWriteSourceControl && (isLocalDraftThread || canOperateThisThread); const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext); const [isCommitDialogOpen, setIsCommitDialogOpen] = useState(false); const [dialogCommitMessage, setDialogCommitMessage] = useState(""); diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx index 65a05960841c4..260b41af0bbfb 100644 --- a/apps/web/src/components/LegacySidebar.tsx +++ b/apps/web/src/components/LegacySidebar.tsx @@ -127,7 +127,7 @@ import { useDesktopUpdateState } from "../state/desktopUpdate"; import { useThreadActions } from "../hooks/useThreadActions"; import { archiveWithPreflight } from "../j5/a2a/archiveFlow"; -import { useCanStartIn } from "../j5/sharing/access"; +import { useCanStartInAny } from "../j5/sharing/access"; import { readCanStartThreadIn } from "../j5/sharing/threadOperability"; import { projectEnvironment } from "../state/projects"; import { threadEnvironment, useEnvironmentThread } from "../state/threads"; @@ -1176,7 +1176,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec isManualProjectSorting, dragHandleProps, } = props; - const canStartIn = useCanStartIn(); + const canStartThreadHere = useCanStartInAny(project.memberProjects); const environmentMachine = project.allRemoteMembersAreWsl ? "linux" : project.allRemoteMembersAreDesktopLocal @@ -2114,6 +2114,7 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec project.memberProjects.map((member) => ({ id: member.physicalProjectKey, label: formatProjectMemberActionLabel(member, project.groupedProjectCount), + disabled: !readCanStartThreadIn(scopeProjectRef(member.environmentId, member.id)), })), { x: event.clientX, @@ -2539,28 +2540,29 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec )} - {project.memberProjects.some((member) => canStartIn(member.environmentId, member.id)) ? ( - - - -
- } - /> - - {newThreadShortcutLabel ? `New thread (${newThreadShortcutLabel})` : "New thread"} - - - ) : null} + + s.clearSelection); const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor); const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread); @@ -4646,9 +4646,7 @@ export default function Sidebar() { } onNewProject={openAddProjectCommandPalette} onNewThread={handleNewThreadClick} - newThreadDisabled={ - !projects.some((project) => canStartIn(project.environmentId, project.id)) - } + newThreadDisabled={!canStartInAnyProject} newThreadShortcutLabel={newThreadShortcutLabel} newThreadInProjectShortcutLabel={newThreadInProjectShortcutLabel} showNewThreadInProjectHint={projectGroups.length > 1} diff --git a/apps/web/src/j5/sharing/access.ts b/apps/web/src/j5/sharing/access.ts index 6b113c4fbddd8..bd06907f9703b 100644 --- a/apps/web/src/j5/sharing/access.ts +++ b/apps/web/src/j5/sharing/access.ts @@ -18,6 +18,7 @@ import { import { levelReaches, type PersonLevel } from "@t3tools/contracts/j5"; import * as Option from "effect/Option"; import { AsyncResult, Atom } from "effect/reactivity"; +import { useCallback } from "react"; import { useComposerDraftStore } from "../../composerDraftStore"; import { environmentCatalog } from "../../connection/catalog"; @@ -132,14 +133,30 @@ export function useCanStartIn(): ( return useAtomValue(startsAtom); } +/** + * Whether this connection may start a thread in at least one of these projects. A row or a button + * that needs the one answer asks this, so it renders again only when that answer changes, not on + * every server's access refresh. + */ +export function useCanStartInAny( + projects: ReadonlyArray<{ readonly environmentId: EnvironmentId; readonly id: ProjectId }>, +): boolean { + const select = useCallback( + (starts: (environmentId: EnvironmentId, projectId: ProjectId | null) => boolean) => + projects.some((project) => starts(project.environmentId, project.id)), + [projects], + ); + return useAtomValue(startsAtom, select); +} + /** * Whether this connection may add a project to the server: upstream's server-wide "Operate tasks", * which upstream's Add project flow asks, and a Collaborator's or Owner's level at server scope. */ export function useCanAddProject(environmentId: EnvironmentId | null): boolean { const permitted = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope); - const starts = useCanStartIn(); - return permitted && environmentId !== null && starts(environmentId, null); + const access = useConnectionAccess(environmentId); + return permitted && environmentId !== null && sharingAllowsStart(access, null); } /** @@ -151,12 +168,12 @@ export function useCanForkThread( environmentId: EnvironmentId | null, threadId: ThreadId | null, ): boolean { - const starts = useCanStartIn(); + const access = useConnectionAccess(environmentId); const projectId = useThreadShell( environmentId === null || threadId === null ? null : scopeThreadRef(environmentId, threadId), )?.projectId ?? null; - return environmentId !== null && starts(environmentId, projectId); + return environmentId !== null && sharingAllowsStart(access, projectId); } // Upstream's thread action menu asks through `threadOperability.ts` and `sharingMenu.ts`, which diff --git a/apps/web/src/j5/sharing/startableProjects.test.ts b/apps/web/src/j5/sharing/startableProjects.test.ts new file mode 100644 index 0000000000000..7f8a6dd44922b --- /dev/null +++ b/apps/web/src/j5/sharing/startableProjects.test.ts @@ -0,0 +1,83 @@ +import { EnvironmentId, ProjectId, ProviderInstanceId } from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping"; +import type { Project } from "../../types"; +import { startableProjectPicker } from "./startableProjects"; + +const LOCAL = EnvironmentId.make("env-local"); +const REMOTE = EnvironmentId.make("env-remote"); +const repositoryIdentity = { + canonicalKey: "github.com/example/shared-repo", + locator: { + source: "git-remote" as const, + remoteName: "origin", + remoteUrl: "https://github.com/example/shared-repo.git", + }, +}; + +const project = (environmentId: EnvironmentId, id: string, title = "shared-repo"): Project => ({ + id: ProjectId.make(id), + environmentId, + title, + workspaceRoot: `/tmp/${id}`, + repositoryIdentity: title === "shared-repo" ? repositoryIdentity : null, + defaultModelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5-codex" }, + createdAt: "2026-01-01T00:00:00.000Z", + updatedAt: "2026-01-01T00:00:00.000Z", + scripts: [], +}); + +// One repository checked out on both servers, shown as one group whose representative is local. +const groups = buildSidebarProjectSnapshots({ + projects: [project(LOCAL, "shared-local"), project(REMOTE, "shared-remote")], + settings: { sidebarProjectGroupingMode: "repository", sidebarProjectGroupingOverrides: {} }, + primaryEnvironmentId: LOCAL, + resolveEnvironmentLabel: () => null, +}); + +const startsOnlyIn = + (...ids: string[]) => + (_environmentId: EnvironmentId, projectId: ProjectId) => + ids.includes(projectId); + +describe("the projects offered a new thread", () => { + it("offers a group by a checkout that can take a thread when its usual one cannot", () => { + const picker = startableProjectPicker({ + groups, + preferredProjectRef: null, + canStartIn: startsOnlyIn("shared-remote"), + }); + expect(picker.projects.map((entry) => entry.id)).toEqual(["shared-remote"]); + expect(picker.projects[0]?.displayName).toBe(groups[0]?.displayName); + }); + + it("keeps a click in the group from falling back to a checkout that cannot take a thread", () => { + const picker = startableProjectPicker({ + groups, + preferredProjectRef: { environmentId: LOCAL, projectId: ProjectId.make("shared-local") }, + canStartIn: startsOnlyIn("shared-remote"), + }); + const group = picker.groupByTargetKey.get(`${REMOTE}:shared-remote`); + expect(group?.memberProjectRefs).toEqual([ + { environmentId: REMOTE, projectId: "shared-remote" }, + ]); + }); + + it("leaves out a group none of whose checkouts can take a thread", () => { + expect( + startableProjectPicker({ groups, preferredProjectRef: null, canStartIn: startsOnlyIn() }) + .projects, + ).toEqual([]); + }); + + it("leaves a group upstream's when every checkout can take a thread", () => { + const picker = startableProjectPicker({ + groups, + preferredProjectRef: { environmentId: REMOTE, projectId: ProjectId.make("shared-remote") }, + canStartIn: startsOnlyIn("shared-local", "shared-remote"), + }); + expect(picker.projects.map((entry) => entry.id)).toEqual(["shared-remote"]); + expect(picker.groupByTargetKey.get(`${REMOTE}:shared-remote`)).toBe(groups[0]); + }); +}); diff --git a/apps/web/src/j5/sharing/startableProjects.ts b/apps/web/src/j5/sharing/startableProjects.ts new file mode 100644 index 0000000000000..f1daa73c8d247 --- /dev/null +++ b/apps/web/src/j5/sharing/startableProjects.ts @@ -0,0 +1,53 @@ +import type { EnvironmentId, ProjectId, ScopedProjectRef } from "@t3tools/contracts"; + +import { + buildSidebarProjectPickerEntries, + type SidebarProjectGroupMember, + type SidebarProjectSnapshot, +} from "../../sidebarProjectGrouping"; + +/** + * Upstream's project picker for a new thread, narrowed to the checkouts the person may start a + * thread in. A group keeps only those checkouts, so its chosen one, and the one a click in it + * falls back to, is one that can take a thread; a group with none is left out. + */ +export function startableProjectPicker(input: { + readonly groups: ReadonlyArray; + readonly preferredProjectRef: ScopedProjectRef | null; + readonly canStartIn: (environmentId: EnvironmentId, projectId: ProjectId) => boolean; +}) { + const groups = input.groups.flatMap((group): SidebarProjectSnapshot[] => { + const memberProjects = group.memberProjects.filter((member) => + input.canStartIn(member.environmentId, member.id), + ); + if (memberProjects.length === 0) return []; + if (memberProjects.length === group.memberProjects.length) return [group]; + return [ + { + ...group, + memberProjects, + memberProjectRefs: group.memberProjectRefs.filter((ref) => + input.canStartIn(ref.environmentId, ref.projectId), + ), + }, + ]; + }); + const entries = buildSidebarProjectPickerEntries({ + groups, + preferredProjectRef: input.preferredProjectRef, + }); + return { + projects: entries.map( + ({ group, targetProject }): SidebarProjectGroupMember & { displayName: string } => ({ + ...targetProject, + displayName: group.displayName, + }), + ), + groupByTargetKey: new Map( + entries.map(({ group, targetProject }) => [ + `${targetProject.environmentId}:${targetProject.id}`, + group, + ]), + ), + }; +} diff --git a/docs/j5/product/upstream.md b/docs/j5/product/upstream.md index 5760ab3c07c5b..ed9333c256813 100644 --- a/docs/j5/product/upstream.md +++ b/docs/j5/product/upstream.md @@ -385,7 +385,7 @@ Each advance checks for new upstream reads of `T3CODE_HOME` or `.t3` paths and n - feeds that carry many threads are filtered where they are produced; - the configuration, the lifecycle welcome and the sidebar are given in a reduced form that names nothing of the host; - requests keyed by a folder the client names are refused to a Viewer; - - upstream's doors to a new thread, a fork and a new project, and a thread's branch controls, are offered only where the person's level lets them start or write; upstream offers them to every connection, a read-only one included; + - a new thread or a fork is offered only where the person may start a thread in the project, a new project only to a level at server scope, and a change to a thread's branch only to someone who may write to the thread; upstream offers new-thread and fork drafts to every connection, a read-only one included, and decides the other two by a permission the device holds at its person's highest level anywhere; - for now a Viewer is listed a thread's preview tabs and does not watch them, since upstream's preview events cover the whole server ([#540](https://github.com/Jacksondr5/j5code/issues/540)). - **A link is J5's own token**, on a route that takes no sign-in. When it is used, it mints one of upstream's single-use pairing links for that device. It lasts as long as the Owner chose, from an hour to thirty days. A device already paired as one person that opens a link for another is refused before upstream exchanges it, since upstream would replace that browser's session. - **Upstream's own pairing** pairs a device for a person: the startup link, the desktop app and T3 Connect for the first owner, a Connections link for the person whose device made it, and the CLI as divergence D36 says. From 68ed60ecdb83a72fe9b63bd6ff447337fff2f948 Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Mon, 26 Oct 2026 00:32:18 -0400 Subject: [PATCH 4/5] fix(web): New thread and project search start only where the person can A plain New thread click whose open project refuses a thread starts it in a checkout of the group the person can start in. A project picked from search with no thread creates its draft in a startable checkout, and is listed disabled when it has none. The start read moves to an import-free module so upstream's new-thread helpers no longer load the connection runtime. Co-Authored-By: Claude Opus 5.5 --- FORK.md | 12 ++-- apps/web/src/components/CommandPalette.tsx | 27 +++++++- apps/web/src/components/LegacySidebar.tsx | 2 +- apps/web/src/components/Sidebar.tsx | 5 ++ apps/web/src/j5/sharing/access.ts | 3 +- apps/web/src/j5/sharing/startAccess.ts | 22 +++++++ .../src/j5/sharing/startableProjects.test.ts | 65 ++++++++++++++++++- apps/web/src/j5/sharing/startableProjects.ts | 55 ++++++++++++++++ apps/web/src/j5/sharing/threadOperability.ts | 27 +------- apps/web/src/lib/chatThreadActions.ts | 2 +- 10 files changed, 182 insertions(+), 38 deletions(-) create mode 100644 apps/web/src/j5/sharing/startAccess.ts diff --git a/FORK.md b/FORK.md index 237e814f8f361..4c6fe668df85e 100644 --- a/FORK.md +++ b/FORK.md @@ -451,18 +451,18 @@ migrations after upstream migrations. 84. An agent's steer waits for a Claude turn's running tool calls (register D4, Bryant 2026-10-22). Upstream's `steerTurn` in `apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts` offers every steer with SDK priority `"now"`, which cancels running tool calls. J5-owned leaf `apps/server/src/j5/a2a/claudeAgentSteers.ts` sends a steer that isn't a person's with `"next"` instead: Claude Code lets the tool calls finish and adds the message at the next tool result. A person's steer keeps `"now"` and upstream's capability flags. A late steer can still be queued at the first result, so the leaf follows its `command_lifecycle` frames and holds a clean completion until the turn consuming the steer returns its result. Folded commands share that result. Failed results are never held; upstream handles a person's aborting steer itself. A CLI that reports no lifecycle frames never holds a turn, and a later native turn follows upstream's wake-turn path. Tracking uses a `Map` by provider turn and a `WeakSet` of queries reporting lifecycle. `SilenceDetector` releases tracked steers when a run ends without a clean SDK result, before its membership gate. It sends no unread-after-Stop notice; that design is deferred to #694. The adapter carries four hooks: the leaf import; `j5ObserveClaudeSteer` at the top of `handleSdkMessage`; `j5ClaudeSteerHoldsResult` beside upstream's `isClaudeActiveSteeringAbortResult` in the steered-result branch, where held usage joins `steeredSegmentUsage`; and `j5ClaudeSteerFields` plus `j5OfferClaudeSteer` around the offer in `steerTurn`. J5 delivery's `peerSteeringRun` selects running Claude turns by driver (case 26). Tests: `j5/a2a/claudeAgentSteers.test.ts` covers priority, lifecycle tracking, failed offers and cleanup; `j5/a2a/claudeAgentSteers.integration.test.ts` exercises the real adapter and orchestrator with a scripted SDK stream for mid-tool delivery, a late steer sharing one billed provider turn, Stop while held, and a person's `"now"` steer; `j5/a2a/SilenceDetector.test.ts` checks terminal cleanup without an unread notice. The hold relies on the `@internal` `command_lifecycle` contract of the user's own, unpinned `claude` binary (`provider/Drivers/ClaudeExecutable.ts`), not just the SDK version. For a fresh uuid user message, the assumptions are that the CLI emits `queued`, then consumption or cancellation frames, and a result for the consuming turn; J5 and upstream do not withdraw that queued message, and Stop closes the query. Check those assumptions at Claude Code upgrades as well as upstream advances, including cancellation sources and the four hooks. A steer racing Stop can still run a tool before the process closes (retired D5). Retire this case when upstream delivers agent steers without cancelling tools. If upstream #21158 lands, check that its capability guard does not turn J5's Claude peer steers back into queued turns. -85. Upstream's doors to a new thread, a fork and a new project follow the person's level, as do a thread's branch controls ([#640](https://github.com/Jacksondr5/j5code/issues/640), [#641](https://github.com/Jacksondr5/j5code/issues/641), register D33, Jackson's 2026-10-25 approval of one J5 check beside each upstream check). Upstream offers a new thread or a fork to every connection, a read-only one included, as local navigation (`threadActionRequiresOperate` leaves "New thread on " to it), and decides Add project and branch changes by server-wide permissions, which a device holds at its person's highest level anywhere (case 70). So a Viewer, a Viewer of one thread who writes to another, and a Collaborator on one thread were offered doors the server refuses: a thread or a fork needs the project, and a project needs a level at server scope (case 78's `NARROWED_COMMAND_SCOPES`). The rule is J5-owned `sharingAllowsStart` in `packages/client-runtime/src/j5/sharing.ts`: a thread or a fork takes the project's level (`projectLevelFor`), a project of its own a level at server scope, and a level on one thread starts nothing. The web reads it in `apps/web/src/j5/sharing/access.ts` through `useCanStartIn` (one function over every project, for lists), `useCanStartInAny` (one boolean for a row or a button, which renders again only when that answer changes), `useCanAddProject` and `useCanForkThread`; outside a render through `readCanStartThreadIn` in `threadOperability.ts`; and, for the palette's grouped projects, through `startableProjectPicker` in `startableProjects.ts`, which keeps only a group's checkouts that can take a thread before upstream's `buildSidebarProjectPickerEntries` picks one. A server that has not answered withholds nothing. Each control is hidden or disabled as that surface already does for what a connection lacks: +85. Upstream's doors to a new thread, a fork and a new project follow the person's level, as do a thread's branch controls ([#640](https://github.com/Jacksondr5/j5code/issues/640), [#641](https://github.com/Jacksondr5/j5code/issues/641), register D33, Jackson's 2026-10-25 approval of one J5 check beside each upstream check). Upstream offers a new thread or a fork to every connection, a read-only one included, as local navigation (`threadActionRequiresOperate` leaves "New thread on " to it), and decides Add project and branch changes by server-wide permissions, which a device holds at its person's highest level anywhere (case 70). So a Viewer, a Viewer of one thread who writes to another, and a Collaborator on one thread were offered doors the server refuses: a thread or a fork needs the project, and a project needs a level at server scope (case 78's `NARROWED_COMMAND_SCOPES`). The rule is J5-owned `sharingAllowsStart` in `packages/client-runtime/src/j5/sharing.ts`: a thread or a fork takes the project's level (`projectLevelFor`), a project of its own a level at server scope, and a level on one thread starts nothing. The web reads it in `apps/web/src/j5/sharing/access.ts` through `useCanStartIn` (one function over every project, for lists), `useCanStartInAny` (one boolean for a row or a button, which renders again only when that answer changes), `useCanAddProject` and `useCanForkThread`; outside a render through `readCanStartThreadIn` in `startAccess.ts`, which imports nothing at runtime so upstream's new-thread helpers can load it without the connection runtime; and, for grouped projects, through `startableProjects.ts`: `startableProjectPicker` keeps only a group's checkouts that can take a thread before upstream's `buildSidebarProjectPickerEntries` picks one, `readStartableProjectRef` reads its first pick at click time, and `startableMemberRef` and `openableFromSearch` answer for a project picked from search. A server that has not answered withholds nothing. Each control is hidden or disabled as that surface already does for what a connection lacks: - - `apps/web/src/components/Sidebar.tsx`: adds `useCanStartInAny` to its existing `access.ts` import and calls it over `projects`; the header's `newThreadDisabled` reads it, where it read `projects.length === 0`. - - `apps/web/src/components/LegacySidebar.tsx`: imports `useCanStartInAny` and `readCanStartThreadIn`. `SidebarProjectItem` calls `useCanStartInAny(project.memberProjects)`, and the row's hover New thread button's positioning `
` takes `hidden` when no checkout in the group can take a thread, as the rows hide the actions a connection lacks. In `handleCreateThreadClick`'s checkout chooser, and in the thread menu's "New thread on ", an item is `disabled` by `readCanStartThreadIn`, as the menu disables Rename. The newer sidebar's and the thread view's menus get "New thread on " from case 71's `withSharingMenuItems` (`sharingMenu.ts`), with no further upstream edit. - - `apps/web/src/components/CommandPalette.tsx`: imports `useCanAddProject`, `useCanStartIn` and `startableProjectPicker`, and calls the last two after `contextualProjectRef`. "New thread in…" lists `startPicker.projects` in place of `pickerProjects` and reads its groups from `startPicker.groupByTargetKey` (search terms and the click's checkout), and it is left out when it lists nothing; "New thread in " is offered only when the contextual project can take a thread. `canCreateProject` and `canCreateClonedProject` read `useCanAddProject`, which holds upstream's "Operate tasks" too, in place of `useEnvironmentScope(…, AuthOrchestrationOperateScope)`, so the browse and clone submits are disabled with upstream's "This connection cannot add projects." The New project flow's `canSubmitNewProject`, which upstream gates on no permission, also requires `canCreateProject`, and its Create tooltip says the same. - - `apps/web/src/lib/chatThreadActions.ts`: imports `readCanStartThreadIn`; `startNewThreadFromContext` also returns `false` when it refuses the context's project, so the `chat.new` and `chat.newLocal` keybindings and the sidebar's Shift+click do nothing there, as upstream's keybindings do for a permission the connection lacks. + - `apps/web/src/components/Sidebar.tsx`: adds `useCanStartInAny` to its existing `access.ts` import and calls it over `projects`; the header's `newThreadDisabled` reads it, where it read `projects.length === 0`. It imports `readStartableProjectRef`: when `handleNewThreadClick`'s single-group shortcut is refused by `startNewThreadFromContext`, a click without Shift starts the thread in the checkout `readStartableProjectRef(projectGroups)` returns (the filtered picker's first), so a group mixing a checkout the person cannot start in with one they can does not leave the enabled button doing nothing; Shift+click keeps upstream's contextual project. + - `apps/web/src/components/LegacySidebar.tsx`: imports `useCanStartInAny`, and `readCanStartThreadIn` from `startAccess.ts`. `SidebarProjectItem` calls `useCanStartInAny(project.memberProjects)`, and the row's hover New thread button's positioning `
` takes `hidden` when no checkout in the group can take a thread, as the rows hide the actions a connection lacks. In `handleCreateThreadClick`'s checkout chooser, and in the thread menu's "New thread on ", an item is `disabled` by `readCanStartThreadIn`, as the menu disables Rename. The newer sidebar's and the thread view's menus get "New thread on " from case 71's `withSharingMenuItems` (`sharingMenu.ts`), with no further upstream edit. + - `apps/web/src/components/CommandPalette.tsx`: imports `useCanAddProject`, `useCanStartIn`, `startableProjectPicker`, `startableMemberRef` and `openableFromSearch`, and calls `useCanStartIn` and `startableProjectPicker` after `contextualProjectRef`. "New thread in…" lists `startPicker.projects` in place of `pickerProjects` and reads its groups from `startPicker.groupByTargetKey` (search terms and the click's checkout), and it is left out when it lists nothing; "New thread in " is offered only when the contextual project can take a thread. `canCreateProject` and `canCreateClonedProject` read `useCanAddProject`, which holds upstream's "Operate tasks" too, in place of `useEnvironmentScope(…, AuthOrchestrationOperateScope)`, so the browse and clone submits are disabled with upstream's "This connection cannot add projects." The New project flow's `canSubmitNewProject`, which upstream gates on no permission, also requires `canCreateProject`, and its Create tooltip says the same. A project picked from search still opens its group's latest thread; with none, `openProjectFromSearch` creates its draft in `startableMemberRef`'s checkout (the one picked, else another of its group the person may start in) in place of the picked one, and none when no checkout can take a thread. `projectSearchItems` maps upstream's items through `openableFromSearch` over a set of the projects with an unarchived thread (`searchProjectKeysWithThreads`), so a project with no thread to open and no checkout to start one in is listed `disabled`, as upstream lists a server that is not connected. + - `apps/web/src/lib/chatThreadActions.ts`: imports `readCanStartThreadIn` from `startAccess.ts`; `startNewThreadFromContext` also returns `false` when it refuses the context's project, so the `chat.new` and `chat.newLocal` keybindings and the sidebar's Shift+click do nothing there, as upstream's keybindings do for a permission the connection lacks. - `apps/web/src/hooks/useScratchProject.ts`: imports and calls `useCanStartIn`; `scratchEnvironmentId` offers a server only where a project can be added, so "New thread without a project", its keybinding and the other scratch doors leave out a server that refuses `projects.openScratch` to a narrowed session. - `apps/web/src/components/chat/MessagesTimeline.tsx`: imports `useCanForkThread`; `AssistantForkButton` calls it beside `canForkProjectedAssistantItem` and returns `null` on either, as it did on the one. - `apps/web/src/components/BranchToolbarBranchSelector.tsx`: imports `useCanOperateThread`; `canOperateThread`, which gates only the branch change, is `useCanOperateThread(environmentId, threadId)` in place of upstream's server-wide "Operate tasks". - `apps/web/src/components/GitActionsControl.tsx`: imports `useCanOperateThread` and adds `canOperateThisThread` beside upstream's `canOperateThread`; `canChangeThreadBranch` ("Commit on new branch" and "Check out feature branch & continue") reads it in place of `canOperateThread`. Upstream's `canOperateThread` still gates the commit dialog's Open in editor buttons. `GitActionsControl.test.ts` and `GitActionsControl.lifecycle.test.ts` mock the J5 hook as that permission (one `vi.mock` each). - Folder actions (commit, push, pull, Open in editor) are left to upstream's permissions: the server allows them to anyone who holds Collaborator at any scope (case 69, Jackson 2026-10-17), and a Viewer everywhere does not hold them. Mobile is not covered, with the rest of sharing on mobile ([#609](https://github.com/Jacksondr5/j5code/issues/609)). Proof: `packages/client-runtime/src/j5/sharing.test.ts`, "what a connection may start"; `apps/web/src/j5/sharing/sharingMenu.test.ts`, "a new thread from the thread menu"; and `apps/web/src/j5/sharing/startableProjects.test.ts`. On a pin advance: if upstream adds a door to a new thread, a fork or a project, add the call beside it; if upstream starts gating a new thread on its own permission, keep J5's call beside upstream's; if upstream renames `newThreadDisabled`, `handleCreateThreadClick`, `startNewThreadFromContext`, `scratchEnvironmentId`, `canCreateProject`, `canSubmitNewProject`, `canChangeThreadBranch` or `AssistantForkButton`, or changes how `buildSidebarProjectPickerEntries` picks a group's checkout, move the call with it. + Folder actions (commit, push, pull, Open in editor) are left to upstream's permissions: the server allows them to anyone who holds Collaborator at any scope (case 69, Jackson 2026-10-17), and a Viewer everywhere does not hold them. Mobile is not covered, with the rest of sharing on mobile ([#609](https://github.com/Jacksondr5/j5code/issues/609)). Proof: `packages/client-runtime/src/j5/sharing.test.ts`, "what a connection may start"; `apps/web/src/j5/sharing/sharingMenu.test.ts`, "a new thread from the thread menu"; and `apps/web/src/j5/sharing/startableProjects.test.ts`. On a pin advance: if upstream adds a door to a new thread, a fork or a project, add the call beside it; if upstream starts gating a new thread on its own permission, keep J5's call beside upstream's; if upstream renames `newThreadDisabled`, `handleNewThreadClick`, `handleCreateThreadClick`, `startNewThreadFromContext`, `openProjectFromSearch`, `projectSearchItems`, `scratchEnvironmentId`, `canCreateProject`, `canSubmitNewProject`, `canChangeThreadBranch` or `AssistantForkButton`, or changes how `buildSidebarProjectPickerEntries` picks a group's checkout, move the call with it. ## Pin and upstream advance runbook diff --git a/apps/web/src/components/CommandPalette.tsx b/apps/web/src/components/CommandPalette.tsx index 3eb9c11e18df7..5f2a2535773f0 100644 --- a/apps/web/src/components/CommandPalette.tsx +++ b/apps/web/src/components/CommandPalette.tsx @@ -3,7 +3,11 @@ import { useHighlightsPaletteItems } from "../j5/highlights/highlightsPalette"; import { useSharingPaletteItems } from "../j5/sharing/sharingPalette"; import { useCanAddProject, useCanStartIn } from "../j5/sharing/access"; -import { startableProjectPicker } from "../j5/sharing/startableProjects"; +import { + openableFromSearch, + startableMemberRef, + startableProjectPicker, +} from "../j5/sharing/startableProjects"; import { threadPullRequestLinkMode } from "@t3tools/client-runtime/thread-pull-request-compatibility"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; @@ -1129,6 +1133,11 @@ function OpenCommandPaletteDialog(props: { [browseNavigation], ); + const searchProjectKeysWithThreads = new Set( + threads.flatMap((thread) => + thread.archivedAt === null ? [`${thread.environmentId}:${thread.projectId}`] : [], + ), + ); const openProjectFromSearch = async (project: (typeof projects)[number]) => { const group = projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`); const groupedProjectKeys = group @@ -1160,7 +1169,8 @@ function OpenCommandPaletteDialog(props: { return; } - await handleNewThread(scopeProjectRef(project.environmentId, project.id)); + const startRef = startableMemberRef({ project, group, canStartIn }); + if (startRef) await handleNewThread(startRef); }; const projectSearchItems = buildProjectActionItems({ @@ -1197,6 +1207,19 @@ function OpenCommandPaletteDialog(props: { }, icon: projectFaviconIcon, runProject: openProjectFromSearch, + }).map((item, index) => { + // J5: a project with no thread to open and no checkout this person may start one in is shown + // but cannot be picked, as upstream shows a server that is not connected. + const project = pickerProjects[index]; + const openable = + !project || + openableFromSearch({ + project, + group: projectGroupByTargetKey.get(`${project.environmentId}:${project.id}`), + projectKeysWithThreads: searchProjectKeysWithThreads, + canStartIn, + }); + return openable ? item : { ...item, disabled: true }; }); const projectThreadItems = (() => { diff --git a/apps/web/src/components/LegacySidebar.tsx b/apps/web/src/components/LegacySidebar.tsx index 260b41af0bbfb..0be178730482a 100644 --- a/apps/web/src/components/LegacySidebar.tsx +++ b/apps/web/src/components/LegacySidebar.tsx @@ -128,7 +128,7 @@ import { useDesktopUpdateState } from "../state/desktopUpdate"; import { useThreadActions } from "../hooks/useThreadActions"; import { archiveWithPreflight } from "../j5/a2a/archiveFlow"; import { useCanStartInAny } from "../j5/sharing/access"; -import { readCanStartThreadIn } from "../j5/sharing/threadOperability"; +import { readCanStartThreadIn } from "../j5/sharing/startAccess"; import { projectEnvironment } from "../state/projects"; import { threadEnvironment, useEnvironmentThread } from "../state/threads"; import { useEnvironment, useEnvironments, usePrimaryEnvironmentId } from "../state/environments"; diff --git a/apps/web/src/components/Sidebar.tsx b/apps/web/src/components/Sidebar.tsx index 3ce96b9b5d715..60af2a570e315 100644 --- a/apps/web/src/components/Sidebar.tsx +++ b/apps/web/src/components/Sidebar.tsx @@ -181,6 +181,7 @@ import { EnvironmentMachineIcon } from "./EnvironmentMachineIcon"; import { ProjectEnvironmentBadge } from "./ProjectEnvironmentBadge"; import { useCanStartInAny, useIsNarrowEverywhere } from "../j5/sharing/access"; import { buildWithSharingMenuItems, runSharingMenuAction } from "../j5/sharing/sharingMenu"; +import { readStartableProjectRef } from "../j5/sharing/startableProjects"; import { buildDraftActionMenuItems, buildThreadActionMenuItems, @@ -4498,6 +4499,10 @@ export default function Sidebar() { activeThread: newThreadContext.activeThread ?? undefined, defaultProjectRef: newThreadContext.defaultProjectRef, handleNewThread: newThreadContext.handleNewThread, + }).then((started) => { + // J5: a project this person cannot start in hands a plain click to one they can. + const fallback = started || event?.shiftKey ? null : readStartableProjectRef(projectGroups); + if (fallback) void newThreadContext.handleNewThread(fallback); }); return; } diff --git a/apps/web/src/j5/sharing/access.ts b/apps/web/src/j5/sharing/access.ts index bd06907f9703b..6abfda0d04d1f 100644 --- a/apps/web/src/j5/sharing/access.ts +++ b/apps/web/src/j5/sharing/access.ts @@ -28,7 +28,8 @@ import { useEnvironmentScope } from "../../state/session"; import { j5Sharing } from "../state"; import { ownerSomewhereState } from "./settingsAccess.logic"; import { provideSharingMenuAccess } from "./sharingMenu"; -import { provideSharingStart, provideSharingThreadOperability } from "./threadOperability"; +import { provideSharingStart } from "./startAccess"; +import { provideSharingThreadOperability } from "./threadOperability"; export { j5Sharing }; diff --git a/apps/web/src/j5/sharing/startAccess.ts b/apps/web/src/j5/sharing/startAccess.ts new file mode 100644 index 0000000000000..2111d5c4e152c --- /dev/null +++ b/apps/web/src/j5/sharing/startAccess.ts @@ -0,0 +1,22 @@ +import type { EnvironmentId, ProjectId, ScopedProjectRef } from "@t3tools/contracts"; + +// `useCanStartIn`'s answer for code that runs outside a render, handed over by `access.ts` as +// `threadOperability.ts` is. It imports nothing at runtime, so upstream's new-thread helpers can +// ask it without loading the connection runtime. Upstream offers a new thread to any connection, +// so until then nothing is withheld. +let sharingAllowsStart: ( + environmentId: EnvironmentId, + projectId: ProjectId | null, +) => boolean = () => true; + +/** Called once by `access.ts` with the read behind `useCanStartIn`. */ +export function provideSharingStart( + read: (environmentId: EnvironmentId, projectId: ProjectId | null) => boolean, +) { + sharingAllowsStart = read; +} + +/** `useCanStartIn` for one project, for code that runs outside a render. */ +export function readCanStartThreadIn(project: ScopedProjectRef): boolean { + return sharingAllowsStart(project.environmentId, project.projectId); +} diff --git a/apps/web/src/j5/sharing/startableProjects.test.ts b/apps/web/src/j5/sharing/startableProjects.test.ts index 7f8a6dd44922b..bfb6be17e8158 100644 --- a/apps/web/src/j5/sharing/startableProjects.test.ts +++ b/apps/web/src/j5/sharing/startableProjects.test.ts @@ -3,7 +3,13 @@ import { describe, expect, it } from "vite-plus/test"; import { buildSidebarProjectSnapshots } from "../../sidebarProjectGrouping"; import type { Project } from "../../types"; -import { startableProjectPicker } from "./startableProjects"; +import { + openableFromSearch, + readStartableProjectRef, + startableMemberRef, + startableProjectPicker, +} from "./startableProjects"; +import { provideSharingStart } from "./startAccess"; const LOCAL = EnvironmentId.make("env-local"); const REMOTE = EnvironmentId.make("env-remote"); @@ -81,3 +87,60 @@ describe("the projects offered a new thread", () => { expect(picker.groupByTargetKey.get(`${REMOTE}:shared-remote`)).toBe(groups[0]); }); }); + +describe("a project picked from search", () => { + const picked = { environmentId: LOCAL, id: ProjectId.make("shared-local") }; + + it("starts a new thread in another checkout of its group when the picked one cannot take one", () => { + expect( + startableMemberRef({ + project: picked, + group: groups[0], + canStartIn: startsOnlyIn("shared-remote"), + }), + ).toEqual({ environmentId: REMOTE, projectId: "shared-remote" }); + }); + + it("starts nowhere when no checkout of its group can take a thread", () => { + expect( + startableMemberRef({ project: picked, group: groups[0], canStartIn: startsOnlyIn() }), + ).toBeNull(); + }); + + it("can still be picked to open a thread when no checkout can take a new one", () => { + expect( + openableFromSearch({ + project: picked, + group: groups[0], + projectKeysWithThreads: new Set([`${REMOTE}:shared-remote`]), + canStartIn: startsOnlyIn(), + }), + ).toBe(true); + }); + + it("cannot be picked with no thread to open and no checkout to start one in", () => { + expect( + openableFromSearch({ + project: picked, + group: groups[0], + projectKeysWithThreads: new Set(), + canStartIn: startsOnlyIn(), + }), + ).toBe(false); + }); +}); + +describe("a plain New thread click the open project refuses", () => { + it("goes to a checkout the person can start in", () => { + provideSharingStart((_environmentId, projectId) => projectId === "shared-remote"); + expect(readStartableProjectRef(groups)).toEqual({ + environmentId: REMOTE, + projectId: "shared-remote", + }); + }); + + it("goes nowhere when no checkout can take a thread", () => { + provideSharingStart(() => false); + expect(readStartableProjectRef(groups)).toBeNull(); + }); +}); diff --git a/apps/web/src/j5/sharing/startableProjects.ts b/apps/web/src/j5/sharing/startableProjects.ts index f1daa73c8d247..c86efa64cb3ac 100644 --- a/apps/web/src/j5/sharing/startableProjects.ts +++ b/apps/web/src/j5/sharing/startableProjects.ts @@ -5,6 +5,7 @@ import { type SidebarProjectGroupMember, type SidebarProjectSnapshot, } from "../../sidebarProjectGrouping"; +import { readCanStartThreadIn } from "./startAccess"; /** * Upstream's project picker for a new thread, narrowed to the checkouts the person may start a @@ -51,3 +52,57 @@ export function startableProjectPicker(input: { ), }; } + +/** + * Where a new thread starts when the person picks this project and it has none: the checkout + * picked, or, when that one cannot take a thread, the first of its group that can. `null` when + * none can, so the pick creates no draft the server would refuse. + */ +export function startableMemberRef(input: { + readonly project: { readonly environmentId: EnvironmentId; readonly id: ProjectId }; + readonly group: SidebarProjectSnapshot | undefined; + readonly canStartIn: (environmentId: EnvironmentId, projectId: ProjectId) => boolean; +}): ScopedProjectRef | null { + const picked = { environmentId: input.project.environmentId, projectId: input.project.id }; + return ( + [picked, ...(input.group?.memberProjectRefs ?? [])].find((ref) => + input.canStartIn(ref.environmentId, ref.projectId), + ) ?? null + ); +} + +/** + * Whether picking this project in search does anything: it has a thread to open, or a checkout + * the person may start one in. `projectKeysWithThreads` holds `environmentId:projectId` for each + * project with a thread that is not archived. + */ +export function openableFromSearch(input: { + readonly project: { readonly environmentId: EnvironmentId; readonly id: ProjectId }; + readonly group: SidebarProjectSnapshot | undefined; + readonly projectKeysWithThreads: ReadonlySet; + readonly canStartIn: (environmentId: EnvironmentId, projectId: ProjectId) => boolean; +}): boolean { + const refs = input.group?.memberProjectRefs ?? [ + { environmentId: input.project.environmentId, projectId: input.project.id }, + ]; + return ( + refs.some((ref) => input.projectKeysWithThreads.has(`${ref.environmentId}:${ref.projectId}`)) || + startableMemberRef(input) !== null + ); +} + +/** + * The checkout a plain New thread click starts in when the open project cannot take a thread: + * the one the filtered picker would choose first, read when clicked so the sidebar does not + * render again on every access refresh. + */ +export function readStartableProjectRef( + groups: ReadonlyArray, +): ScopedProjectRef | null { + const target = startableProjectPicker({ + groups, + preferredProjectRef: null, + canStartIn: (environmentId, projectId) => readCanStartThreadIn({ environmentId, projectId }), + }).projects[0]; + return target ? { environmentId: target.environmentId, projectId: target.id } : null; +} diff --git a/apps/web/src/j5/sharing/threadOperability.ts b/apps/web/src/j5/sharing/threadOperability.ts index fcb1f1e49e41d..944170ddedb8f 100644 --- a/apps/web/src/j5/sharing/threadOperability.ts +++ b/apps/web/src/j5/sharing/threadOperability.ts @@ -1,10 +1,4 @@ -import { - AuthOrchestrationOperateScope, - type EnvironmentId, - type ProjectId, - type ScopedProjectRef, - type ScopedThreadRef, -} from "@t3tools/contracts"; +import { AuthOrchestrationOperateScope, type ScopedThreadRef } from "@t3tools/contracts"; import { readEnvironmentScope } from "../../state/session"; @@ -28,22 +22,3 @@ export function readCanOperateThread(thread: ScopedThreadRef): boolean { sharingAllowsOperate(thread) ); } - -// `useCanStartIn`'s answer, handed over by `access.ts` in the same way. Upstream offers a new -// thread to any connection, so until then nothing is withheld. -let sharingAllowsStart: ( - environmentId: EnvironmentId, - projectId: ProjectId | null, -) => boolean = () => true; - -/** Called once by `access.ts` with the read behind `useCanStartIn`. */ -export function provideSharingStart( - read: (environmentId: EnvironmentId, projectId: ProjectId | null) => boolean, -) { - sharingAllowsStart = read; -} - -/** `useCanStartIn` for one project, for code that runs outside a render. */ -export function readCanStartThreadIn(project: ScopedProjectRef): boolean { - return sharingAllowsStart(project.environmentId, project.projectId); -} diff --git a/apps/web/src/lib/chatThreadActions.ts b/apps/web/src/lib/chatThreadActions.ts index 768c7e500af0a..92c8693291deb 100644 --- a/apps/web/src/lib/chatThreadActions.ts +++ b/apps/web/src/lib/chatThreadActions.ts @@ -6,7 +6,7 @@ import type { ScopedProjectRef, } from "@t3tools/contracts"; import type { ComposerThreadDraftState, DraftThreadEnvMode } from "../composerDraftStore"; -import { readCanStartThreadIn } from "../j5/sharing/threadOperability"; +import { readCanStartThreadIn } from "../j5/sharing/startAccess"; type ComposerModelSelectionState = Pick< ComposerThreadDraftState, From 3a73c3f1207cec89ebbc41fccc36a818ff0586fe Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Mon, 26 Oct 2026 00:46:30 -0400 Subject: [PATCH 5/5] fix(web): the thread header's project name doesn't start a thread where the person can't Co-Authored-By: Claude Opus 5.5 --- FORK.md | 3 ++- apps/web/src/components/chat/ChatHeader.tsx | 6 ++++++ apps/web/src/j5/sharing/access.ts | 13 +++++++++++++ 3 files changed, 21 insertions(+), 1 deletion(-) diff --git a/FORK.md b/FORK.md index 4c6fe668df85e..9a461f9af419b 100644 --- a/FORK.md +++ b/FORK.md @@ -459,6 +459,7 @@ migrations after upstream migrations. - `apps/web/src/lib/chatThreadActions.ts`: imports `readCanStartThreadIn` from `startAccess.ts`; `startNewThreadFromContext` also returns `false` when it refuses the context's project, so the `chat.new` and `chat.newLocal` keybindings and the sidebar's Shift+click do nothing there, as upstream's keybindings do for a permission the connection lacks. - `apps/web/src/hooks/useScratchProject.ts`: imports and calls `useCanStartIn`; `scratchEnvironmentId` offers a server only where a project can be added, so "New thread without a project", its keybinding and the other scratch doors leave out a server that refuses `projects.openScratch` to a narrowed session. - `apps/web/src/components/chat/MessagesTimeline.tsx`: imports `useCanForkThread`; `AssistantForkButton` calls it beside `canForkProjectedAssistantItem` and returns `null` on either, as it did on the one. + - `apps/web/src/components/chat/ChatHeader.tsx`: imports `useCanStartThreadIn` and calls it with the active project; the breadcrumb's project-name button, which starts a new thread in that project, is `disabled` when the person can't start one there. - `apps/web/src/components/BranchToolbarBranchSelector.tsx`: imports `useCanOperateThread`; `canOperateThread`, which gates only the branch change, is `useCanOperateThread(environmentId, threadId)` in place of upstream's server-wide "Operate tasks". - `apps/web/src/components/GitActionsControl.tsx`: imports `useCanOperateThread` and adds `canOperateThisThread` beside upstream's `canOperateThread`; `canChangeThreadBranch` ("Commit on new branch" and "Check out feature branch & continue") reads it in place of `canOperateThread`. Upstream's `canOperateThread` still gates the commit dialog's Open in editor buttons. `GitActionsControl.test.ts` and `GitActionsControl.lifecycle.test.ts` mock the J5 hook as that permission (one `vi.mock` each). @@ -821,7 +822,7 @@ explicitly marked. | `apps/web/src/contextMenuFallback.ts` | N | 71 | | `apps/web/src/hooks/useThreadActionMenu.ts` | A | 21, 69, 71 | | `apps/web/src/hooks/useThreadActionMenu.test.ts` | A | 71 | -| `apps/web/src/components/chat/ChatHeader.tsx` | N | 73 | +| `apps/web/src/components/chat/ChatHeader.tsx` | N | 73, 85 | | `apps/web/src/components/chat/ThreadDetailsPanel.tsx` | N | 73 | | `apps/web/src/components/settings/SettingsScopeSentence.tsx` | N | 72 | | `apps/web/src/components/settings/ProjectSettingsPanel.tsx` | N | 72 | diff --git a/apps/web/src/components/chat/ChatHeader.tsx b/apps/web/src/components/chat/ChatHeader.tsx index 9a5b7a9f59341..0f11c0d479551 100644 --- a/apps/web/src/components/chat/ChatHeader.tsx +++ b/apps/web/src/components/chat/ChatHeader.tsx @@ -1,4 +1,5 @@ import { ThreadPeopleChip } from "../../j5/sharing/ThreadPeople"; +import { useCanStartThreadIn } from "../../j5/sharing/access"; import { AuthOrchestrationOperateScope, type EnvironmentId, @@ -83,6 +84,10 @@ export const ChatHeader = memo(function ChatHeader({ }: ChatHeaderProps) { const activeProjectName = activeProject?.title; const activeProjectCwd = activeProject?.workspaceRoot ?? null; + const canStartInProject = useCanStartThreadIn( + activeProject?.environmentId ?? null, + activeProject?.id ?? null, + ); const interfaceFont = useClientSettings((settings) => settings.fontFamilySans); const breadcrumbContainerRef = useRef(null); const [collapseParentTitle, setCollapseParentTitle] = useState(false); @@ -299,6 +304,7 @@ export const ChatHeader = memo(function ChatHeader({ type="button" aria-label={`New thread in ${activeProjectName}`} onClick={onNewThreadInProject} + disabled={!canStartInProject} className="inline-flex min-w-0 max-w-full cursor-pointer items-center gap-1.5 rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring" /> } diff --git a/apps/web/src/j5/sharing/access.ts b/apps/web/src/j5/sharing/access.ts index 6abfda0d04d1f..1f3f874bb167d 100644 --- a/apps/web/src/j5/sharing/access.ts +++ b/apps/web/src/j5/sharing/access.ts @@ -150,6 +150,19 @@ export function useCanStartInAny( return useAtomValue(startsAtom, select); } +/** `useCanStartInAny` for one project: whether this connection may start a thread in it. */ +export function useCanStartThreadIn( + environmentId: EnvironmentId | null, + projectId: ProjectId | null, +): boolean { + const select = useCallback( + (starts: (environmentId: EnvironmentId, projectId: ProjectId | null) => boolean) => + environmentId === null || projectId === null || starts(environmentId, projectId), + [environmentId, projectId], + ); + return useAtomValue(startsAtom, select); +} + /** * Whether this connection may add a project to the server: upstream's server-wide "Operate tasks", * which upstream's Add project flow asks, and a Collaborator's or Owner's level at server scope.