Skip to content
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

chore(chat, vscode): add api getActiveEditorSelection #3638

Merged
merged 9 commits into from
Jan 2, 2025
Merged
Show file tree
Hide file tree
Changes from 3 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
6 changes: 6 additions & 0 deletions clients/tabby-chat-panel/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,11 @@ export interface ClientApiMethods {

// Provide all repos found in workspace folders.
readWorkspaceGitRepositories?: () => Promise<GitRepository[]>

/**
* @returns The active selection of active editor.
*/
getActiveEditorSelection?: () => Promise<EditorFileContext | null>
}

export interface ClientApi extends ClientApiMethods {
Expand All @@ -297,6 +302,7 @@ export function createClient(target: HTMLIFrameElement, api: ClientApiMethods):
openInEditor: api.openInEditor,
openExternal: api.openExternal,
readWorkspaceGitRepositories: api.readWorkspaceGitRepositories,
getActiveEditorSelection: api.getActiveEditorSelection,
},
})
}
Expand Down
1 change: 1 addition & 0 deletions clients/vscode/src/chat/createClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export function createClient(webview: Webview, api: ClientApiMethods): ServerApi
openInEditor: api.openInEditor,
openExternal: api.openExternal,
readWorkspaceGitRepositories: api.readWorkspaceGitRepositories,
getActiveEditorSelection: api.getActiveEditorSelection,
},
});
}
26 changes: 18 additions & 8 deletions clients/vscode/src/chat/webview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type {
SymbolInfo,
FileLocation,
GitRepository,
EditorFileContext,
} from "tabby-chat-panel";
import * as semver from "semver";
import type { StatusInfo, Config } from "tabby-agent";
Expand Down Expand Up @@ -101,14 +102,14 @@ export class ChatWebview {
this.disposables.push(
window.onDidChangeActiveTextEditor((editor) => {
if (this.chatPanelLoaded) {
this.syncActiveEditorSelection(editor);
this.notifyActiveEditorSelectionChange(editor);
}
}),
);
this.disposables.push(
window.onDidChangeTextEditorSelection((event) => {
if (event.textEditor === window.activeTextEditor && this.chatPanelLoaded) {
this.syncActiveEditorSelection(event.textEditor);
this.notifyActiveEditorSelectionChange(event.textEditor);
}
}),
);
Expand Down Expand Up @@ -237,11 +238,10 @@ export class ChatWebview {

this.chatPanelLoaded = true;

// 1. Sync the active editor selection
// 2. Send pending actions
// 3. Call the client's init method
// 4. Show the chat panel (call syncStyle underlay)
await this.syncActiveEditorSelection(window.activeTextEditor);
// 1. Send pending actions
// 2. Call the client's init method
// 3. Show the chat panel (call syncStyle underlay)
// await this.notifyActiveEditorSelectionChange(window.activeTextEditor);

this.pendingActions.forEach(async (fn) => {
await fn();
Expand Down Expand Up @@ -448,6 +448,16 @@ export class ChatWebview {
}
return infoList;
},

getActiveEditorSelection: async (): Promise<EditorFileContext | null> => {
const editor = window.activeTextEditor;
if (!editor) {
liangfung marked this conversation as resolved.
Show resolved Hide resolved
return null;
}

const fileContext = await getFileContextFromSelection(editor, this.gitProvider);
return fileContext;
},
});
}

Expand Down Expand Up @@ -635,7 +645,7 @@ export class ChatWebview {
);
}

private async syncActiveEditorSelection(editor: TextEditor | undefined) {
private async notifyActiveEditorSelectionChange(editor: TextEditor | undefined) {
if (!editor || !isValidForSyncActiveEditorSelection(editor)) {
await this.client?.updateActiveSelection(null);
return;
Expand Down
48 changes: 30 additions & 18 deletions ee/tabby-ui/app/chat/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ const convertToHSLColor = (style: string) => {
}

export default function ChatPage() {
const [isInit, setIsInit] = useState(false)
const [isChatComponentLoaded, setIsChatComponentLoaded] = useState(false)
const [isServerLoaded, setIsServerLoaded] = useState(false)
const [fetcherOptions, setFetcherOptions] = useState<FetcherOptions | null>(
null
)
Expand All @@ -61,7 +62,6 @@ export default function ChatPage() {
const [isRefreshLoading, setIsRefreshLoading] = useState(false)

const chatRef = useRef<ChatRef>(null)
const [chatLoaded, setChatLoaded] = useState(false)
const { width } = useWindowSize()
const prevWidthRef = useRef(width)
const chatInputRef = useRef<HTMLTextAreaElement>(null)
Expand All @@ -76,8 +76,12 @@ export default function ChatPage() {
useState(false)
const [supportsOnLookupSymbol, setSupportsOnLookupSymbol] = useState(false)
const [
supportsProvideWorkspaceGitRepoInfo,
setSupportsProvideWorkspaceGitRepoInfo
supportsReadWorkspaceGitRepoInfo,
setSupportsReadWorkspaceGitRepoInfo
] = useState(false)
const [
supportsGetActiveEditorSelection,
setSupportsGetActiveEditorSelection
] = useState(false)

const executeCommand = (command: ChatCommand) => {
Expand Down Expand Up @@ -116,7 +120,6 @@ export default function ChatPage() {
}

setActiveChatId(nanoid())
setIsInit(true)
setFetcherOptions(request.fetcherOptions)
useMacOSKeyboardEventHandler.current =
request.useMacOSKeyboardEventHandler
Expand Down Expand Up @@ -244,34 +247,41 @@ export default function ChatPage() {
server?.hasCapability('lookupSymbol').then(setSupportsOnLookupSymbol)
server
?.hasCapability('readWorkspaceGitRepositories')
.then(setSupportsProvideWorkspaceGitRepoInfo)
.then(setSupportsReadWorkspaceGitRepoInfo)
server
?.hasCapability('getActiveEditorSelection')
.then(setSupportsGetActiveEditorSelection)
}

checkCapabilities()
checkCapabilities().then(() => {
setTimeout(() => {
setIsServerLoaded(true)
})
})
}
}, [server])

useLayoutEffect(() => {
if (!chatLoaded) return
if (!isChatComponentLoaded) return
if (
width &&
isInit &&
isServerLoaded &&
fetcherOptions &&
!errorMessage &&
!prevWidthRef.current
) {
chatRef.current?.focus()
}
prevWidthRef.current = width
}, [width, chatLoaded])
}, [width, isChatComponentLoaded])

const clearPendingState = () => {
setPendingRelevantContexts([])
setPendingCommand(undefined)
setPendingActiveSelection(null)
}

const onChatLoaded = () => {
const onChatLoaded = async () => {
const currentChatRef = chatRef.current
if (!currentChatRef) return

Expand All @@ -284,14 +294,11 @@ export default function ChatPage() {
}

if (pendingCommand) {
// FIXME: this delay is a workaround for waiting for the active selection to be updated
setTimeout(() => {
currentChatRef.executeCommand(pendingCommand)
}, 500)
await currentChatRef.executeCommand(pendingCommand)
}

clearPendingState()
setChatLoaded(true)
await setIsChatComponentLoaded(true)
}

const openInEditor = async (fileLocation: FileLocation) => {
Expand Down Expand Up @@ -376,7 +383,7 @@ export default function ChatPage() {
)
}

if (!isInit || !fetcherOptions) {
if (!isServerLoaded || !fetcherOptions) {
return (
<StaticContent>
<>
Expand Down Expand Up @@ -420,10 +427,15 @@ export default function ChatPage() {
openInEditor={openInEditor}
openExternal={openExternal}
readWorkspaceGitRepositories={
supportsProvideWorkspaceGitRepoInfo
supportsReadWorkspaceGitRepoInfo
? server?.readWorkspaceGitRepositories
: undefined
}
getActiveEditorSelection={
supportsGetActiveEditorSelection
? server?.getActiveEditorSelection
: undefined
}
/>
</ErrorBoundary>
)
Expand Down
53 changes: 31 additions & 22 deletions ee/tabby-ui/app/files/components/chat-side-bar.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import React, { useRef, useState } from 'react'
import React, { useState } from 'react'
import { find } from 'lodash-es'
import type { FileLocation, GitRepository } from 'tabby-chat-panel'
import type {
EditorContext,
FileLocation,
GitRepository
} from 'tabby-chat-panel'
import { useClient } from 'tabby-chat-panel/react'

import { RepositoryListQuery } from '@/lib/gql/generates/graphql'
Expand Down Expand Up @@ -32,7 +36,6 @@ export const ChatSideBar: React.FC<ChatSideBarProps> = ({
React.useContext(SourceCodeBrowserContext)
const activeChatId = useChatStore(state => state.activeChatId)
const iframeRef = React.useRef<HTMLIFrameElement>(null)
const executedCommand = useRef(false)
const repoMapRef = useLatest(repoMap)
const openInCodeBrowser = async (fileLocation: FileLocation) => {
const { filepath, location } = fileLocation
Expand Down Expand Up @@ -72,6 +75,25 @@ export const ChatSideBar: React.FC<ChatSideBarProps> = ({
return list
})

const getActiveEditorSelection = useLatest(() => {
if (!pendingEvent) return null
const { lineFrom, lineTo, code, path, gitUrl } = pendingEvent
const activeSelection: EditorContext = {
kind: 'file',
content: code,
range: {
start: lineFrom,
end: lineTo ?? lineFrom
},
filepath: {
kind: 'git',
filepath: path,
gitUrl
}
}
return activeSelection
})

const client = useClient(iframeRef, {
refresh: async () => {
window.location.reload()
Expand All @@ -94,7 +116,10 @@ export const ChatSideBar: React.FC<ChatSideBarProps> = ({
window.open(url, '_blank')
},
readWorkspaceGitRepositories: async () => {
return readWorkspaceGitRepositories.current?.()
return readWorkspaceGitRepositories.current()
},
getActiveEditorSelection: async () => {
return getActiveEditorSelection.current()
}
})

Expand Down Expand Up @@ -122,25 +147,9 @@ export const ChatSideBar: React.FC<ChatSideBarProps> = ({
React.useEffect(() => {
if (pendingEvent && client && initialized) {
const execute = async () => {
const { lineFrom, lineTo, code, path, gitUrl } = pendingEvent
client.updateActiveSelection({
kind: 'file',
content: code,
range: {
start: lineFrom,
end: lineTo ?? lineFrom
},
filepath: {
kind: 'git',
filepath: path,
gitUrl
}
})
// todo notify activeselection change
const command = getCommand(pendingEvent)
// FIXME: this delay is a workaround for waiting for the active selection to be updated
setTimeout(() => {
client.executeCommand(command)
}, 500)
client.executeCommand(command)
setPendingEvent(undefined)
}

Expand Down
11 changes: 10 additions & 1 deletion ee/tabby-ui/app/files/components/source-code-browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ const SourceCodeBrowserRenderer: React.FC<SourceCodeBrowserProps> = ({
setInitialized,
chatSideBarVisible,
setChatSideBarVisible,
pendingEvent,
setPendingEvent,
repoMap,
setRepoMap,
Expand Down Expand Up @@ -655,8 +656,10 @@ const SourceCodeBrowserRenderer: React.FC<SourceCodeBrowserProps> = ({

React.useEffect(() => {
const onCallCompletion = (data: QuickActionEventPayload) => {
setChatSideBarVisible(true)
setPendingEvent(data)
// setTimeout(() => {
// setChatSideBarVisible(true)
// })
}
emitter.on('code_browser_quick_action', onCallCompletion)

Expand All @@ -665,6 +668,12 @@ const SourceCodeBrowserRenderer: React.FC<SourceCodeBrowserProps> = ({
}
}, [])

React.useEffect(() => {
if (pendingEvent && !chatSideBarVisible) {
setChatSideBarVisible(true)
}
}, [pendingEvent])

return (
<ResizablePanelGroup
direction="horizontal"
Expand Down
Loading
Loading