Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(teams): team task slugs (#5052)
teo94503936919a
diff --git a/apps/web/src/features/settings/Team.tsx b/apps/web/src/features/settings/Team.tsxindex 7464248f99..bc3d52a78c 100644--- a/apps/web/src/features/settings/Team.tsx+++ b/apps/web/src/features/settings/Team.tsx@@ -1,3 +1,4 @@+import { toast } from '@core/component/Toast/Toast';import { UserIcon } from '@core/component/UserIcon';import { SERVER_HOSTS } from '@core/constant/servers';import { useUserId } from '@core/context/user';@@ -12,6 +13,7 @@ import { Select } from '@kobalte/core/select';import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';import CaretDownIcon from '@phosphor/caret-down.svg';import CheckIcon from '@phosphor/check.svg';+import CopyIcon from '@phosphor/copy.svg';import EnvelopeIcon from '@phosphor/envelope.svg';import LinkIcon from '@phosphor/link.svg';import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';@@ -68,7 +70,11 @@ import {canRemoveTeamMember,isTeamAdminOrOwner,} from './teamMemberPermissions';-import { getTeamSlugError, normalizeTeamSlugInput } from './teamSlug';+import {+ buildTeamTaskAutolinkTargetUrl,+ getTeamSlugError,+ normalizeTeamSlugInput,+} from './teamSlug';const roleOrder: Record<string, number> = {[TeamRole.owner]: 0,@@ -1035,6 +1041,20 @@ function TeamManagement(props: {setTeamSlugError(undefined);};+ const handleCopyGithubAutolinkUrl = async () => {+ const targetUrl = buildTeamTaskAutolinkTargetUrl(+ props.teamSlug,+ getWebOrigin()+ );+ try {+ await navigator.clipboard.writeText(targetUrl);+ toast.success('GitHub autolink URL copied');+ } catch (error) {+ console.error('Failed to copy GitHub autolink URL', error);+ toast.failure('Failed to copy GitHub autolink URL');+ }+ };+const handleDeleteTeam = () => {if (!props.teamId) return;@@ -1232,6 +1252,27 @@ function TeamManagement(props: {</Show></SettingsRow>+ <SettingsRow+ label="GitHub autolink"+ description={+ <>+ Use <code>{props.teamSlug}-</code> as the reference prefix in+ GitHub, then paste this target URL.+ </>+ }+ hideDescriptionOnMobile+ >+ <Button+ variant="base"+ size="sm"+ class="rounded-xs"+ onClick={handleCopyGithubAutolinkUrl}+ >+ <CopyIcon class="size-4" />+ Copy target URL+ </Button>+ </SettingsRow>+<Show when={isAdminOrOwner()}><SettingsRowlabel="Auto-join on domain"diff --git a/apps/web/src/features/settings/teamSlug.test.ts b/apps/web/src/features/settings/teamSlug.test.tsindex 538aaa571b..79e0095664 100644--- a/apps/web/src/features/settings/teamSlug.test.ts+++ b/apps/web/src/features/settings/teamSlug.test.ts@@ -1,6 +1,8 @@import { describe, expect, it } from 'vitest';import {+ buildTeamTaskAutolinkTargetUrl,getTeamSlugError,+ isValidTeamTaskSlug,normalizeTeamSlugInput,TEAM_SLUG_ALLOWED_INPUT_REGEX,TEAM_SLUG_MAX_LENGTH,@@ -73,3 +75,32 @@ describe('team slug validation', function () {);});});++describe('GitHub autolink target URL', function () {+ it('builds the numeric target template for the team slug', function () {+ expect(buildTeamTaskAutolinkTargetUrl('ENG', 'https://macro.com/')).toBe(+ 'https://macro.com/app/task-slug/ENG-<num>'+ );+ });+});++describe('team task slug validation', function () {+ it('accepts slugs the backend parser accepts', function () {+ expect(isValidTeamTaskSlug('ENG-42')).toBe(true);+ expect(isValidTeamTaskSlug('MY_TEAM-1')).toBe(true);+ expect(isValidTeamTaskSlug('A-B-7')).toBe(true);+ });++ it('rejects slugs without a positive task number', function () {+ expect(isValidTeamTaskSlug('ENG')).toBe(false);+ expect(isValidTeamTaskSlug('ENG-')).toBe(false);+ expect(isValidTeamTaskSlug('ENG-0')).toBe(false);+ expect(isValidTeamTaskSlug('ENG-4a')).toBe(false);+ expect(isValidTeamTaskSlug('ENG-9999999999')).toBe(false);+ });++ it('rejects empty prefix segments', function () {+ expect(isValidTeamTaskSlug('-42')).toBe(false);+ expect(isValidTeamTaskSlug('ENG--42')).toBe(false);+ });+});diff --git a/apps/web/src/features/settings/teamSlug.ts b/apps/web/src/features/settings/teamSlug.tsindex 4c9c6697cb..9df1b54dcb 100644--- a/apps/web/src/features/settings/teamSlug.ts+++ b/apps/web/src/features/settings/teamSlug.ts@@ -67,3 +67,32 @@ export function getTeamSlugError(input: string): string | undefined {return undefined;}++/** Builds the target URL template GitHub requires for numeric autolinks. */+export function buildTeamTaskAutolinkTargetUrl(+ teamSlug: string,+ webOrigin: string+): string {+ return `${webOrigin.replace(/\/$/, '')}/app/task-slug/${teamSlug}-<num>`;+}++const TEAM_TASK_NUMBER_REGEX: RegExp = /^\d{1,9}$/;++/**+ * Mirrors the backend team-task slug parser: a `-`-separated prefix with no+ * empty segments and a positive task number (digits capped at 9 to stay+ * inside an i32), so slugs the backend would reject with 400 never leave the+ * client.+ */+export function isValidTeamTaskSlug(slug: string): boolean {+ const separatorIndex = slug.lastIndexOf('-');+ if (separatorIndex === -1) return false;++ const prefix = slug.slice(0, separatorIndex);+ const number = slug.slice(separatorIndex + 1);+ if (prefix === '' || prefix.split('-').some((segment) => segment === '')) {+ return false;+ }++ return TEAM_TASK_NUMBER_REGEX.test(number) && Number(number) > 0;+}diff --git a/apps/web/src/lib/core/context/user.ts b/apps/web/src/lib/core/context/user.tsindex b771ec405a..b697143341 100644--- a/apps/web/src/lib/core/context/user.ts+++ b/apps/web/src/lib/core/context/user.ts@@ -1,4 +1,5 @@import type { PermissionId } from '@core/constant/permissions';+import { thrownResultErrorHasCode } from '@core/util/result';import { type UserInfoData, useUserInfoQuery } from '@queries/auth/user-info';import { queryReadyGate } from '@queries/gate';import { type Accessor, createMemo } from 'solid-js';@@ -34,6 +35,14 @@ export const [UserContextProvider, useUserContext] =const isAuthenticated = createMemo((): boolean | undefined => {if (query.isLoading) return undefined;+ if (query.isError) {+ // Only a 401 proves the user is signed out; a transient failure+ // (network blip, 5xx) leaves the auth state unknown so consumers+ // don't bounce an authenticated user to login.+ return thrownResultErrorHasCode(query.error, 'UNAUTHORIZED')+ ? false+ : undefined;+ }if (!query.data) return false;return query.data.authenticated ?? false;});diff --git a/apps/web/src/lib/core/util/postLoginRedirect.ts b/apps/web/src/lib/core/util/postLoginRedirect.tsnew file mode 100644index 0000000000..7c1a5ddc55--- /dev/null+++ b/apps/web/src/lib/core/util/postLoginRedirect.ts@@ -0,0 +1,15 @@+const POST_LOGIN_REDIRECT_KEY = 'redirectUrl';++/** Preserves a URL for BasePathComponent to restore after authentication. */+export function setPostLoginRedirect(url: string): void {+ sessionStorage.setItem(POST_LOGIN_REDIRECT_KEY, url);+}++/** Reads and clears the URL preserved by {@link setPostLoginRedirect}. */+export function consumePostLoginRedirect(): string | null {+ const url = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY);+ if (url !== null) {+ sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY);+ }+ return url;+}diff --git a/apps/web/src/lib/queries/storage/keys.ts b/apps/web/src/lib/queries/storage/keys.tsindex b205c1eef3..b3a90ae201 100644--- a/apps/web/src/lib/queries/storage/keys.ts+++ b/apps/web/src/lib/queries/storage/keys.ts@@ -87,6 +87,12 @@ export const taskSimilaritySearchKeys = createQueryKeys(});+export const teamTaskKeys = createQueryKeys('teamTask', {+ bySlug: (slug: string) => ({+ queryKey: [slug],+ }),+});+export const instructionsMdKeys = createQueryKeys('instructionsMd', {id: null,text: (id: string) => ({diff --git a/apps/web/src/lib/queries/storage/team-task.ts b/apps/web/src/lib/queries/storage/team-task.tsnew file mode 100644index 0000000000..63de995f0f--- /dev/null+++ b/apps/web/src/lib/queries/storage/team-task.ts@@ -0,0 +1,35 @@+import { throwOnErr } from '@core/util/result';+import { storageServiceClient } from '@service-storage/client';+import { useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { teamTaskKeys } from './keys';++/** Resolves a stable team-task slug to its canonical document. */+export function useTeamTaskQuery(slug: Accessor<string | undefined>) {+ return useQuery(() => {+ const currentSlug = slug();++ return {+ queryKey: currentSlug+ ? teamTaskKeys.bySlug(currentSlug).queryKey+ : teamTaskKeys.bySlug._def,+ queryFn: ({ signal }: { signal: AbortSignal }) => {+ if (!currentSlug) {+ throw new Error('A team-task slug is required');+ }++ // DSS resolves the slug against the authenticated user's team.+ return throwOnErr(() =>+ storageServiceClient.getDocumentByTeamSlug({+ slug: currentSlug,+ signal,+ })+ );+ },+ // Resolution failures are deterministic (404/403), so an automatic+ // retry only delays the not-found state; the route offers manual retry.+ retry: false,+ enabled: !!currentSlug,+ };+ });+}diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex dd9318acc0..186318164c 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -1184,6 +1184,16 @@ export const storageServiceClient = {});},+ async getDocumentByTeamSlug(params: { slug: string; signal?: AbortSignal }) {+ return (+ await dssFetch<{+ data: GetDocumentResponseData;+ }>(`/documents/slug/${encodeURIComponent(params.slug)}`, {+ signal: params.signal,+ })+ ).map((result) => result.data);+ },+async createDocument(request: CreateDocumentRequest) {const result = await fetchWithToken<CreateDocumentResponse,diff --git a/apps/web/src/routes/Root.tsx b/apps/web/src/routes/Root.tsxindex 0380aa9d99..2de44d4bfa 100644--- a/apps/web/src/routes/Root.tsx+++ b/apps/web/src/routes/Root.tsx@@ -61,6 +61,7 @@ import {} from '@core/util/cookies';import { licenseChannel } from '@core/util/licenseUpdateBroadcastChannel';import { isTauri } from '@core/util/platform';+import { consumePostLoginRedirect } from '@core/util/postLoginRedirect';import { thrownResultErrorHasCode } from '@core/util/result';import { transformShortIdInUrlPathname } from '@core/util/url';import { EntityProvider } from '@entity';@@ -117,6 +118,7 @@ import {Suspense,Switch,} from 'solid-js';+import { TaskRoute } from './TaskRoute';/** Syncs login cookie with auth state. Only updates on successful query (not errors/loading). */function useSyncLoginCookie() {@@ -248,9 +250,8 @@ function BasePathComponent() {});// check session storage for redirect url- const redirectUrl = sessionStorage.getItem('redirectUrl');+ const redirectUrl = consumePostLoginRedirect();if (redirectUrl) {- sessionStorage.removeItem('redirectUrl');const relativeUrl = redirectUrl.replace(window.location.origin, '');window.location.href = relativeUrl;return;@@ -342,6 +343,10 @@ function OnboardingRoute() {}const ROUTES: RouteDefinition[] = [+ {+ path: '/task-slug/:taskSlug',+ component: TaskRoute,+ },LAYOUT_ROUTE,/** BEGIN - APP ROUTES */{diff --git a/apps/web/src/routes/TaskRoute.test.tsx b/apps/web/src/routes/TaskRoute.test.tsxnew file mode 100644index 0000000000..fb06afe452--- /dev/null+++ b/apps/web/src/routes/TaskRoute.test.tsx@@ -0,0 +1,215 @@+/**+ * @vitest-environment jsdom+ */++import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import type { JSX } from 'solid-js';+import { render } from 'solid-js/web';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const DOCUMENT_ID = '019f148f-2a38-7f56-8944-ee118e48d27c';++const mocks = vi.hoisted(() => ({+ authenticated: true as boolean | undefined,+ getDocumentByTeamSlug: vi.fn(),+ navigate: vi.fn(),+ taskSlug: 'ENG-42',+}));++vi.mock('@core/auth', () => ({+ useIsAuthenticated: () => () => mocks.authenticated,+}));++vi.mock('@core/component/LoadingBlock', () => ({+ LoadingBlock: () => <div>Loading task…</div>,+}));++vi.mock('@service-storage/client', () => ({+ storageServiceClient: {+ getDocumentByTeamSlug: mocks.getDocumentByTeamSlug,+ },+}));++vi.mock('@solidjs/router', () => ({+ // Mirrors the real Navigate component: a replace navigation on render.+ Navigate: (props: { href: string }) => {+ mocks.navigate(props.href, { replace: true });+ return null;+ },+ useNavigate: () => mocks.navigate,+ useParams: () => ({+ get taskSlug() {+ return mocks.taskSlug;+ },+ }),+}));++vi.mock('@ui', () => ({+ Button: (props: { children: JSX.Element; onClick?: () => void }) => (+ <button onClick={props.onClick}>{props.children}</button>+ ),+}));++import { TaskRoute } from './TaskRoute';++let dispose: (() => void) | undefined;++function renderRoute(): HTMLElement {+ const container = document.createElement('div');+ document.body.appendChild(container);+ // No retry override: the hook itself must disable retries so deterministic+ // resolution failures surface immediately.+ const queryClient = new QueryClient();+ const disposeRender = render(+ () => (+ <QueryClientProvider client={queryClient}>+ <TaskRoute />+ </QueryClientProvider>+ ),+ container+ );+ dispose = () => {+ disposeRender();+ queryClient.clear();+ container.remove();+ };+ return container;+}++beforeEach(() => {+ mocks.authenticated = true;+ mocks.taskSlug = 'ENG-42';+ mocks.navigate.mockReset();+ mocks.getDocumentByTeamSlug.mockReset();+ mocks.getDocumentByTeamSlug.mockResolvedValue(+ ok({ documentMetadata: { documentId: DOCUMENT_ID } })+ );+ sessionStorage.clear();+ window.history.replaceState({}, '', '/app/task-slug/ENG-42');+});++afterEach(() => {+ dispose?.();+ dispose = undefined;+});++describe('TaskRoute', () => {+ it('rejects an invalid task slug without resolving it', async () => {+ mocks.taskSlug = 'ENG-0';++ const container = renderRoute();++ await vi.waitFor(() => {+ expect(container.textContent).toContain('Task not found');+ });+ expect(mocks.getDocumentByTeamSlug).not.toHaveBeenCalled();+ });++ it('resolves a team task slug and replaces it with the canonical task route', async () => {+ renderRoute();++ await vi.waitFor(() => {+ expect(mocks.getDocumentByTeamSlug).toHaveBeenCalledWith({+ slug: 'ENG-42',+ signal: expect.any(AbortSignal),+ });+ expect(mocks.navigate).toHaveBeenCalledWith(`/task/${DOCUMENT_ID}`, {+ replace: true,+ });+ });+ });++ it('preserves the slug route while sending a signed-out user to login', async () => {+ mocks.authenticated = false;++ renderRoute();++ await vi.waitFor(() => {+ expect(mocks.navigate).toHaveBeenCalledWith('/login', { replace: true });+ });+ expect(sessionStorage.getItem('redirectUrl')).toBe(window.location.href);+ expect(mocks.getDocumentByTeamSlug).not.toHaveBeenCalled();+ });++ it('shows a not-found state for an unknown task reference', async () => {+ mocks.getDocumentByTeamSlug.mockResolvedValue(+ err([{ code: 'NOT_FOUND', message: 'Resource not found' }])+ );++ const container = renderRoute();++ await vi.waitFor(() => {+ expect(container.textContent).toContain('Task not found');+ });+ expect(mocks.getDocumentByTeamSlug).toHaveBeenCalledTimes(1);+ expect(mocks.navigate).not.toHaveBeenCalled();+ });++ it('shows the not-found state when the user has no team access', async () => {+ mocks.getDocumentByTeamSlug.mockResolvedValue(+ err([{ code: 'FORBIDDEN', message: 'Forbidden' }])+ );++ const container = renderRoute();++ await vi.waitFor(() => {+ expect(container.textContent).toContain('Task not found');+ });+ expect(container.textContent).not.toContain('Try again');+ });++ it('recovers from a transient error through the retry button', async () => {+ let releaseRefetch = (): void => undefined;+ mocks.getDocumentByTeamSlug+ .mockResolvedValueOnce(+ err([{ code: 'SERVER_ERROR', message: 'Internal server error' }])+ )+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ releaseRefetch = () =>+ resolve(ok({ documentMetadata: { documentId: DOCUMENT_ID } }));+ })+ );++ const container = renderRoute();++ await vi.waitFor(() => {+ expect(container.textContent).toContain('Unable to open task');+ });++ const retryButton = [...container.querySelectorAll('button')].find(+ (button) => button.textContent === 'Try again'+ );+ expect(retryButton).toBeDefined();+ retryButton?.click();++ // While the refetch is in flight the error state yields to the loading+ // state instead of leaving the retry click without feedback.+ await vi.waitFor(() => {+ expect(container.textContent).toContain('Loading task…');+ });++ releaseRefetch();+ await vi.waitFor(() => {+ expect(mocks.navigate).toHaveBeenCalledWith(`/task/${DOCUMENT_ID}`, {+ replace: true,+ });+ });+ });++ it('shows a retryable error when a success payload has no document id', async () => {+ mocks.getDocumentByTeamSlug.mockResolvedValue(+ ok({ documentMetadata: { documentId: '' } })+ );++ const container = renderRoute();++ await vi.waitFor(() => {+ expect(container.textContent).toContain('Unable to open task');+ });+ expect(container.textContent).toContain('Try again');+ expect(mocks.navigate).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/routes/TaskRoute.tsx b/apps/web/src/routes/TaskRoute.tsxnew file mode 100644index 0000000000..22cc57d6b9--- /dev/null+++ b/apps/web/src/routes/TaskRoute.tsx@@ -0,0 +1,99 @@+import { isValidTeamTaskSlug } from '@app/features/settings/teamSlug';+import { useIsAuthenticated } from '@core/auth';+import { LoadingBlock } from '@core/component/LoadingBlock';+import { setPostLoginRedirect } from '@core/util/postLoginRedirect';+import { thrownResultErrorHasCode } from '@core/util/result';+import { useTeamTaskQuery } from '@queries/storage/team-task';+import { Navigate, useNavigate, useParams } from '@solidjs/router';+import { Button } from '@ui';+import { createEffect, createMemo, Match, on, Show, Switch } from 'solid-js';++type TaskRouteParams = {+ taskSlug: string;+};++/** Resolves a team-scoped task slug to the existing canonical task route. */+export function TaskRoute() {+ const params = useParams<TaskRouteParams>();+ const navigate = useNavigate();+ const isAuthenticated = useIsAuthenticated();+ const taskSlug = () => params.taskSlug;+ const isValidSlug = () => isValidTeamTaskSlug(taskSlug());+ const slugToResolve = createMemo(() =>+ isAuthenticated() === true && isValidSlug() ? taskSlug() : undefined+ );+ const taskQuery = useTeamTaskQuery(slugToResolve);+ const documentId = () => taskQuery.data?.documentMetadata.documentId;+ // FORBIDDEN covers a user who is not part of a Macro team yet; to them the+ // reference is just as unavailable as a slug that does not resolve.+ const taskNotFound = () =>+ thrownResultErrorHasCode(taskQuery.error, 'NOT_FOUND') ||+ thrownResultErrorHasCode(taskQuery.error, 'FORBIDDEN');++ // A GitHub autolink may be opened before the user has signed in. Preserve+ // the full URL so BasePathComponent can restore it after authentication.+ createEffect(+ on(isAuthenticated, (authenticated) => {+ if (authenticated !== false) return;+ setPostLoginRedirect(window.location.href);+ navigate('/login', { replace: true });+ })+ );++ return (+ <Switch fallback={<LoadingBlock />}>+ <Match when={isAuthenticated() !== true}>+ <LoadingBlock />+ </Match>+ <Match when={!isValidSlug()}>+ <TaskRouteError notFound />+ </Match>+ <Match when={documentId()}>+ {(id) => <Navigate href={`/task/${id()}`} />}+ </Match>+ <Match when={taskQuery.isError && !taskQuery.isFetching}>+ <TaskRouteError+ notFound={taskNotFound()}+ onRetry={() => void taskQuery.refetch()}+ />+ </Match>+ <Match when={taskQuery.isSuccess}>+ <TaskRouteError+ notFound={false}+ onRetry={() => void taskQuery.refetch()}+ />+ </Match>+ </Switch>+ );+}++function TaskRouteError(props: { notFound: boolean; onRetry?: () => void }) {+ const navigate = useNavigate();++ return (+ <div class="size-full flex items-center justify-center p-8">+ <div class="flex max-w-sm flex-col items-center gap-4 text-center">+ <h1 class="text-lg font-medium text-ink">+ {props.notFound ? 'Task not found' : 'Unable to open task'}+ </h1>+ <p class="text-sm text-ink-muted">+ {props.notFound+ ? 'This task reference does not exist or is not available to your team.'+ : 'Something went wrong while resolving this task reference.'}+ </p>+ <div class="flex items-center gap-2">+ <Button variant="base" size="sm" onClick={() => navigate('/tasks')}>+ Go to tasks+ </Button>+ <Show when={!props.notFound && props.onRetry}>+ {(onRetry) => (+ <Button variant="base" size="sm" onClick={onRetry()}>+ Try again+ </Button>+ )}+ </Show>+ </div>+ </div>+ </div>+ );+}