Skip to content

feat: making documents inside public chats visible #665

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
12 changes: 8 additions & 4 deletions app/(auth)/auth.config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import type { NextAuthConfig } from 'next-auth';

const publicRoutes = ['/api/document'];

export const authConfig = {
pages: {
signIn: '/login',
Expand All @@ -15,18 +17,20 @@ export const authConfig = {
const isOnChat = nextUrl.pathname.startsWith('/');
const isOnRegister = nextUrl.pathname.startsWith('/register');
const isOnLogin = nextUrl.pathname.startsWith('/login');
const isPublicRoute = publicRoutes.some((route) =>
nextUrl.pathname.startsWith(route),
);

if (isLoggedIn && (isOnLogin || isOnRegister)) {
return Response.redirect(new URL('/', nextUrl as unknown as URL));
}

if (isOnRegister || isOnLogin) {
return true; // Always allow access to register and login pages
if (isOnRegister || isOnLogin || isPublicRoute) {
return true; // Always allow access to register and login pages or public routes
}

if (isOnChat) {
if (isLoggedIn) return true;
return false; // Redirect unauthenticated users to login page
return isLoggedIn; // Redirect unauthenticated users to login page
}

if (isLoggedIn) {
Expand Down
35 changes: 23 additions & 12 deletions app/(chat)/api/document/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { ArtifactKind } from '@/components/artifact';
import {
deleteDocumentsByIdAfterTimestamp,
getDocumentsById,
getChatById,
saveDocument,
} from '@/lib/db/queries';

Expand All @@ -14,25 +15,30 @@ export async function GET(request: Request) {
return new Response('Missing id', { status: 400 });
}

const session = await auth();
const documents = await getDocumentsById({ id });
const [document] = documents;

if (!session || !session.user) {
return new Response('Unauthorized', { status: 401 });
if (!document) {
return new Response('Not Found', { status: 404 });
}

const documents = await getDocumentsById({ id });
const session = await auth();

const [document] = documents;
if (session?.user && document.userId === session.user.id) {
return Response.json(documents, { status: 200 });
}

if (!document) {
const chat = await getChatById({ id: document.chatId });

if (!chat) {
return new Response('Not Found', { status: 404 });
}

if (document.userId !== session.user.id) {
return new Response('Unauthorized', { status: 401 });
if (chat.visibility === 'public') {
return Response.json(documents, { status: 200 });
}

return Response.json(documents, { status: 200 });
return new Response('Unauthorized', { status: 401 });
}

export async function POST(request: Request) {
Expand All @@ -53,8 +59,13 @@ export async function POST(request: Request) {
content,
title,
kind,
}: { content: string; title: string; kind: ArtifactKind } =
await request.json();
chatId,
}: {
content: string;
title: string;
kind: ArtifactKind;
chatId: string;
} = await request.json();

const documents = await getDocumentsById({ id: id });

Expand All @@ -72,6 +83,7 @@ export async function POST(request: Request) {
title,
kind,
userId: session.user.id,
chatId,
});

return Response.json(document, { status: 200 });
Expand All @@ -97,7 +109,6 @@ export async function DELETE(request: Request) {
}

const documents = await getDocumentsById({ id });

const [document] = documents;

if (document.userId !== session.user.id) {
Expand Down
5 changes: 4 additions & 1 deletion components/artifact.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export type ArtifactKind = (typeof artifactDefinitions)[number]['kind'];
export interface UIArtifact {
title: string;
documentId: string;
chatId: string;
kind: ArtifactKind;
content: string;
isVisible: boolean;
Expand Down Expand Up @@ -146,6 +147,7 @@ function PureArtifact({
title: artifact.title,
content: updatedContent,
kind: artifact.kind,
chatId: artifact.chatId,
}),
});

Expand Down Expand Up @@ -194,7 +196,7 @@ function PureArtifact({
}

const handleVersionChange = (type: 'next' | 'prev' | 'toggle' | 'latest') => {
if (!documents) return;
if (!documents || isReadonly) return;

if (type === 'latest') {
setCurrentVersionIndex(documents.length - 1);
Expand Down Expand Up @@ -503,6 +505,7 @@ export const Artifact = memo(PureArtifact, (prevProps, nextProps) => {
if (!equal(prevProps.votes, nextProps.votes)) return false;
if (prevProps.input !== nextProps.input) return false;
if (!equal(prevProps.messages, nextProps.messages.length)) return false;
if (prevProps.isReadonly !== nextProps.isReadonly) return false;

return true;
});
30 changes: 22 additions & 8 deletions components/code-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { python } from '@codemirror/lang-python';
import { oneDark } from '@codemirror/theme-one-dark';
import { basicSetup } from 'codemirror';
import React, { memo, useEffect, useRef } from 'react';
import { Suggestion } from '@/lib/db/schema';
import type { Suggestion } from '@/lib/db/schema';

type EditorProps = {
content: string;
Expand All @@ -15,17 +15,24 @@ type EditorProps = {
isCurrentVersion: boolean;
currentVersionIndex: number;
suggestions: Array<Suggestion>;
isReadonly?: boolean;
};

function PureCodeEditor({ content, onSaveContent, status }: EditorProps) {
function PureCodeEditor({ content, saveContent, status, isReadonly }: EditorProps) {
const containerRef = useRef<HTMLDivElement>(null);
const editorRef = useRef<EditorView | null>(null);

useEffect(() => {
if (containerRef.current && !editorRef.current) {
const startState = EditorState.create({
doc: content,
extensions: [basicSetup, python(), oneDark],
extensions: [
basicSetup,
python(),
oneDark,
EditorView.editable.of(!isReadonly),
EditorState.readOnly.of(!!isReadonly)
],
});

editorRef.current = new EditorView({
Expand All @@ -47,7 +54,7 @@ function PureCodeEditor({ content, onSaveContent, status }: EditorProps) {
useEffect(() => {
if (editorRef.current) {
const updateListener = EditorView.updateListener.of((update) => {
if (update.docChanged) {
if (update.docChanged && !isReadonly) {
const transaction = update.transactions.find(
(tr) => !tr.annotation(Transaction.remote),
);
Expand All @@ -63,13 +70,19 @@ function PureCodeEditor({ content, onSaveContent, status }: EditorProps) {

const newState = EditorState.create({
doc: editorRef.current.state.doc,
extensions: [basicSetup, python(), oneDark, updateListener],
selection: currentSelection,
extensions: [
basicSetup,
python(),
oneDark,
updateListener,
EditorView.editable.of(!isReadonly),
EditorState.readOnly.of(!!isReadonly)
],
});

editorRef.current.setState(newState);
}
}, [onSaveContent]);
}, [saveContent, isReadonly]);

useEffect(() => {
if (editorRef.current && content) {
Expand Down Expand Up @@ -106,8 +119,9 @@ function areEqual(prevProps: EditorProps, nextProps: EditorProps) {
if (prevProps.status === 'streaming' && nextProps.status === 'streaming')
return false;
if (prevProps.content !== nextProps.content) return false;
if (prevProps.isReadonly !== nextProps.isReadonly) return false;

return true;
}

export const CodeEditor = memo(PureCodeEditor, areEqual);
export const CodeEditor = memo(PureCodeEditor, areEqual);
19 changes: 12 additions & 7 deletions components/document-preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import {
memo,
MouseEvent,
type MouseEvent,
useCallback,
useEffect,
useMemo,
Expand All @@ -11,7 +11,7 @@ import {
import { ArtifactKind, UIArtifact } from './artifact';
import { FileIcon, FullscreenIcon, ImageIcon, LoaderIcon } from './icons';
import { cn, fetcher } from '@/lib/utils';
import { Document } from '@/lib/db/schema';
import type { Document } from '@/lib/db/schema';
import { InlineDocumentSkeleton } from './document-skeleton';
import useSWR from 'swr';
import { Editor } from './text-editor';
Expand All @@ -23,15 +23,15 @@ import { SpreadsheetEditor } from './sheet-editor';
import { ImageEditor } from './image-editor';

interface DocumentPreviewProps {
isReadonly: boolean;
result?: any;
args?: any;
chatId: string;
}

export function DocumentPreview({
isReadonly,
result,
args,
chatId,
}: DocumentPreviewProps) {
const { artifact, setArtifact } = useArtifact();

Expand Down Expand Up @@ -64,7 +64,7 @@ export function DocumentPreview({
<DocumentToolResult
type="create"
result={{ id: result.id, title: result.title, kind: result.kind }}
isReadonly={isReadonly}
chatId={chatId}
/>
);
}
Expand All @@ -74,7 +74,7 @@ export function DocumentPreview({
<DocumentToolCall
type="create"
args={{ title: args.title }}
isReadonly={isReadonly}
chatId={chatId}
/>
);
}
Expand All @@ -94,6 +94,7 @@ export function DocumentPreview({
id: artifact.documentId,
createdAt: new Date(),
userId: 'noop',
chatId: artifact.chatId,
}
: null;

Expand All @@ -104,6 +105,7 @@ export function DocumentPreview({
<HitboxLayer
hitboxRef={hitboxRef}
result={result}
chatId={chatId}
setArtifact={setArtifact}
/>
<DocumentHeader
Expand Down Expand Up @@ -145,12 +147,14 @@ const PureHitboxLayer = ({
hitboxRef,
result,
setArtifact,
chatId,
}: {
hitboxRef: React.RefObject<HTMLDivElement>;
result: any;
setArtifact: (
updaterFn: UIArtifact | ((currentArtifact: UIArtifact) => UIArtifact),
) => void;
chatId: string;
}) => {
const handleClick = useCallback(
(event: MouseEvent<HTMLElement>) => {
Expand All @@ -165,6 +169,7 @@ const PureHitboxLayer = ({
documentId: result.id,
kind: result.kind,
isVisible: true,
chatId,
boundingBox: {
left: boundingBox.x,
top: boundingBox.y,
Expand All @@ -174,7 +179,7 @@ const PureHitboxLayer = ({
},
);
},
[setArtifact, result],
[setArtifact, result, chatId],
);

return (
Expand Down
Loading