Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(docx): open uploaded DOCX files again (#7443)

Jacob Beckermanf82c538b2e97
diff --git a/apps/web/src/features/block-write/definition.test.ts b/apps/web/src/features/block-write/definition.test.ts
new file mode 100644
index 0000000000..3ee1c46fd3
--- /dev/null
+++ b/apps/web/src/features/block-write/definition.test.ts
@@ -0,0 +1,52 @@
+import { err, ok } from 'neverthrow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({ file: vi.fn(), markdown: vi.fn() }));
+vi.mock('@core/block', () => ({
+ defineBlock: (value: unknown) => value,
+ LoadErrors: { INVALID: 'invalid' },
+}));
+vi.mock('@queries/storage/documentLoad/sync-document-context', () => ({
+ fetchFileDocumentOpenContext: state.file,
+ fetchSyncDocumentOpenContext: state.markdown,
+}));
+vi.mock('./DocxBlock', () => ({ default: () => null }));
+
+const context = {
+ syncService: true,
+ documentMetadata: { documentId: 'doc', fileType: 'docx' },
+ userAccessLevel: 'edit',
+ fromCache: false,
+ token: 'token',
+};
+
+describe('write block loading', () => {
+ beforeEach(() => {
+ state.file.mockReset();
+ state.markdown.mockReset();
+ });
+
+ // An uploaded DOCX is a stored file, never sync-service content, so the
+ // Markdown open context rejects it with INVALID ("Unable to load").
+ it('opens an uploaded DOCX through the file open context, not the Markdown one', async () => {
+ state.file.mockResolvedValue(ok(context));
+ const { definition } = await import('./definition');
+ const loaded = await definition.load(
+ { type: 'sync-service', id: 'doc' },
+ 'navigate'
+ );
+ expect(loaded.isOk() && loaded.value).toEqual(context);
+ expect(state.file).toHaveBeenCalledWith('doc');
+ expect(state.markdown).not.toHaveBeenCalled();
+ });
+
+ it('passes load errors through', async () => {
+ state.file.mockResolvedValue(err([{ code: 'UNAUTHORIZED' }]));
+ const { definition } = await import('./definition');
+ const loaded = await definition.load(
+ { type: 'sync-service', id: 'doc' },
+ 'navigate'
+ );
+ expect(loaded.isErr() && loaded.error).toEqual([{ code: 'UNAUTHORIZED' }]);
+ });
+});
diff --git a/apps/web/src/features/block-write/definition.ts b/apps/web/src/features/block-write/definition.ts
index 2b85e94a20..3e14e56dc0 100644
--- a/apps/web/src/features/block-write/definition.ts
+++ b/apps/web/src/features/block-write/definition.ts
@@ -1,5 +1,5 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
-import { fetchSyncDocumentOpenContext } from '@queries/storage/documentLoad/sync-document-context';
+import { fetchFileDocumentOpenContext } from '@queries/storage/documentLoad/sync-document-context';
import { err, ok } from 'neverthrow';
import { lazy } from 'solid-js';
@@ -21,9 +21,11 @@ export const definition = defineBlock({
async load(source, intent) {
if (source.type !== 'sync-service') return LoadErrors.INVALID;
if (intent === 'preload') return ok({ type: 'preload', origin: source });
- // The same open context as the other sync-service blocks: a token plus a
- // session-bound authorization that re-checks access on reconnect.
- const context = await fetchSyncDocumentOpenContext(source.id);
+ // Not the Markdown open context: an uploaded DOCX stays a stored file until
+ // an editor seeds it into the sync service, so its location is never
+ // sync-service content. The file context keeps the same session-bound
+ // sync authorization.
+ const context = await fetchFileDocumentOpenContext(source.id);
if (context.isErr()) return err(context.error);
return ok(context.value);
},
diff --git a/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts b/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts
index 7d43eb29d0..a202ceb612 100644
--- a/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts
+++ b/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.test.ts
@@ -1,6 +1,7 @@
import 'fake-indexeddb/auto';
import { render } from '@solidjs/testing-library';
import { QueryClientProvider } from '@tanstack/solid-query';
+import { base64url } from 'jose';
import { err, ok } from 'neverthrow';
import { createComponent, createEffect } from 'solid-js';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -13,7 +14,10 @@ import {
clearOfflineDocumentContexts,
offlineDocumentContextCache,
} from './offline-context-runtime';
-import { fetchSyncDocumentOpenContext } from './sync-document-context';
+import {
+ fetchFileDocumentOpenContext,
+ fetchSyncDocumentOpenContext,
+} from './sync-document-context';
const mocks = vi.hoisted(() => ({
native: true,
@@ -347,3 +351,56 @@ describe('native document identity bootstrap', () => {
expect(mocks.userInfo).not.toHaveBeenCalled();
});
});
+
+// An uploaded DOCX lives in document storage until its first editor seeds it
+// into sync-service: its location is a presigned URL, never sync content.
+describe('stored-file document open context', () => {
+ const docxContext = {
+ ...documentContext,
+ documentMetadata: { ...documentContext.documentMetadata, fileType: 'docx' },
+ };
+ const sessionToken = `e30.${base64url.encode(
+ JSON.stringify({
+ user_id: identity.id,
+ document_id: 'doc-1',
+ access_level: 'edit',
+ })
+ )}.test-signature`;
+
+ it('opens on the web without requiring sync-service content', async () => {
+ mocks.native = false;
+ mocks.bundle.mockResolvedValue({ ...docxContext, token: 'web-token' });
+ const opened = (
+ await fetchFileDocumentOpenContext('doc-1')
+ )._unsafeUnwrap();
+ expect(opened).toMatchObject({ fromCache: false, token: 'web-token' });
+ expect(opened.authorization).toBeUndefined();
+ expect(mocks.location).not.toHaveBeenCalled();
+ });
+
+ it('binds native synchronization to the session and never opens from the cache', async () => {
+ queryClient.setQueryData(authKeys.userInfo.queryKey, identity);
+ mocks.bundle.mockResolvedValue({ ...docxContext, token: sessionToken });
+ const opened = (
+ await fetchFileDocumentOpenContext('doc-1')
+ )._unsafeUnwrap();
+ expect(opened.fromCache).toBe(false);
+ expect(mocks.snapshot).not.toHaveBeenCalled();
+ expect(mocks.location).not.toHaveBeenCalled();
+ const authorization = opened.authorization!;
+ expect(authorization.isCurrent()).toBe(true);
+ expect(authorization.canWrite()).toBe(true);
+ expect(await authorization.getToken()).toBe(sessionToken);
+
+ const invalidated = vi.fn();
+ authorization.onInvalidated(invalidated);
+ mocks.login = false;
+ await clearOfflineDocumentContexts();
+ queryClient.setQueryData(authKeys.userInfo.queryKey, {
+ authenticated: false,
+ });
+ expect(invalidated).toHaveBeenCalled();
+ expect(authorization.isCurrent()).toBe(false);
+ expect(authorization.canWrite()).toBe(false);
+ });
+});
diff --git a/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.ts b/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.ts
index 0b0e996e41..dc88c8f94b 100644
--- a/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.ts
+++ b/apps/web/src/lib/queries/storage/documentLoad/sync-document-context.ts
@@ -19,6 +19,7 @@ import {
} from '../document-location';
import { authorizedContext } from './authorized-context';
import {
+ type DocumentLoadBundle,
documentLoadQueryOptions,
fetchDocumentLoadBundle,
} from './documentLoadBundle';
@@ -43,24 +44,39 @@ const readyLocation = z.object({
content: z.object({ state: z.literal('ready') }),
});
+function fetchBundle(documentId: string, session?: DocumentCacheSession) {
+ return session
+ ? queryClient.fetchQuery({
+ ...documentLoadQueryOptions(documentId),
+ queryKey: documentLoadKeys.authorizedBundle(
+ session.userId,
+ session.epoch,
+ documentId
+ ).queryKey,
+ // Authorization must not borrow a token from an earlier connection
+ // or an in-flight request belonging to a different signed-in user.
+ staleTime: 0,
+ })
+ : throwOnErr(() => fetchDocumentLoadBundle(documentId));
+}
+
+function bindBundle(
+ documentId: string,
+ session: DocumentCacheSession | undefined,
+ bundle: DocumentLoadBundle
+): FreshSyncDocumentContext {
+ return {
+ syncService: true,
+ ...(session ? authorizedContext(documentId, session, bundle) : bundle),
+ };
+}
+
async function loadRemote(
documentId: string,
session?: DocumentCacheSession
): Promise<FreshSyncDocumentContext> {
const [bundle, initialLocation] = await Promise.all([
- session
- ? queryClient.fetchQuery({
- ...documentLoadQueryOptions(documentId),
- queryKey: documentLoadKeys.authorizedBundle(
- session.userId,
- session.epoch,
- documentId
- ).queryKey,
- // Authorization must not borrow a token from an earlier connection
- // or an in-flight request belonging to a different signed-in user.
- staleTime: 0,
- })
- : throwOnErr(() => fetchDocumentLoadBundle(documentId)),
+ fetchBundle(documentId, session),
throwOnErr(() => fetchDocumentLocation({ documentId })),
]);
let location: unknown = initialLocation;
@@ -77,10 +93,7 @@ async function loadRemote(
},
]);
}
- return {
- syncService: true,
- ...(session ? authorizedContext(documentId, session, bundle) : bundle),
- };
+ return bindBundle(documentId, session, bundle);
}
const loader = createSyncDocumentContextLoader({
@@ -103,8 +116,19 @@ const loader = createSyncDocumentContextLoader({
onSessionChange: onDocumentSessionChange,
});
-/** Open cached native documents before network work; authorize synchronization separately. */
-export async function fetchSyncDocumentOpenContext(documentId: string) {
+// An uploaded file (DOCX) stays in document storage until its first editor
+// seeds it into sync-service, so its location is never sync-service content
+// and there is no local snapshot to open from offline. Synchronization still
+// uses the same session-bound authorization.
+const fileLoader = createSyncDocumentContextLoader({
+ cache: offlineDocumentContextCache,
+ loadRemote: async (documentId, session) =>
+ bindBundle(documentId, session, await fetchBundle(documentId, session)),
+ hasLocalSnapshot: async () => false,
+ onSessionChange: onDocumentSessionChange,
+});
+
+async function openWith(opener: typeof loader, documentId: string) {
if (isNativeMobilePlatform() && !offlineDocumentContextCache.capture()) {
const epoch = documentSessionEpoch();
await prefetchUserInfo();
@@ -115,5 +139,15 @@ export async function fetchSyncDocumentOpenContext(documentId: string) {
return LoadErrors.UNAUTHORIZED;
}
}
- return loadResult(catchToResult(() => loader.load(documentId)));
+ return loadResult(catchToResult(() => opener.load(documentId)));
+}
+
+/** Open cached native documents before network work; authorize synchronization separately. */
+export function fetchSyncDocumentOpenContext(documentId: string) {
+ return openWith(loader, documentId);
+}
+
+/** Open a stored-file document (DOCX), which needs no sync-service content, with the same authorization. */
+export function fetchFileDocumentOpenContext(documentId: string) {
+ return openWith(fileLoader, documentId);
}