Skip to content

An AI-powered search engine with a generative UI

feat: add centralized keyboard shortcut system (#817)

Yoshiki Miura927a1f205c2a
diff --git a/TODO.md b/TODO.md
new file mode 100644
index 00000000..f35f2f49
--- /dev/null
+++ b/TODO.md
@@ -0,0 +1,36 @@
+# Issue #798: File upload/download with docker not working
+
+## 事象
+
+R2/S3互換ストレージへのファイルアップロードは成功するが、ダウンロード時に `400 Bad Request` が発生する。
+
+### 原因
+
+- `R2_PUBLIC_URL` に S3 APIエンドポイント (`https://{accountId}.r2.cloudflarestorage.com`) が設定されている
+- S3 APIエンドポイントは認証(AWS Signature V4)が必要だが、AI SDKは認証なしのHTTP GETでファイルを取得しようとするため 400 になる
+- `.env.local.example` に `R2_PUBLIC_URL` が何を指すのか説明がなく、ユーザーがS3 APIエンドポイントと混同しやすい
+
+### 該当コード
+
+- `app/api/upload/route.ts:94` — ダウンロードURLを `R2_PUBLIC_URL + filePath` で構築
+- `lib/storage/r2-client.ts:4` — `R2_PUBLIC_URL` の定義
+
+## 対応方針
+
+Phase 1: ドキュメント整備(今回対応)
+Phase 2: Presigned URL方式への変更(将来検討)
+
+## TODO (Phase 1: ドキュメント整備)
+
+- [ ] `.env.local.example` の `R2_PUBLIC_URL` にコメントを追加
+ - S3 APIエンドポイントではなく、パブリックアクセスURLであることを明記
+ - R2の場合: `https://pub-xxx.r2.dev` またはカスタムドメイン
+ - Cloudflare R2ダッシュボードでバケットのパブリックアクセスを有効にする必要がある旨を記載
+- [ ] Issue #798 にコメントで回答
+
+## 将来検討 (Phase 2: Presigned URL)
+
+- object key をDBに保存し、表示時・AI投入時に都度 presigned URL を生成する方式
+- `R2_PUBLIC_URL` 環境変数の廃止
+- バケットのパブリック公開が不要になるセキュリティ上のメリット
+- 詳細は Codex レビュー指摘事項を参照(DBへの署名付きURL保存禁止、既存データ互換など)
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index bd559307..9e160dd0 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -79,8 +79,9 @@ export async function POST(req: Request) {
forwardedFor.split(',')[0]?.trim() ||
req.headers.get('x-real-ip') ||
null
- const guestLimitResponse = await checkAndEnforceGuestLimit(ip)
- if (guestLimitResponse) return guestLimitResponse
+ // TODO: Re-enable guest limit
+ // const guestLimitResponse = await checkAndEnforceGuestLimit(ip)
+ // if (guestLimitResponse) return guestLimitResponse
}
const cookieStore = await cookies()
diff --git a/app/layout.tsx b/app/layout.tsx
index 01220ca5..3487b883 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -14,6 +14,7 @@ import { Toaster } from '@/components/ui/sonner'
import AppSidebar from '@/components/app-sidebar'
import ArtifactRoot from '@/components/artifact/artifact-root'
import Header from '@/components/header'
+import { KeyboardShortcutHandler } from '@/components/keyboard-shortcut-handler'
import { ThemeProvider } from '@/components/theme-provider'
import './globals.css'
@@ -86,6 +87,7 @@ export default async function RootLayout({
<UserProvider hasUser={!!userId}>
<SidebarProvider defaultOpen={false}>
{userId && <AppSidebar />}
+ <KeyboardShortcutHandler />
<div className="flex flex-col flex-1 min-w-0">
<Header user={user} />
<main className="flex flex-1 min-h-0 min-w-0 overflow-hidden">
diff --git a/components/chat-panel.tsx b/components/chat-panel.tsx
index 9e0744fa..368a0292 100644
--- a/components/chat-panel.tsx
+++ b/components/chat-panel.tsx
@@ -8,6 +8,7 @@ import { UseChatHelpers } from '@ai-sdk/react'
import { ArrowUp, ChevronDown, MessageCirclePlus, Square } from 'lucide-react'
import { toast } from 'sonner'
+import { SHORTCUT_EVENTS } from '@/lib/keyboard-shortcuts'
import { UploadedFile } from '@/lib/types'
import type { UIDataTypes, UIMessage, UITools } from '@/lib/types/ai'
import type { ModelSelectorData } from '@/lib/types/model-selector'
@@ -96,7 +97,7 @@ export function ChatPanel({
}, 300)
}
- const handleNewChat = () => {
+ const handleNewChat = useCallback(() => {
setMessages([])
closeArtifact()
// Reset focus state when clearing chat
@@ -105,7 +106,35 @@ export function ChatPanel({
// Reset chatId in parent component
onNewChat?.()
router.push('/')
- }
+ }, [setMessages, closeArtifact, onNewChat, router])
+
+ // Listen for keyboard shortcut events
+ // Uses defaultPrevented to prevent duplicate handling
+ // when multiple ChatPanel instances are mounted (Next.js component caching)
+ const handleNewChatRef = useRef(handleNewChat)
+ useEffect(() => {
+ handleNewChatRef.current = handleNewChat
+ }, [handleNewChat])
+
+ useEffect(() => {
+ const handleFocusInput = (e: Event) => {
+ if (e.defaultPrevented) return
+ e.preventDefault()
+ inputRef.current?.focus()
+ }
+ const handleNewChatShortcut = (e: Event) => {
+ if (e.defaultPrevented) return
+ e.preventDefault()
+ handleNewChatRef.current()
+ }
+
+ window.addEventListener(SHORTCUT_EVENTS.focusInput, handleFocusInput)
+ window.addEventListener(SHORTCUT_EVENTS.newChat, handleNewChatShortcut)
+ return () => {
+ window.removeEventListener(SHORTCUT_EVENTS.focusInput, handleFocusInput)
+ window.removeEventListener(SHORTCUT_EVENTS.newChat, handleNewChatShortcut)
+ }
+ }, [])
const isToolInvocationInProgress = () => {
if (!messages.length) return false
diff --git a/components/chat.tsx b/components/chat.tsx
index ef4b7e7e..db8bebfe 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -9,6 +9,8 @@ import { toast } from 'sonner'
import { ChatProvider } from '@/lib/contexts/chat-context'
import { generateId } from '@/lib/db/schema'
+import { SHORTCUT_EVENTS } from '@/lib/keyboard-shortcuts'
+import { stripSpecBlocks } from '@/lib/render/strip-spec-blocks'
import { UploadedFile } from '@/lib/types'
import type { UIMessage } from '@/lib/types/ai'
import {
@@ -234,6 +236,51 @@ export function Chat({
return result
}, [messages])
+ // Listen for copy message shortcut
+ // Uses ref to avoid re-registering listener on every messages change.
+ // Uses defaultPrevented + visibility check to prevent duplicate handling
+ // when multiple Chat instances are mounted (Next.js component caching).
+ const messagesRef = useRef(messages)
+ useEffect(() => {
+ messagesRef.current = messages
+ }, [messages])
+
+ useEffect(() => {
+ const handleCopyMessage = (e: Event) => {
+ if (e.defaultPrevented) return
+ // Only handle in the visible (active) Chat instance
+ if (!scrollContainerRef.current?.offsetParent) return
+ e.preventDefault()
+
+ const assistantMessages = messagesRef.current.filter(
+ m => m.role === 'assistant'
+ )
+ const lastAssistant = assistantMessages[assistantMessages.length - 1]
+ if (!lastAssistant) {
+ toast.info('No assistant message to copy')
+ return
+ }
+ const text =
+ lastAssistant.parts
+ ?.filter(
+ (p): p is { type: 'text'; text: string } => p.type === 'text'
+ )
+ .map(p => p.text)
+ .join('\n') ?? ''
+
+ if (text) {
+ navigator.clipboard.writeText(stripSpecBlocks(text)).then(
+ () => toast.success('Message copied to clipboard'),
+ () => toast.error('Failed to copy message')
+ )
+ }
+ }
+
+ window.addEventListener(SHORTCUT_EVENTS.copyMessage, handleCopyMessage)
+ return () =>
+ window.removeEventListener(SHORTCUT_EVENTS.copyMessage, handleCopyMessage)
+ }, [])
+
// Dispatch custom event when messages change
useEffect(() => {
window.dispatchEvent(
diff --git a/components/keyboard-shortcut-handler.tsx b/components/keyboard-shortcut-handler.tsx
new file mode 100644
index 00000000..e7a95e21
--- /dev/null
+++ b/components/keyboard-shortcut-handler.tsx
@@ -0,0 +1,62 @@
+'use client'
+
+import { useTheme } from 'next-themes'
+
+import { toast } from 'sonner'
+
+import { SHORTCUT_EVENTS, SHORTCUTS } from '@/lib/keyboard-shortcuts'
+import { SearchMode } from '@/lib/types/search'
+import { getCookie, setCookie } from '@/lib/utils/cookies'
+
+import { useKeyboardShortcut } from '@/hooks/use-keyboard-shortcut'
+
+import { useSidebar } from './ui/sidebar'
+
+const THEME_CYCLE: Record<string, string> = {
+ dark: 'light',
+ light: 'system',
+ system: 'dark'
+}
+
+const SEARCH_MODE_LABELS: Record<SearchMode, string> = {
+ quick: 'Quick',
+ adaptive: 'Adaptive'
+}
+
+export function KeyboardShortcutHandler() {
+ const { theme, setTheme } = useTheme()
+ const { toggleSidebar } = useSidebar()
+
+ useKeyboardShortcut(SHORTCUTS.toggleSidebar, toggleSidebar)
+
+ useKeyboardShortcut(SHORTCUTS.focusInput, () => {
+ window.dispatchEvent(
+ new CustomEvent(SHORTCUT_EVENTS.focusInput, { cancelable: true })
+ )
+ })
+
+ useKeyboardShortcut(SHORTCUTS.newChat, () => {
+ window.dispatchEvent(
+ new CustomEvent(SHORTCUT_EVENTS.newChat, { cancelable: true })
+ )
+ })
+
+ useKeyboardShortcut(SHORTCUTS.toggleTheme, () => {
+ setTheme(THEME_CYCLE[theme ?? 'system'] ?? 'dark')
+ })
+
+ useKeyboardShortcut(SHORTCUTS.copyMessage, () => {
+ window.dispatchEvent(
+ new CustomEvent(SHORTCUT_EVENTS.copyMessage, { cancelable: true })
+ )
+ })
+
+ useKeyboardShortcut(SHORTCUTS.toggleSearchMode, () => {
+ const current = getCookie('searchMode') || 'quick'
+ const next: SearchMode = current === 'quick' ? 'adaptive' : 'quick'
+ setCookie('searchMode', next)
+ toast.info(`Search mode: ${SEARCH_MODE_LABELS[next]}`)
+ })
+
+ return null
+}
diff --git a/components/ui/sidebar.tsx b/components/ui/sidebar.tsx
index 31aff046..fa10c9e9 100644
--- a/components/ui/sidebar.tsx
+++ b/components/ui/sidebar.tsx
@@ -33,7 +33,6 @@ const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = '16rem'
const SIDEBAR_WIDTH_MOBILE = '18rem'
const SIDEBAR_WIDTH_ICON = '3rem'
-const SIDEBAR_KEYBOARD_SHORTCUT = 'b'
type SidebarContextProps = {
state: 'expanded' | 'collapsed'
@@ -128,22 +127,6 @@ const SidebarProvider = React.forwardRef<
return isMobile ? setOpenMobile(open => !open) : setOpen(open => !open)
}, [isMobile, setOpen, setOpenMobile])
- // Adds a keyboard shortcut to toggle the sidebar.
- React.useEffect(() => {
- const handleKeyDown = (event: KeyboardEvent) => {
- if (
- event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
- (event.metaKey || event.ctrlKey)
- ) {
- event.preventDefault()
- toggleSidebar()
- }
- }
-
- window.addEventListener('keydown', handleKeyDown)
- return () => window.removeEventListener('keydown', handleKeyDown)
- }, [toggleSidebar])
-
// We add a state so that we can do data-state="expanded" or "collapsed".
// This makes it easier to style the sidebar with Tailwind classes.
const state = open ? 'expanded' : 'collapsed'
diff --git a/hooks/use-keyboard-shortcut.ts b/hooks/use-keyboard-shortcut.ts
new file mode 100644
index 00000000..c9fabab5
--- /dev/null
+++ b/hooks/use-keyboard-shortcut.ts
@@ -0,0 +1,30 @@
+'use client'
+
+import { useEffect, useRef } from 'react'
+
+import {
+ matchesShortcut,
+ type ShortcutDefinition} from '@/lib/keyboard-shortcuts'
+
+export function useKeyboardShortcut(
+ shortcut: ShortcutDefinition,
+ handler: () => void
+): void {
+ const handlerRef = useRef(handler)
+
+ useEffect(() => {
+ handlerRef.current = handler
+ }, [handler])
+
+ useEffect(() => {
+ const handleKeyDown = (event: KeyboardEvent) => {
+ if (matchesShortcut(event, shortcut)) {
+ event.preventDefault()
+ handlerRef.current()
+ }
+ }
+
+ window.addEventListener('keydown', handleKeyDown)
+ return () => window.removeEventListener('keydown', handleKeyDown)
+ }, [shortcut])
+}
diff --git a/lib/keyboard-shortcuts.ts b/lib/keyboard-shortcuts.ts
new file mode 100644
index 00000000..e66b4ea9
--- /dev/null
+++ b/lib/keyboard-shortcuts.ts
@@ -0,0 +1,72 @@
+export type ShortcutDefinition = {
+ id: string
+ key: string
+ meta: boolean
+ shift: boolean
+ description: string
+}
+
+export const SHORTCUTS = {
+ toggleSidebar: {
+ id: 'toggleSidebar',
+ key: 'b',
+ meta: true,
+ shift: false,
+ description: 'Toggle sidebar'
+ },
+ focusInput: {
+ id: 'focusInput',
+ key: 'k',
+ meta: true,
+ shift: false,
+ description: 'Focus search input'
+ },
+ newChat: {
+ id: 'newChat',
+ key: 'o',
+ meta: true,
+ shift: true,
+ description: 'New chat'
+ },
+ toggleTheme: {
+ id: 'toggleTheme',
+ key: 'd',
+ meta: true,
+ shift: true,
+ description: 'Cycle theme'
+ },
+ copyMessage: {
+ id: 'copyMessage',
+ key: 'c',
+ meta: true,
+ shift: true,
+ description: 'Copy latest assistant message'
+ },
+ toggleSearchMode: {
+ id: 'toggleSearchMode',
+ key: 'm',
+ meta: true,
+ shift: true,
+ description: 'Toggle search mode'
+ }
+} as const satisfies Record<string, ShortcutDefinition>
+
+export const SHORTCUT_EVENTS = {
+ focusInput: 'shortcut:focus-input',
+ newChat: 'shortcut:new-chat',
+ copyMessage: 'shortcut:copy-message'
+} as const
+
+export function matchesShortcut(
+ event: KeyboardEvent,
+ shortcut: ShortcutDefinition
+): boolean {
+ if (event.repeat) return false
+ if (event.altKey) return false
+ return (
+ event.key.toLowerCase() === shortcut.key &&
+ (event.metaKey || event.ctrlKey) === shortcut.meta &&
+ event.shiftKey === shortcut.shift
+ )
+}
+