Skip to content

Commit

Permalink
feat(gpt-runner-vscode): add wait for server port
Browse files Browse the repository at this point in the history
  • Loading branch information
2214962083 committed Jul 3, 2023
1 parent b0cc8df commit 85f5dea
Show file tree
Hide file tree
Showing 12 changed files with 69 additions and 26 deletions.
17 changes: 17 additions & 0 deletions packages/gpt-runner-shared/src/common/helpers/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,3 +229,20 @@ export function getErrorMsg(error: any) {
)
return errorMessage
}

export function waitForCondition(conditionFn: (...args: any[]) => boolean, timeout = 10000) {
return new Promise<void>((resolve, reject) => {
const startTime = Date.now()
const interval = setInterval(() => {
if (conditionFn()) {
clearInterval(interval)
resolve()
}
else if (Date.now() - startTime > timeout) {
clearInterval(interval)
console.warn('waitForCondition timeout with function', conditionFn.toString())
reject(new Error('waitForCondition timeout'))
}
}, 100)
})
}
3 changes: 2 additions & 1 deletion packages/gpt-runner-vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@
"execa": "^7.1.1",
"fs-extra": "^11.1.1",
"jiti": "^1.18.2",
"uuid": "^9.0.0"
"uuid": "^9.0.0",
"wait-port": "^1.0.4"
}
}
14 changes: 13 additions & 1 deletion packages/gpt-runner-vscode/src/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,23 @@ import { commands } from 'vscode'
import { state } from './state'
import { Commands } from './constant'

export enum VscodeEventName {
VscodeUpdateOpeningFilePaths = 'VscodeUpdateOpeningFilePaths',
}

export interface VscodeEventData {
[VscodeEventName.VscodeUpdateOpeningFilePaths]: void
}

export type VscodeEventEmitterMap = EventEmitterMap & {
[K in VscodeEventName]: (data: VscodeEventData[K]) => any
}

export enum EventType {
ReceiveMessage = 'ReceiveMessage',
}

const emitter = new EventEmitter<EventEmitterMap>()
const emitter = new EventEmitter<VscodeEventEmitterMap>()

// rewrite emit method to send message to webview
const oldEmit = emitter.emit
Expand Down
10 changes: 8 additions & 2 deletions packages/gpt-runner-vscode/src/register/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import child_process from 'child_process'
import { getPort, getRunServerEnv } from '@nicepkg/gpt-runner-shared/node'
import type { Disposable, ExtensionContext } from 'vscode'
import * as vscode from 'vscode'
import waitPort from 'wait-port'
import type { ContextLoader } from '../contextLoader'
import { Commands } from '../constant'
import { log } from '../log'
Expand Down Expand Up @@ -34,8 +35,6 @@ export async function registerServer(
autoFreePort: true,
})

state.serverPort = finalPort

serverProcess = child_process.spawn('node', [
serverUri.fsPath,
'--port',
Expand All @@ -50,6 +49,13 @@ export async function registerServer(
},
})

await waitPort({
port: finalPort,
output: 'silent',
})

state.serverPort = finalPort

serverProcess.stdout.on('data', (data: string) => {
log.appendLine(`stdout: ${data}`)
})
Expand Down
16 changes: 10 additions & 6 deletions packages/gpt-runner-vscode/src/register/sync-opening-file-paths.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as vscode from 'vscode'
import { ClientEventName, debounce, toUnixPath } from '@nicepkg/gpt-runner-shared/common'
import { emitter } from '../emitter'
import { VscodeEventName, emitter } from '../emitter'
import type { ContextLoader } from '../contextLoader'
import { state } from '../state'
import { docIsFile } from '../utils'
Expand Down Expand Up @@ -63,12 +63,16 @@ export async function registerSyncOpeningFilePaths(
debounceUpdateActiveFile()
}))

setTimeout(() => {
// wait for all document to be load
// update files when vscode is activated
debounceUpdateOpenFiles()
// FIXME: fix some file path is lost when vscode is activated
// update files when vscode is activated
debounceUpdateOpenFiles()
debounceUpdateActiveFile()

// for webview
emitter.on(VscodeEventName.VscodeUpdateOpeningFilePaths, () => {
debounceUpdateActiveFile()
}, 1000)
debounceUpdateOpenFiles()
})

return vscode.Disposable.from({
dispose,
Expand Down
18 changes: 8 additions & 10 deletions packages/gpt-runner-vscode/src/register/webview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import fs from 'fs'
import type { ExtensionContext } from 'vscode'
import * as vscode from 'vscode'
import * as uuid from 'uuid'
import { ClientEventName, toUnixPath } from '@nicepkg/gpt-runner-shared/common'
import { ClientEventName, toUnixPath, waitForCondition } from '@nicepkg/gpt-runner-shared/common'
import { PathUtils } from '@nicepkg/gpt-runner-shared/node'
import type { ContextLoader } from '../contextLoader'
import { Commands, EXT_DISPLAY_NAME, EXT_NAME } from '../constant'
import { createHash, getLang, getServerBaseUrl } from '../utils'
import { state } from '../state'
import { EventType, emitter } from '../emitter'
import { EventType, VscodeEventName, emitter } from '../emitter'
import { log } from '../log'

class ChatViewProvider implements vscode.WebviewViewProvider {
Expand All @@ -34,13 +34,7 @@ class ChatViewProvider implements vscode.WebviewViewProvider {
}

static handleWebviewWindowInit() {
emitter.emit(ClientEventName.UpdateIdeOpeningFiles, {
filePaths: state.openingFilePaths,
})

emitter.emit(ClientEventName.UpdateIdeActiveFilePath, {
filePath: state.activeFilePath,
})
emitter.emit(VscodeEventName.VscodeUpdateOpeningFilePaths)
}

resolveWebviewView(
Expand Down Expand Up @@ -108,7 +102,8 @@ class ChatViewProvider implements vscode.WebviewViewProvider {
initialRoutePath: '/chat',
showDiffCodesBtn: true,
showInsertCodesBtn: true,
defaultLangId: '${getLang()}'
defaultLangId: '${getLang()}',
showIdeFileContextOptions: true
}
window.addEventListener('message', event => {
Expand Down Expand Up @@ -149,6 +144,9 @@ export async function registerWebview(
webviewPanelDisposer?.dispose?.()
}

// ensure server port is ready
await waitForCondition(() => !!state.serverPort)

const registerProvider = () => {
dispose()

Expand Down
2 changes: 2 additions & 0 deletions packages/gpt-runner-web/client/src/helpers/global-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export interface GlobalConfig {
showDiffCodesBtn: boolean
showInsertCodesBtn: boolean
defaultLangId: LocaleLang
showIdeFileContextOptions: boolean
}

window.__DEFAULT_GLOBAL_CONFIG__ = {
Expand All @@ -19,6 +20,7 @@ window.__DEFAULT_GLOBAL_CONFIG__ = {
showDiffCodesBtn: false,
showInsertCodesBtn: false,
defaultLangId: getLang(),
showIdeFileContextOptions: false,
}

export function getGlobalConfig() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { LoadingView } from '../../../../../../components/loading-view'
import type { ISelectOption } from '../../../../../../components/select-option'
import { SelectOption } from '../../../../../../components/select-option'
import { useTokenNum } from '../../../../../../hooks/use-token-num.hook'
import { getGlobalConfig } from '../../../../../../helpers/global-config'
import { SelectWrapper, StyledBadge, StyledVSCodeCheckbox } from './context-settings.styles'

export interface ContextSettingsProps {
Expand Down Expand Up @@ -78,7 +79,7 @@ export const ContextSettings = memo((props: ContextSettingsProps) => {
{isLoading && <LoadingView absolute></LoadingView>}

{/* ide opening files or active file */}
<SelectWrapper>
{getGlobalConfig().showIdeFileContextOptions && <SelectWrapper>
<StyledVSCodeCheckbox
style={{
marginBottom: 0,
Expand Down Expand Up @@ -109,7 +110,7 @@ export const ContextSettings = memo((props: ContextSettingsProps) => {
activeIdeFileContents: value === 'activeIdeFileContents',
})
}} />
</SelectWrapper>
</SelectWrapper>}

{/* selected files */}
<StyledVSCodeCheckbox
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,8 @@ function BaseModelSettings_<FormData extends BaseModelConfig>(props: BaseModelSe
style={{
marginBottom: '1rem',
}}
checked={isAllChecked}
indeterminate={isAllChecked}
checked={false}
onClick={(e) => {
const newCheckedMap = Object.fromEntries(Object.keys(checkedMap).map(key => [key, !isAllChecked])) as Record<keyof FormData, boolean>
setCheckedMap(newCheckedMap)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ export const gptFilesControllers: ControllerConfig = {
url: '/get-gpt-file-info',
method: 'get',
handler: async (req, res) => {
const debug = new Debug('gpt-files.controller')
const query = req.query as GetGptFileInfoReqParams

verifyParamsByZod(query, GetGptFileInfoReqParamsSchema)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ export const llmControllers: ControllerConfig = {
return res.write(`data: ${JSON.stringify(buildFailResponse(options))}\n\n`)
}

console.log('debug', process.env.DEBUG)
debug.log('model config', model)

try {
Expand Down
5 changes: 3 additions & 2 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 85f5dea

Please sign in to comment.