Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions .github/workflows/fork-principals.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ name: Fork principals

on:
pull_request:
branches: [main]
branches: [main, "feat/**"]
workflow_dispatch:

permissions:
Expand Down Expand Up @@ -38,10 +38,16 @@ jobs:
run: node apps/web/node_modules/playwright/cli.js install --with-deps --only-shell chromium

- name: Typecheck
run: vp run --filter @t3tools/contracts --filter t3 typecheck
run: vp run --filter @t3tools/contracts --filter @t3tools/client-runtime --filter @t3tools/web --filter t3 typecheck

- name: Test contracts
run: vp run --filter @t3tools/contracts test

- name: Test server
run: vp run --filter t3 test

- name: Test session-sharing web and client-runtime code
if: ${{ !cancelled() }}
run: |
(cd packages/client-runtime && vp test run src/state/sessionAccess.test.ts)
(cd apps/web && vp test run src/sidebarProjectGrouping.test.ts src/components/chat/ShareThreadDialog.browser.test.tsx)
3 changes: 3 additions & 0 deletions apps/server/src/auth/EnvironmentAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -854,6 +854,9 @@ export const make = Effect.gen(function* () {
...authScopeResponse(session.scopes),
sessionMethod: session.method,
...(session.expiresAt ? { expiresAt: DateTime.toUtc(session.expiresAt) } : {}),
...(principalOfSubject(session.subject) !== DEFAULT_PRINCIPAL_ID
? { principal: principalOfSubject(session.subject) }
: {}),
}) satisfies AuthSessionState,
),
Effect.catchIf(isServerAuthCredentialError, () =>
Expand Down
2 changes: 2 additions & 0 deletions apps/server/src/auth/RpcAuthorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,8 @@ export const RPC_REQUIRED_SCOPES = {
[ORCHESTRATION_V2_WS_METHODS.subscribeThread]: AuthOrchestrationReadScope,
[ORCHESTRATION_V2_WS_METHODS.subscribeCommandOutput]: AuthOrchestrationReadScope,
[WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope,
[WS_METHODS.sessionAccessList]: AuthOrchestrationReadScope,
[WS_METHODS.sessionAccessThreadShares]: AuthOrchestrationReadScope,
[WS_METHODS.serverProbe]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,
[WS_METHODS.serverGetNpmRelease]: AuthOrchestrationReadScope,
Expand Down
7 changes: 6 additions & 1 deletion apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,7 @@ import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../termina
import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions";
import { useEnvironmentQuery } from "../state/query";
import { useEnvironmentScope } from "~/state/session";
import { useThreadAccessRole } from "~/state/sessionAccess";
import {
primaryServerAvailableEditorsAtom,
primaryServerKeybindingsAtom,
Expand Down Expand Up @@ -423,7 +424,11 @@ export default function ChatView(props: ChatViewProps) {
embedded: parentPanel,
} = props;
const embedded = parentPanel !== undefined;
const canOperateThread = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
const hasOperateScope = useEnvironmentScope(environmentId, AuthOrchestrationOperateScope);
const isSessionViewer =
useThreadAccessRole(routeKind === "server" ? scopeThreadRef(environmentId, threadId) : null) ===
"viewer";
const canOperateThread = hasOperateScope && !isSessionViewer;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Apply viewer roles to the mobile composer

When a recipient opens a viewer-shared thread in the mobile app, this role check applies only to web ChatView. Mobile ThreadRouteScreen still derives canOperateThread from the environment scope, which principal sessions have, so ThreadComposer enables Send; the server then rejects the dispatch because viewers may only read. Apply the shared role check on mobile too, so viewers aren't shown an action that always fails.

AGENTS.md reference: AGENTS.md:L69-L73

Useful? React with 👍 / 👎.

const canOperateTerminal = useEnvironmentScope(environmentId, AuthTerminalOperateScope);
const draftId = routeKind === "draft" ? props.draftId : null;
const handleNewThread = useNewThreadHandler();
Expand Down
18 changes: 18 additions & 0 deletions apps/web/src/components/CommandPalette.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,8 @@ import { ProjectFilePicker } from "./files/ProjectFilePicker";
import { openLinkPullRequestDialog } from "./pullRequest/LinkPullRequestDialog";
import { canShareWithGuestAtom } from "./chat/guestShareAvailability";
import { openGuestShareDialog } from "./chat/guestShareDialogState";
import { openShareThreadDialog } from "./chat/shareThreadDialogState";
import { readCanShareThread } from "../state/sessionAccess";
import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
import { settingsForThisPlatform, SETTINGS_SECTION_LABELS } from "./settings/settingsSearch";
import { primaryServerKeybindingsAtom } from "../state/server";
Expand Down Expand Up @@ -1412,6 +1414,22 @@ function OpenCommandPaletteDialog(props: {
});
}

if (activeThread !== null) {
const threadRef = scopeThreadRef(activeThread.environmentId, activeThread.id);
if (readCanShareThread(threadRef, activeThread.source.ownerPrincipal)) {
actionItems.push({
kind: "action",
value: "action:share-thread-with-principal",
searchTerms: ["share", "invite", "viewer", "participant", "session", "group"],
title: "Share…",
icon: <UserPlusIcon className={ITEM_ICON_CLASS} />,
run: async () => {
openShareThreadDialog(threadRef);
},
});
}
}

if (activeThread !== null) {
const thread = activeThread;
actionItems.push({
Expand Down
21 changes: 20 additions & 1 deletion apps/web/src/components/Sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ import {
projectGroupsSpanEnvironments,
resolveSidebarProjectScopeKeys,
getSidebarProjectSettingsKey,
partitionSharedThreads,
type SidebarProjectSnapshot,
} from "../sidebarProjectGrouping";
import { resolveProjectExpanded, useUiStateStore } from "../uiStateStore";
Expand All @@ -128,6 +129,8 @@ import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { useOrderWhileOpen } from "../hooks/useOrderWhileOpen";
import { useProjectPin } from "../hooks/useProjectGroupUpdate";
import { useSidebarProjectGroups } from "../hooks/useSidebarProjectGroups";
import { readCanShareThread, useSharedSidebarInput } from "../state/sessionAccess";
import { SidebarSharedThreads } from "./sidebar/SidebarSharedThreads";
import { useTerminalFocus } from "../hooks/useTerminalFocus";
import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
import { registerSettleAndAdvance } from "../settleAndAdvance";
Expand Down Expand Up @@ -162,6 +165,7 @@ import { readEnvironmentScope, useEnvironmentScope } from "../state/session";
import { appAtomRegistry } from "../rpc/atomRegistry";
import { canShareWithGuestAtom } from "./chat/guestShareAvailability";
import { openGuestShareDialog } from "./chat/guestShareDialogState";
import { openShareThreadDialog } from "./chat/shareThreadDialogState";
import {
buildThreadRouteParams,
resolveActiveThreadRouteRef,
Expand Down Expand Up @@ -1116,7 +1120,11 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
),
),
);
const threads = useQuietThreadShells();
const allThreads = useQuietThreadShells();
const { mine: threads, shared: sharedThreadSections } = partitionSharedThreads({
threads: allThreads,
...useSharedSidebarInput(useEnvironmentIdentities().map(({ environmentId }) => environmentId)),
});
const routeRowThreadKey =
routeThreadRef === null
? null
Expand Down Expand Up @@ -2644,6 +2652,7 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
canShareWithGuest: appAtomRegistry.get(
canShareWithGuestAtom(threadRef.environmentId),
),
canShareSession: readCanShareThread(threadRef, thread.source.ownerPrincipal),
canTurnIntoProject: canTurnThreadIntoProject(threadRef),
supports: {
settlement: configLoaded,
Expand Down Expand Up @@ -2766,6 +2775,9 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
case "rename":
startThreadRename(threadRef, thread.title);
return;
case "share-session":
openShareThreadDialog(threadRef);
return;
case "share-guest":
openGuestShareDialog(threadRef);
return;
Expand Down Expand Up @@ -3638,6 +3650,13 @@ export default function Sidebar({ routeReveal }: { routeReveal: SidebarRouteReve
)}
</div>
) : null}
{!isSearchingThreads ? (
<SidebarSharedThreads
sections={sharedThreadSections}
routeThreadKey={routeRowThreadKey}
onOpenThread={navigateToThread}
/>
) : null}
</SidebarGroup>
</SidebarContent>
<SidebarChromeFooter />
Expand Down
29 changes: 29 additions & 0 deletions apps/web/src/components/auth/PairingRouteSurface.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ import React, { startTransition, useEffect, useEffectEvent, useRef, useState } f
import { connectPairing } from "../../connection/onboarding";
import {
peekPairingTokenFromUrl,
resolvePrimaryEnvironmentHttpUrl,
stripPairingTokenFromUrl,
submitServerAuthCredential,
} from "../../environments/primary";
import { isElectron } from "../../env";
import { readHostedPairingRequest } from "../../hostedPairing";
import { ensureLocalApi } from "../../localApi";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { StandalonePage, StandalonePageHeader } from "../ui/standalone-page";
Expand Down Expand Up @@ -62,6 +65,19 @@ export function PairingRouteSurface({
});
};

const signInWithOidc = async () => {
const url = resolvePrimaryEnvironmentHttpUrl("/auth/oidc/start", {
client: isElectron ? "desktop" : "web",
});
if (!isElectron) {
window.location.assign(url);
return;
}
await ensureLocalApi()
.shell.openExternal(url)
.catch((error) => setErrorMessage(errorMessageFromUnknown(error)));
};

const handleSubmit = async (event?: React.SubmitEvent<HTMLFormElement>) => {
event?.preventDefault();
await submitCredential(credential);
Expand Down Expand Up @@ -89,6 +105,19 @@ export function PairingRouteSurface({
description={describeAuthGate(auth.bootstrapMethods)}
/>

{auth.oidcSignIn ? (
<div className="mt-6 space-y-2">
<Button disabled={isSubmitting} onClick={() => void signInWithOidc()} size="sm">
Sign in with Kanidm
</Button>
<p className="text-xs text-muted-foreground">
{isElectron
? "Opens your browser; the app signs in when you return."
: "Or pair this device with a token below."}
</p>
</div>
) : null}

<form className="mt-6 space-y-4" onSubmit={(event) => void handleSubmit(event)}>
<div className="space-y-2">
<label className="text-sm font-medium" htmlFor="pairing-token">
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/chat/ChatComposer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ import {
} from "./composerContextUndo";
import type { ThreadSyncPhase } from "../../threadSync";
import { ComposerBanner } from "./ComposerBanner";
import { ComposerSessionViewerBanner } from "./ComposerSessionViewerBanner";
import { ComposerSurface } from "./ComposerSurface";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack";
import {
Expand Down Expand Up @@ -3194,6 +3195,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
<ComposerBanner.Dock>
<ComposerBanner.Column>
<ComposerBannerStack items={shelfItems} />
<ComposerSessionViewerBanner threadRef={routeThreadRef} />
{showComposerTopDrawer ? (
<ComposerBanner.Attachment>
<ComposerBanner.Root data-chat-composer-top-drawer="true" variant="info">
Expand Down
27 changes: 27 additions & 0 deletions apps/web/src/components/chat/ComposerSessionViewerBanner.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { ScopedThreadRef } from "@t3tools/contracts";

import { useThreadAccessRole } from "../../state/sessionAccess";
import { ComposerBanner } from "./ComposerBanner";

/** Tells a viewer why the composer is off; its owner must make them a participant to let them send. */
export function ComposerSessionViewerBanner({
threadRef,
}: {
readonly threadRef: ScopedThreadRef | null;
}) {
if (useThreadAccessRole(threadRef) !== "viewer") return null;
return (
<ComposerBanner.Attachment>
<ComposerBanner.Root variant="info">
<ComposerBanner.Row>
<ComposerBanner.Icon />
<ComposerBanner.Content>
<span className="min-w-0 flex-1 text-foreground/85">
You can read this session. Ask its owner for participant access to send messages.
</span>
</ComposerBanner.Content>
</ComposerBanner.Row>
</ComposerBanner.Root>
</ComposerBanner.Attachment>
);
}
59 changes: 59 additions & 0 deletions apps/web/src/components/chat/ShareThreadDialog.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { expect, it, vi } from "vite-plus/test";
import { page, userEvent } from "vite-plus/test/browser";

import { act, render } from "../../../test/render";
import { AppAtomRegistryProvider } from "../../rpc/atomRegistry";

const access = vi.hoisted(() => ({ mutate: vi.fn() }));

vi.mock(import("~/state/sessionAccess"), async (original) => ({
...(await original()),
useSessionAccess: (() => ({ principal: "can", snapshot: null, refresh: vi.fn() })) as never,
useSessionAccessMutation: (() => ({ canMutate: true, mutate: access.mutate })) as never,
}));
vi.mock(import("~/state/query"), async (original) => ({
...(await original()),
useEnvironmentQuery: (() => ({
data: { shares: [{ principal: "dejana", role: "participant" }] },
})) as never,
}));

import { ShareThreadDialogHost } from "./ShareThreadDialog";
import { openShareThreadDialog } from "./shareThreadDialogState";

const environmentId = EnvironmentId.make("env-1");
const threadId = ThreadId.make("thread-1");

it("shares a session with a person and removes an existing share", async () => {
access.mutate.mockReset().mockResolvedValue(true);
// The dialog needs no route.
await using _screen = await render(
<AppAtomRegistryProvider>
<ShareThreadDialogHost />
</AppAtomRegistryProvider>,
{ router: false },
);
await act(async () => openShareThreadDialog({ environmentId, threadId }));

const share = page.getByRole("button", { name: "Share", exact: true });
await userEvent.type(page.getByLabelText("Person"), "Not A Name");
await expect.element(share).toBeDisabled();

await userEvent.clear(page.getByLabelText("Person"));
await userEvent.type(page.getByLabelText("Person"), "kemal");
await userEvent.click(share);
expect(access.mutate).toHaveBeenCalledWith({
type: "thread.share",
threadId,
principal: "kemal",
role: "viewer",
});

await userEvent.click(page.getByRole("button", { name: "Remove dejana" }));
expect(access.mutate).toHaveBeenLastCalledWith({
type: "thread.unshare",
threadId,
principal: "dejana",
});
});
Loading
Loading