Fix rich markdown image paste bloat (#5290)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -62,9 +62,7 @@ import {
|
||||
triggerEdgeBump
|
||||
} from '../../../../src/platform/haptics'
|
||||
import {
|
||||
TerminalWebView,
|
||||
type TerminalKeyboardAvoidanceMetrics,
|
||||
type MobileTerminalTheme,
|
||||
type TerminalModes,
|
||||
type TerminalWebViewHandle
|
||||
} from '../../../../src/terminal/TerminalWebView'
|
||||
@@ -127,6 +125,18 @@ import {
|
||||
buildMobileImagePastePayload,
|
||||
saveMobileClipboardImageAsTempFile
|
||||
} from '../../../../src/session/mobile-clipboard-image'
|
||||
import { TerminalPaneView } from '../../../../src/session/TerminalPaneView'
|
||||
import {
|
||||
getRepoIdFromMobileWorktreeId,
|
||||
isFileExistsErrorMessage,
|
||||
isGestureMouseTrackingMode,
|
||||
MOBILE_SESSION_STATUS_LABELS,
|
||||
TERMINAL_GESTURE_INPUT_BUCKET_CAPACITY,
|
||||
TERMINAL_GESTURE_INPUT_FLUSH_DELAY_MS,
|
||||
TERMINAL_GESTURE_INPUT_MAX_PENDING_SEQUENCES,
|
||||
TERMINAL_GESTURE_INPUT_MAX_QUEUE_AGE_MS,
|
||||
TERMINAL_GESTURE_INPUT_REFILL_PER_SECOND
|
||||
} from '../../../../src/session/mobile-session-route-helpers'
|
||||
import { resolveMarkdownFloatingActionsBottom } from '../../../../src/session/markdown-floating-actions-layout'
|
||||
import { resolveTabStripScrollOffset } from '../../../../src/session/tab-strip-scroll'
|
||||
import {
|
||||
@@ -194,106 +204,6 @@ function getMobileSessionTabTitle(tab: MobileSessionTab): string {
|
||||
return tab.title || 'Terminal'
|
||||
}
|
||||
|
||||
function isFileExistsErrorMessage(message: string): boolean {
|
||||
const normalized = message.toLowerCase()
|
||||
return normalized.includes('eexist') || normalized.includes('already exists')
|
||||
}
|
||||
|
||||
function getRepoIdFromMobileWorktreeId(id: string): string {
|
||||
// Why: mobile cannot import desktop shared modules in its standalone tsc run,
|
||||
// but the runtime worktree id wire format is still `${repoId}::${path}`.
|
||||
const separatorIdx = id.indexOf('::')
|
||||
return separatorIdx === -1 ? id : id.slice(0, separatorIdx)
|
||||
}
|
||||
|
||||
const STATUS_LABELS: Record<ConnectionState, string> = {
|
||||
connecting: 'Connecting',
|
||||
handshaking: 'Securing',
|
||||
connected: 'Connected',
|
||||
disconnected: 'Disconnected',
|
||||
reconnecting: 'Reconnecting',
|
||||
'auth-failed': 'Auth failed'
|
||||
}
|
||||
|
||||
const TERMINAL_GESTURE_INPUT_BUCKET_CAPACITY = 64
|
||||
const TERMINAL_GESTURE_INPUT_REFILL_PER_SECOND = 120
|
||||
const TERMINAL_GESTURE_INPUT_FLUSH_DELAY_MS = 16
|
||||
const TERMINAL_GESTURE_INPUT_MAX_PENDING_SEQUENCES = 32
|
||||
const TERMINAL_GESTURE_INPUT_MAX_QUEUE_AGE_MS = 250
|
||||
|
||||
function isWheelMouseTrackingMode(mode: TerminalModes['mouseTrackingMode'] | undefined): boolean {
|
||||
return mode === 'vt200' || mode === 'drag' || mode === 'any'
|
||||
}
|
||||
|
||||
function isGestureMouseTrackingMode(mode: TerminalModes['mouseTrackingMode'] | undefined): boolean {
|
||||
return mode === 'x10' || isWheelMouseTrackingMode(mode)
|
||||
}
|
||||
|
||||
function TerminalPaneView({
|
||||
handle,
|
||||
active,
|
||||
keyboardLift,
|
||||
terminalTheme,
|
||||
onRef,
|
||||
onWebReady,
|
||||
onSelectionMode,
|
||||
onSelectionCopy,
|
||||
onSelectionEvicted,
|
||||
onModesChanged,
|
||||
onKeyboardAvoidanceMetrics,
|
||||
onHaptic,
|
||||
onTerminalInput,
|
||||
onTerminalTap
|
||||
}: {
|
||||
handle: string
|
||||
active: boolean
|
||||
keyboardLift: number
|
||||
terminalTheme?: MobileTerminalTheme
|
||||
onRef: (handle: string, ref: TerminalWebViewHandle | null) => void
|
||||
onWebReady: (handle: string) => void
|
||||
onSelectionMode: (handle: string, active: boolean) => void
|
||||
onSelectionCopy: (handle: string, text: string) => void
|
||||
onSelectionEvicted: (handle: string) => void
|
||||
onModesChanged: (handle: string, modes: TerminalModes) => void
|
||||
onKeyboardAvoidanceMetrics: (handle: string, metrics: TerminalKeyboardAvoidanceMetrics) => void
|
||||
onHaptic: (kind: 'selection' | 'success' | 'error' | 'edge-bump') => void
|
||||
onTerminalInput: (handle: string, bytes: string) => void
|
||||
onTerminalTap: (handle: string) => void
|
||||
}) {
|
||||
const setRef = useCallback(
|
||||
(ref: TerminalWebViewHandle | null) => {
|
||||
onRef(handle, ref)
|
||||
},
|
||||
[handle, onRef]
|
||||
)
|
||||
|
||||
return (
|
||||
<View
|
||||
pointerEvents={active ? 'auto' : 'none'}
|
||||
style={[
|
||||
styles.terminalPane,
|
||||
keyboardLift > 0 && { transform: [{ translateY: -keyboardLift }] },
|
||||
!active && styles.terminalPaneHidden
|
||||
]}
|
||||
>
|
||||
<TerminalWebView
|
||||
ref={setRef}
|
||||
style={styles.terminalWebView}
|
||||
terminalTheme={terminalTheme}
|
||||
onWebReady={() => onWebReady(handle)}
|
||||
onSelectionMode={(a) => onSelectionMode(handle, a)}
|
||||
onSelectionCopy={(t) => onSelectionCopy(handle, t)}
|
||||
onSelectionEvicted={() => onSelectionEvicted(handle)}
|
||||
onModesChanged={(m) => onModesChanged(handle, m)}
|
||||
onKeyboardAvoidanceMetrics={(m) => onKeyboardAvoidanceMetrics(handle, m)}
|
||||
onHaptic={onHaptic}
|
||||
onTerminalInput={(bytes) => onTerminalInput(handle, bytes)}
|
||||
onTerminalTap={() => onTerminalTap(handle)}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function MarkdownReader({
|
||||
documentId,
|
||||
doc,
|
||||
@@ -3644,7 +3554,7 @@ export default function SessionScreen() {
|
||||
: `${visibleTabs.length} tabs`
|
||||
: showConnectionRetry
|
||||
? `${connectionVerdict.label} — tap to retry`
|
||||
: STATUS_LABELS[connState]
|
||||
: MOBILE_SESSION_STATUS_LABELS[connState]
|
||||
|
||||
// Why: keep safe-area padding in layout at all times, then visually translate
|
||||
// the controls over the terminal when the keyboard appears. iOS keyboard
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { useCallback } from 'react'
|
||||
import { StyleSheet, View } from 'react-native'
|
||||
import {
|
||||
TerminalWebView,
|
||||
type MobileTerminalTheme,
|
||||
type TerminalKeyboardAvoidanceMetrics,
|
||||
type TerminalModes,
|
||||
type TerminalWebViewHandle
|
||||
} from '../terminal/TerminalWebView'
|
||||
|
||||
type TerminalPaneViewProps = {
|
||||
handle: string
|
||||
active: boolean
|
||||
keyboardLift: number
|
||||
terminalTheme?: MobileTerminalTheme
|
||||
onRef: (handle: string, ref: TerminalWebViewHandle | null) => void
|
||||
onWebReady: (handle: string) => void
|
||||
onSelectionMode: (handle: string, active: boolean) => void
|
||||
onSelectionCopy: (handle: string, text: string) => void
|
||||
onSelectionEvicted: (handle: string) => void
|
||||
onModesChanged: (handle: string, modes: TerminalModes) => void
|
||||
onKeyboardAvoidanceMetrics: (handle: string, metrics: TerminalKeyboardAvoidanceMetrics) => void
|
||||
onHaptic: (kind: 'selection' | 'success' | 'error' | 'edge-bump') => void
|
||||
onTerminalInput: (handle: string, bytes: string) => void
|
||||
onTerminalTap: (handle: string) => void
|
||||
}
|
||||
|
||||
export function TerminalPaneView({
|
||||
handle,
|
||||
active,
|
||||
keyboardLift,
|
||||
terminalTheme,
|
||||
onRef,
|
||||
onWebReady,
|
||||
onSelectionMode,
|
||||
onSelectionCopy,
|
||||
onSelectionEvicted,
|
||||
onModesChanged,
|
||||
onKeyboardAvoidanceMetrics,
|
||||
onHaptic,
|
||||
onTerminalInput,
|
||||
onTerminalTap
|
||||
}: TerminalPaneViewProps) {
|
||||
const setRef = useCallback(
|
||||
(ref: TerminalWebViewHandle | null) => {
|
||||
onRef(handle, ref)
|
||||
},
|
||||
[handle, onRef]
|
||||
)
|
||||
|
||||
return (
|
||||
<View
|
||||
// Why: inactive terminal WebViews stay mounted to preserve xterm state,
|
||||
// while touch and visibility are disabled until the tab is active again.
|
||||
pointerEvents={active ? 'auto' : 'none'}
|
||||
style={[
|
||||
styles.terminalPane,
|
||||
keyboardLift > 0 && { transform: [{ translateY: -keyboardLift }] },
|
||||
!active && styles.terminalPaneHidden
|
||||
]}
|
||||
>
|
||||
<TerminalWebView
|
||||
ref={setRef}
|
||||
style={styles.terminalWebView}
|
||||
terminalTheme={terminalTheme}
|
||||
onWebReady={() => onWebReady(handle)}
|
||||
onSelectionMode={(a) => onSelectionMode(handle, a)}
|
||||
onSelectionCopy={(t) => onSelectionCopy(handle, t)}
|
||||
onSelectionEvicted={() => onSelectionEvicted(handle)}
|
||||
onModesChanged={(m) => onModesChanged(handle, m)}
|
||||
onKeyboardAvoidanceMetrics={(m) => onKeyboardAvoidanceMetrics(handle, m)}
|
||||
onHaptic={onHaptic}
|
||||
onTerminalInput={(bytes) => onTerminalInput(handle, bytes)}
|
||||
onTerminalTap={() => onTerminalTap(handle)}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
terminalPane: {
|
||||
...StyleSheet.absoluteFillObject
|
||||
},
|
||||
terminalPaneHidden: {
|
||||
opacity: 0
|
||||
},
|
||||
terminalWebView: {
|
||||
flex: 1
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { TerminalModes } from '../terminal/TerminalWebView'
|
||||
import type { ConnectionState } from '../transport/types'
|
||||
|
||||
export const MOBILE_SESSION_STATUS_LABELS: Record<ConnectionState, string> = {
|
||||
connecting: 'Connecting',
|
||||
handshaking: 'Securing',
|
||||
connected: 'Connected',
|
||||
disconnected: 'Disconnected',
|
||||
reconnecting: 'Reconnecting',
|
||||
'auth-failed': 'Auth failed'
|
||||
}
|
||||
|
||||
export const TERMINAL_GESTURE_INPUT_BUCKET_CAPACITY = 64
|
||||
export const TERMINAL_GESTURE_INPUT_REFILL_PER_SECOND = 120
|
||||
export const TERMINAL_GESTURE_INPUT_FLUSH_DELAY_MS = 16
|
||||
export const TERMINAL_GESTURE_INPUT_MAX_PENDING_SEQUENCES = 32
|
||||
export const TERMINAL_GESTURE_INPUT_MAX_QUEUE_AGE_MS = 250
|
||||
|
||||
export function isFileExistsErrorMessage(message: string): boolean {
|
||||
const normalized = message.toLowerCase()
|
||||
return normalized.includes('eexist') || normalized.includes('already exists')
|
||||
}
|
||||
|
||||
export function getRepoIdFromMobileWorktreeId(id: string): string {
|
||||
// Why: mobile cannot import desktop shared modules in its standalone tsc run,
|
||||
// but the runtime worktree id wire format is still `${repoId}::${path}`.
|
||||
const separatorIdx = id.indexOf('::')
|
||||
return separatorIdx === -1 ? id : id.slice(0, separatorIdx)
|
||||
}
|
||||
|
||||
export function isGestureMouseTrackingMode(
|
||||
mode: TerminalModes['mouseTrackingMode'] | undefined
|
||||
): boolean {
|
||||
return mode === 'x10' || mode === 'vt200' || mode === 'drag' || mode === 'any'
|
||||
}
|
||||
@@ -6,6 +6,10 @@ const sessionSource = readFileSync(
|
||||
new URL('../../app/h/[hostId]/session/[worktreeId].tsx', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
const sessionHelperSource = readFileSync(
|
||||
new URL('../session/mobile-session-route-helpers.ts', import.meta.url),
|
||||
'utf8'
|
||||
)
|
||||
|
||||
function sliceBetween(startPattern: string, endPattern: string): string {
|
||||
const start = source.indexOf(startPattern)
|
||||
@@ -190,8 +194,10 @@ describe('TerminalWebView scroll routing', () => {
|
||||
})
|
||||
|
||||
it('allows x10 mouse gesture reports through the mobile session gate', () => {
|
||||
expect(sessionSource).toContain('function isGestureMouseTrackingMode')
|
||||
expect(sessionSource).toContain("return mode === 'x10' || isWheelMouseTrackingMode(mode)")
|
||||
expect(sessionHelperSource).toContain('function isGestureMouseTrackingMode')
|
||||
expect(sessionHelperSource).toContain(
|
||||
"return mode === 'x10' || mode === 'vt200' || mode === 'drag' || mode === 'any'"
|
||||
)
|
||||
|
||||
const inputBlockStart = sessionSource.indexOf('const handleTerminalInput = useCallback')
|
||||
expect(inputBlockStart).toBeGreaterThanOrEqual(0)
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { toast } from 'sonner'
|
||||
import { insertRichMarkdownImageFromPath } from './rich-markdown-image-insert'
|
||||
import { importExternalPathsToRuntime } from '@/runtime/runtime-file-client'
|
||||
|
||||
vi.mock('@/runtime/runtime-file-client', () => ({
|
||||
importExternalPathsToRuntime: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/connection-context', () => ({
|
||||
getConnectionId: vi.fn(() => 'ssh-1')
|
||||
}))
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: {
|
||||
getState: vi.fn()
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/runtime/runtime-rpc-client', () => ({
|
||||
settingsForRuntimeOwner: vi.fn((settings, runtimeEnvironmentId) =>
|
||||
runtimeEnvironmentId ? { activeRuntimeEnvironmentId: runtimeEnvironmentId } : settings
|
||||
)
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: { error: vi.fn() }
|
||||
}))
|
||||
|
||||
function editorWithRunResult(runResult: boolean) {
|
||||
const run = vi.fn(() => runResult)
|
||||
const insertContentAt = vi.fn(() => ({ run }))
|
||||
const focus = vi.fn(() => ({ insertContentAt }))
|
||||
const chain = vi.fn(() => ({ focus }))
|
||||
return { editor: { chain }, chain, focus, insertContentAt, run }
|
||||
}
|
||||
|
||||
describe('insertRichMarkdownImageFromPath', () => {
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks()
|
||||
const { useAppStore } = await import('@/store')
|
||||
vi.mocked(useAppStore.getState).mockReturnValue({
|
||||
settings: { activeRuntimeEnvironmentId: null },
|
||||
folderWorkspaces: [],
|
||||
worktreesByRepo: {
|
||||
repo1: [{ id: 'wt-1', path: '/repo' }]
|
||||
}
|
||||
} as never)
|
||||
vi.mocked(importExternalPathsToRuntime).mockResolvedValue({
|
||||
results: [{ status: 'imported', destPath: '/repo/image.png' }]
|
||||
} as never)
|
||||
})
|
||||
|
||||
it('shows an error when TipTap rejects image insertion without throwing', async () => {
|
||||
const { editor } = editorWithRunResult(false)
|
||||
|
||||
await insertRichMarkdownImageFromPath({
|
||||
editor: editor as never,
|
||||
filePath: '/repo/note.md',
|
||||
sourcePath: '/tmp/image.png',
|
||||
worktreeId: 'wt-1',
|
||||
insertPos: 4
|
||||
})
|
||||
|
||||
expect(toast.error).toHaveBeenCalledWith('Failed to insert image.')
|
||||
})
|
||||
|
||||
it('uses folder workspace paths for runtime-owned imports', async () => {
|
||||
const { useAppStore } = await import('@/store')
|
||||
vi.mocked(useAppStore.getState).mockReturnValue({
|
||||
settings: { activeRuntimeEnvironmentId: 'env-1' },
|
||||
folderWorkspaces: [{ id: 'folder-1', folderPath: '/folder-workspace' }],
|
||||
worktreesByRepo: {}
|
||||
} as never)
|
||||
const { editor } = editorWithRunResult(true)
|
||||
|
||||
await insertRichMarkdownImageFromPath({
|
||||
editor: editor as never,
|
||||
filePath: '/folder-workspace/note.md',
|
||||
sourcePath: '/tmp/image.png',
|
||||
worktreeId: 'folder:folder-1',
|
||||
runtimeEnvironmentId: 'env-1',
|
||||
insertPos: 4
|
||||
})
|
||||
|
||||
expect(importExternalPathsToRuntime).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
worktreeId: 'folder:folder-1',
|
||||
worktreePath: '/folder-workspace'
|
||||
}),
|
||||
['/tmp/image.png'],
|
||||
'/folder-workspace'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,93 @@
|
||||
import type { Editor } from '@tiptap/react'
|
||||
import { toast } from 'sonner'
|
||||
import { dirname, basename } from '@/lib/path'
|
||||
import { getConnectionId } from '@/lib/connection-context'
|
||||
import { useAppStore } from '@/store'
|
||||
import { importExternalPathsToRuntime } from '@/runtime/runtime-file-client'
|
||||
import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { parseWorkspaceKey } from '../../../../shared/workspace-scope'
|
||||
import { extractIpcErrorMessage } from './rich-markdown-ipc-error-message'
|
||||
|
||||
export type RichMarkdownImageInsertArgs = {
|
||||
editor: Editor
|
||||
filePath: string
|
||||
sourcePath: string
|
||||
worktreeId: string | null
|
||||
runtimeEnvironmentId?: string | null
|
||||
insertPos: number
|
||||
}
|
||||
|
||||
export async function insertRichMarkdownImageFromPath({
|
||||
editor,
|
||||
filePath,
|
||||
sourcePath,
|
||||
worktreeId,
|
||||
runtimeEnvironmentId,
|
||||
insertPos
|
||||
}: RichMarkdownImageInsertArgs): Promise<void> {
|
||||
try {
|
||||
const connectionId = getConnectionId(worktreeId) ?? undefined
|
||||
const settings = settingsForRuntimeOwner(useAppStore.getState().settings, runtimeEnvironmentId)
|
||||
const worktreePath = getWorktreePath(worktreeId)
|
||||
if (settings?.activeRuntimeEnvironmentId?.trim() && !worktreePath) {
|
||||
toast.error(
|
||||
translate(
|
||||
'auto.components.editor.useLocalImagePick.91d835dc88',
|
||||
'Worktree path not available.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
// Why: image bytes should live beside the note instead of inside markdown;
|
||||
// this keeps rich-mode size checks based on document text, not binary data.
|
||||
const { results } = await importExternalPathsToRuntime(
|
||||
{
|
||||
settings,
|
||||
worktreeId,
|
||||
worktreePath,
|
||||
connectionId
|
||||
},
|
||||
[sourcePath],
|
||||
dirname(filePath)
|
||||
)
|
||||
const imported = results.find((result) => result.status === 'imported')
|
||||
if (!imported) {
|
||||
toast.error(
|
||||
translate('auto.components.editor.useLocalImagePick.175cb8b8ce', 'Failed to insert image.')
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
const inserted = editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContentAt(insertPos, { type: 'image', attrs: { src: basename(imported.destPath) } })
|
||||
.run()
|
||||
if (!inserted) {
|
||||
toast.error(
|
||||
translate('auto.components.editor.useLocalImagePick.175cb8b8ce', 'Failed to insert image.')
|
||||
)
|
||||
}
|
||||
} catch (err) {
|
||||
toast.error(extractIpcErrorMessage(err, 'Failed to insert image.'))
|
||||
}
|
||||
}
|
||||
|
||||
function getWorktreePath(worktreeId: string | null): string | null {
|
||||
if (!worktreeId) {
|
||||
return null
|
||||
}
|
||||
const state = useAppStore.getState()
|
||||
const parsedWorkspaceKey = parseWorkspaceKey(worktreeId)
|
||||
if (parsedWorkspaceKey?.type === 'folder') {
|
||||
return (
|
||||
state.folderWorkspaces.find(
|
||||
(workspace) => workspace.id === parsedWorkspaceKey.folderWorkspaceId
|
||||
)?.folderPath ?? null
|
||||
)
|
||||
}
|
||||
const worktrees = Object.values(state.worktreesByRepo ?? {}).flat()
|
||||
return worktrees.find((worktree) => worktree.id === worktreeId)?.path ?? null
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
import { basename, dirname, joinPath } from '@/lib/path'
|
||||
|
||||
export function extractIpcErrorMessage(err: unknown, fallback: string): string {
|
||||
if (!(err instanceof Error)) {
|
||||
return fallback
|
||||
}
|
||||
const match = err.message.match(/Error invoking remote method '[^']*': (?:Error: )?(.+)/)
|
||||
return match ? match[1] : err.message
|
||||
}
|
||||
|
||||
function splitFileExtension(fileName: string): { stem: string; extension: string } {
|
||||
const extensionStart = fileName.lastIndexOf('.')
|
||||
if (extensionStart <= 0) {
|
||||
return { stem: fileName, extension: '' }
|
||||
}
|
||||
return {
|
||||
stem: fileName.slice(0, extensionStart),
|
||||
extension: fileName.slice(extensionStart)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getImageCopyDestination(
|
||||
markdownFilePath: string,
|
||||
sourceImagePath: string
|
||||
): Promise<{ imageName: string; destPath: string }> {
|
||||
const originalImageName = basename(sourceImagePath)
|
||||
const markdownDir = dirname(markdownFilePath)
|
||||
const { stem, extension } = splitFileExtension(originalImageName)
|
||||
let imageName = originalImageName
|
||||
let destPath = joinPath(markdownDir, imageName)
|
||||
let suffix = 1
|
||||
|
||||
const MAX_DECONFLICT_ATTEMPTS = 1000
|
||||
// Why: picking "diagram.png" from elsewhere should not silently replace an
|
||||
// existing sibling asset in the note's directory. We deconflict the copy
|
||||
// target and keep the inserted markdown pointing at the unique name.
|
||||
while (destPath !== sourceImagePath && (await window.api.shell.pathExists(destPath))) {
|
||||
if (suffix >= MAX_DECONFLICT_ATTEMPTS) {
|
||||
throw new Error(`Too many name collisions for "${originalImageName}".`)
|
||||
}
|
||||
imageName = `${stem}-${suffix}${extension}`
|
||||
destPath = joinPath(markdownDir, imageName)
|
||||
suffix += 1
|
||||
}
|
||||
|
||||
return { imageName, destPath }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
export function extractIpcErrorMessage(err: unknown, fallback: string): string {
|
||||
if (!(err instanceof Error)) {
|
||||
return fallback
|
||||
}
|
||||
const match = err.message.match(/Error invoking remote method '[^']*': (?:Error: )?(.+)/)
|
||||
return match ? match[1] : err.message
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { clipboardHasImage, handleRichMarkdownImagePaste } from './rich-markdown-paste-image'
|
||||
import { insertRichMarkdownImageFromPath } from './rich-markdown-image-insert'
|
||||
|
||||
vi.mock('./rich-markdown-image-insert', () => ({
|
||||
insertRichMarkdownImageFromPath: vi.fn().mockResolvedValue(undefined)
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/connection-context', () => ({
|
||||
getConnectionId: vi.fn(() => 'ssh-1')
|
||||
}))
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: {
|
||||
getState: vi.fn(() => ({
|
||||
settings: { activeRuntimeEnvironmentId: null }
|
||||
}))
|
||||
}
|
||||
}))
|
||||
|
||||
vi.mock('@/runtime/runtime-rpc-client', () => ({
|
||||
settingsForRuntimeOwner: vi.fn((settings, runtimeEnvironmentId) =>
|
||||
runtimeEnvironmentId === null
|
||||
? { activeRuntimeEnvironmentId: null }
|
||||
: runtimeEnvironmentId
|
||||
? { activeRuntimeEnvironmentId: runtimeEnvironmentId }
|
||||
: settings
|
||||
)
|
||||
}))
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: { error: vi.fn() }
|
||||
}))
|
||||
|
||||
function pasteEvent(items: Partial<DataTransferItem>[]): ClipboardEvent {
|
||||
return {
|
||||
clipboardData: { items },
|
||||
preventDefault: vi.fn()
|
||||
} as unknown as ClipboardEvent
|
||||
}
|
||||
|
||||
function editorAt(position: number) {
|
||||
return {
|
||||
state: { selection: { from: position } }
|
||||
}
|
||||
}
|
||||
|
||||
async function flushPromises(): Promise<void> {
|
||||
await Promise.resolve()
|
||||
await Promise.resolve()
|
||||
}
|
||||
|
||||
describe('rich markdown image paste', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubGlobal('window', {
|
||||
api: {
|
||||
ui: {
|
||||
saveClipboardImageAsTempFile: vi.fn().mockResolvedValue('/tmp/orca-paste-image.png')
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('detects image files on the clipboard', () => {
|
||||
expect(
|
||||
clipboardHasImage(
|
||||
pasteEvent([
|
||||
{ kind: 'string', type: 'text/plain' },
|
||||
{ kind: 'file', type: 'image/png' }
|
||||
])
|
||||
)
|
||||
).toBe(true)
|
||||
expect(clipboardHasImage(pasteEvent([{ kind: 'string', type: 'text/plain' }]))).toBe(false)
|
||||
})
|
||||
|
||||
it('imports pasted images instead of letting TipTap embed base64 markdown', async () => {
|
||||
const event = pasteEvent([{ kind: 'file', type: 'image/png' }])
|
||||
const editor = editorAt(7)
|
||||
|
||||
expect(
|
||||
handleRichMarkdownImagePaste({
|
||||
editor: editor as never,
|
||||
event,
|
||||
filePath: '/repo/note.md',
|
||||
worktreeId: 'wt-1'
|
||||
})
|
||||
).toBe(true)
|
||||
|
||||
expect(event.preventDefault).toHaveBeenCalled()
|
||||
await flushPromises()
|
||||
expect(window.api.ui.saveClipboardImageAsTempFile).toHaveBeenCalledWith({
|
||||
connectionId: 'ssh-1'
|
||||
})
|
||||
expect(insertRichMarkdownImageFromPath).toHaveBeenCalledWith({
|
||||
editor,
|
||||
filePath: '/repo/note.md',
|
||||
sourcePath: '/tmp/orca-paste-image.png',
|
||||
worktreeId: 'wt-1',
|
||||
runtimeEnvironmentId: undefined,
|
||||
insertPos: 7
|
||||
})
|
||||
})
|
||||
|
||||
it('does not upload clipboard images to SSH first when the markdown belongs to a runtime', async () => {
|
||||
const event = pasteEvent([{ kind: 'file', type: 'image/png' }])
|
||||
|
||||
handleRichMarkdownImagePaste({
|
||||
editor: editorAt(3) as never,
|
||||
event,
|
||||
filePath: '/repo/note.md',
|
||||
worktreeId: 'wt-1',
|
||||
runtimeEnvironmentId: 'env-1'
|
||||
})
|
||||
|
||||
await flushPromises()
|
||||
expect(window.api.ui.saveClipboardImageAsTempFile).toHaveBeenCalledWith({
|
||||
connectionId: undefined
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Editor } from '@tiptap/react'
|
||||
import { toast } from 'sonner'
|
||||
import { getConnectionId } from '@/lib/connection-context'
|
||||
import { useAppStore } from '@/store'
|
||||
import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client'
|
||||
import { extractIpcErrorMessage } from './rich-markdown-ipc-error-message'
|
||||
import { insertRichMarkdownImageFromPath } from './rich-markdown-image-insert'
|
||||
|
||||
export type RichMarkdownImagePasteArgs = {
|
||||
editor: Editor | null
|
||||
event: ClipboardEvent
|
||||
filePath: string
|
||||
worktreeId: string | null
|
||||
runtimeEnvironmentId?: string | null
|
||||
}
|
||||
|
||||
export function clipboardHasImage(event: ClipboardEvent): boolean {
|
||||
const data = event.clipboardData
|
||||
if (!data) {
|
||||
return false
|
||||
}
|
||||
return Array.from(data.items).some(
|
||||
(item) => item.kind === 'file' && item.type.startsWith('image/')
|
||||
)
|
||||
}
|
||||
|
||||
export function handleRichMarkdownImagePaste({
|
||||
editor,
|
||||
event,
|
||||
filePath,
|
||||
worktreeId,
|
||||
runtimeEnvironmentId
|
||||
}: RichMarkdownImagePasteArgs): boolean {
|
||||
if (!editor || !clipboardHasImage(event)) {
|
||||
return false
|
||||
}
|
||||
|
||||
event.preventDefault()
|
||||
const insertPos = editor.state.selection.from
|
||||
|
||||
void saveClipboardImageForMarkdownPaste(worktreeId, runtimeEnvironmentId)
|
||||
.then((sourcePath) => {
|
||||
if (!sourcePath) {
|
||||
return
|
||||
}
|
||||
return insertRichMarkdownImageFromPath({
|
||||
editor,
|
||||
filePath,
|
||||
sourcePath,
|
||||
worktreeId,
|
||||
runtimeEnvironmentId,
|
||||
insertPos
|
||||
})
|
||||
})
|
||||
.catch((err) => {
|
||||
toast.error(extractIpcErrorMessage(err, 'Failed to insert image.'))
|
||||
})
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
async function saveClipboardImageForMarkdownPaste(
|
||||
worktreeId: string | null,
|
||||
runtimeEnvironmentId?: string | null
|
||||
): Promise<string | null> {
|
||||
const settings = settingsForRuntimeOwner(useAppStore.getState().settings, runtimeEnvironmentId)
|
||||
const hasRuntimeOwner = Boolean(settings?.activeRuntimeEnvironmentId?.trim())
|
||||
// Why: runtime-owned notes use runtime-side clipboard import; routing this
|
||||
// temp save through SSH would put the source file on the wrong machine.
|
||||
const connectionId = hasRuntimeOwner ? undefined : (getConnectionId(worktreeId) ?? undefined)
|
||||
|
||||
return window.api.ui.saveClipboardImageAsTempFile({ connectionId })
|
||||
}
|
||||
@@ -1,13 +1,8 @@
|
||||
import { useCallback } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import type { Editor } from '@tiptap/react'
|
||||
import { extractIpcErrorMessage, getImageCopyDestination } from './rich-markdown-image-utils'
|
||||
import { useAppStore } from '@/store'
|
||||
import { getConnectionId } from '@/lib/connection-context'
|
||||
import { basename, dirname } from '@/lib/path'
|
||||
import { importExternalPathsToRuntime } from '@/runtime/runtime-file-client'
|
||||
import { settingsForRuntimeOwner } from '@/runtime/runtime-rpc-client'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { toast } from 'sonner'
|
||||
import { insertRichMarkdownImageFromPath } from './rich-markdown-image-insert'
|
||||
import { extractIpcErrorMessage } from './rich-markdown-ipc-error-message'
|
||||
|
||||
export function useLocalImagePick(
|
||||
editor: Editor | null,
|
||||
@@ -29,80 +24,16 @@ export function useLocalImagePick(
|
||||
if (!srcPath) {
|
||||
return
|
||||
}
|
||||
const connectionId = getConnectionId(worktreeId) ?? undefined
|
||||
const settings = settingsForRuntimeOwner(
|
||||
useAppStore.getState().settings,
|
||||
runtimeEnvironmentId
|
||||
)
|
||||
if (settings?.activeRuntimeEnvironmentId?.trim() || connectionId) {
|
||||
const worktreePath = getWorktreePath(worktreeId)
|
||||
if (settings?.activeRuntimeEnvironmentId?.trim() && !worktreePath) {
|
||||
toast.error(
|
||||
translate(
|
||||
'auto.components.editor.useLocalImagePick.91d835dc88',
|
||||
'Worktree path not available.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
// Why: picked images are client-local files while remote markdown lives
|
||||
// on the server. Upload beside the markdown file before inserting the
|
||||
// relative image path so preview/save works from any client.
|
||||
const { results } = await importExternalPathsToRuntime(
|
||||
{
|
||||
settings,
|
||||
worktreeId,
|
||||
worktreePath,
|
||||
connectionId
|
||||
},
|
||||
[srcPath],
|
||||
dirname(filePath)
|
||||
)
|
||||
const imported = results.find((result) => result.status === 'imported')
|
||||
if (!imported) {
|
||||
toast.error(
|
||||
translate(
|
||||
'auto.components.editor.useLocalImagePick.175cb8b8ce',
|
||||
'Failed to insert image.'
|
||||
)
|
||||
)
|
||||
return
|
||||
}
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContentAt(insertPos, {
|
||||
type: 'image',
|
||||
attrs: { src: basename(imported.destPath) }
|
||||
})
|
||||
.run()
|
||||
return
|
||||
}
|
||||
// Why: copy the image next to the markdown file and insert a relative path
|
||||
// so the markdown stays portable and doesn't bloat with base64 data.
|
||||
const { imageName, destPath } = await getImageCopyDestination(filePath, srcPath)
|
||||
if (srcPath !== destPath) {
|
||||
await window.api.shell.copyFile({ srcPath, destPath })
|
||||
}
|
||||
// Why: insertContentAt places the image at the exact saved position
|
||||
// regardless of where focus lands after the native file dialog closes,
|
||||
// whereas setTextSelection can be overridden by ProseMirror's focus logic.
|
||||
editor
|
||||
.chain()
|
||||
.focus()
|
||||
.insertContentAt(insertPos, { type: 'image', attrs: { src: imageName } })
|
||||
.run()
|
||||
await insertRichMarkdownImageFromPath({
|
||||
editor,
|
||||
filePath,
|
||||
sourcePath: srcPath,
|
||||
worktreeId,
|
||||
runtimeEnvironmentId,
|
||||
insertPos
|
||||
})
|
||||
} catch (err) {
|
||||
toast.error(extractIpcErrorMessage(err, 'Failed to insert image.'))
|
||||
}
|
||||
}, [editor, filePath, runtimeEnvironmentId, worktreeId])
|
||||
}
|
||||
|
||||
function getWorktreePath(worktreeId: string | null): string | null {
|
||||
if (!worktreeId) {
|
||||
return null
|
||||
}
|
||||
const state = useAppStore.getState()
|
||||
const worktrees = Object.values(state.worktreesByRepo ?? {}).flat()
|
||||
return worktrees.find((worktree) => worktree.id === worktreeId)?.path ?? null
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useEditor, type Editor } from '@tiptap/react'
|
||||
import { createRichMarkdownExtensions } from './rich-markdown-extensions'
|
||||
import { createRichMarkdownKeyHandler } from './rich-markdown-key-handler'
|
||||
import { handleRichMarkdownCut } from './rich-markdown-cut-handler'
|
||||
import { handleRichMarkdownImagePaste } from './rich-markdown-paste-image'
|
||||
import { encodeRawMarkdownHtmlForRichEditor } from './raw-markdown-html'
|
||||
import { normalizeSoftBreaks } from './rich-markdown-normalize'
|
||||
import { autoFocusRichEditor } from './rich-markdown-auto-focus'
|
||||
@@ -129,6 +130,14 @@ export function useRichMarkdownEditorInstance({
|
||||
handleDOMEvents: {
|
||||
cut: handleRichMarkdownCut
|
||||
},
|
||||
handlePaste: (_view, event) =>
|
||||
handleRichMarkdownImagePaste({
|
||||
editor: editorRef.current,
|
||||
event,
|
||||
filePath,
|
||||
worktreeId,
|
||||
runtimeEnvironmentId
|
||||
}),
|
||||
handleTextInput: (view, from, to, text) => {
|
||||
typedEmptyOrderedListMarkerRef.current = false
|
||||
if (text !== ' ' || from !== to || !view.state.selection.empty) {
|
||||
|
||||
@@ -10,6 +10,7 @@ export const TUI_AGENT_DISPLAY_NAMES: Record<TuiAgent, string> = {
|
||||
'claude-agent-teams': 'Claude Agent Teams',
|
||||
openclaude: 'OpenClaude',
|
||||
codex: 'Codex',
|
||||
devin: 'Devin',
|
||||
autohand: 'Autohand Code',
|
||||
opencode: 'OpenCode',
|
||||
pi: 'Pi',
|
||||
|
||||
Reference in New Issue
Block a user