Skip to content

Commit

Permalink
fix issue for usePort by using native port
Browse files Browse the repository at this point in the history
  • Loading branch information
vaayne committed May 19, 2023
1 parent 9ba4efc commit 8f38a43
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 70 deletions.
7 changes: 7 additions & 0 deletions src/background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
ToneOptions,
TopicOptions
} from "~lib/enums"
import handleStream from "~lib/stream"

// Register a keyboard shortcut
chrome.commands.onCommand.addListener(function (command) {
Expand Down Expand Up @@ -98,3 +99,9 @@ chrome.contextMenus.onClicked.addListener(async (info, tab) => {
})
})
})

chrome.runtime.onConnect.addListener(function (port) {
port.onMessage.addListener(function (msg) {
handleStream(msg, port)
})
})
16 changes: 7 additions & 9 deletions src/content.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { PlasmoCSConfig } from "plasmo"
import { useEffect, useState } from "react"
import Draggable from "react-draggable"

import { useMessage, usePort } from "@plasmohq/messaging/hook"
import { useMessage } from "@plasmohq/messaging/hook"
import { useStorage } from "@plasmohq/storage/hook"

import ComboxComponent from "~components/combobox"
Expand Down Expand Up @@ -62,7 +62,7 @@ const Index = () => {
const [selectedElement, setSelectedElement] = useState<HTMLElement>()
const [isShowToast, setIsShowToast] = useState<boolean>(false)

const streamPort = usePort("stream")
const streamPort = chrome.runtime.connect({ name: "stream" })

// when press ESC will hidden the window
const handleEscape = (event: any) => {
Expand All @@ -71,6 +71,10 @@ const Index = () => {
}
}

streamPort.onMessage.addListener(function (msg) {
setResponseMessage(msg)
})

// init on page load
useEffect(() => {
// set default engine
Expand All @@ -84,12 +88,6 @@ const Index = () => {
}
}, [])

useEffect(() => {
if (streamPort.data) {
setResponseMessage(streamPort.data)
}
}, [streamPort.data])

// show panel using shortcut
useMessage<string, string>(async (req, res) => {
if (req.name === "activate") {
Expand Down Expand Up @@ -166,7 +164,7 @@ const Index = () => {
notionBoyAPIKey: notionBoyAPIKey
}

streamPort.send(body)
streamPort.postMessage(body)
}

const handleCopy = async () => {
Expand Down
15 changes: 5 additions & 10 deletions src/lib/api/bard.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { ofetch } from "ofetch"

import type { PlasmoMessaging } from "@plasmohq/messaging"

function extractFromHTML(variableName: string, html: string) {
const regex = new RegExp(`"${variableName}":"([^"]+)"`)
const match = regex.exec(html)
Expand Down Expand Up @@ -33,7 +31,7 @@ function generateReqId() {
return Math.floor(Math.random() * 900000) + 100000
}

async function chat(prompt: string, res: PlasmoMessaging.Response<any>) {
async function chat(prompt: string, port: chrome.runtime.Port) {
const requestParams = await fetchRequestParams()
let contextIds = ["", "", ""]
const resp = await ofetch(
Expand All @@ -57,18 +55,15 @@ async function chat(prompt: string, res: PlasmoMessaging.Response<any>) {
)
const { text, ids } = parseBartResponse(resp)
contextIds = ids
res.send(text)
port.postMessage(text)
}

export async function BardChat(
prompt: string,
res: PlasmoMessaging.Response<any>
) {
export async function BardChat(prompt: string, port: chrome.runtime.Port) {
try {
await chat(prompt, res)
await chat(prompt, port)
} catch (err) {
console.error(err)
res.send(
port.postMessage(
"Sorry, Bard Chat is not available at the moment. error: " + err.message
)
}
Expand Down
17 changes: 6 additions & 11 deletions src/lib/api/bing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { FetchError, ofetch } from "ofetch"
import { v4 as uuidv4 } from "uuid"
import WebSocketAsPromised from "websocket-as-promised"

import type { PlasmoMessaging } from "@plasmohq/messaging"

export enum BingConversationStyle {
Creative = "creative",
Balanced = "balanced",
Expand Down Expand Up @@ -232,7 +230,7 @@ export async function createConversation(): Promise<ConversationResponse> {
return resp
}

async function chat(prompt: string, res: PlasmoMessaging.Response<any>) {
async function chat(prompt: string, port: chrome.runtime.Port) {
const conversation = await createConversation()
const bingConversationStyle = BingConversationStyle.Balanced
const conversationContext = {
Expand Down Expand Up @@ -262,15 +260,15 @@ async function chat(prompt: string, res: PlasmoMessaging.Response<any>) {
} else if (event.type === 1) {
if (event.arguments[0].messages) {
const text = convertMessageToMarkdown(event.arguments[0].messages[0])
res.send(text)
port.postMessage(text)
}
} else if (event.type === 2) {
const messages = event.item.messages as ChatResponseMessage[]
const limited = messages.some(
(message) => message.contentOrigin === "TurnLimiter"
)
if (limited) {
res.send(
port.postMessage(
"Sorry, you have reached chat turns limit in this conversation."
)
}
Expand All @@ -284,15 +282,12 @@ async function chat(prompt: string, res: PlasmoMessaging.Response<any>) {
wsp.sendPacked({ protocol: "json", version: 1 })
}

export async function BingChat(
prompt: string,
res: PlasmoMessaging.Response<any>
) {
export async function BingChat(prompt: string, port: chrome.runtime.Port) {
try {
chat(prompt, res)
chat(prompt, port)
} catch (err) {
console.error("BingChat", err)
res.send(
port.postMessage(
"Sorry, Bing Chat is not available at the moment. error: " + err.message
)
}
Expand Down
18 changes: 9 additions & 9 deletions src/lib/api/chatgpt-api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import type { PlasmoMessaging } from "@plasmohq/messaging"

import { parseSSEResponse } from "~lib/utils/sse"

const MODEL = "gpt-3.5-turbo"
Expand All @@ -9,7 +7,7 @@ async function chat(
instraction: string,
prompt: string,
api_key: string,
res: PlasmoMessaging.Response<any>
port: chrome.runtime.Port
) {
const data = {
model: MODEL,
Expand Down Expand Up @@ -47,12 +45,12 @@ async function chat(
const delta = data.choices[0].delta
if (delta?.content) {
content += delta.content
res.send(content)
port.postMessage(content)
}
}
} catch (err) {
console.error(err)
res.send(err)
port.postMessage(err.message)
return
}
})
Expand All @@ -63,23 +61,25 @@ async function ChatGPTApiChat(
instraction: string,
prompt: string,
api_key: string,
res: PlasmoMessaging.Response<any>
port: chrome.runtime.Port
) {
if (!api_key) {
res.send("Please set your OpenAI API key in the extension options page.")
port.postMessage(
"Please set your OpenAI API key in the extension options page."
)
return
}
let message = ""
for (let i = 0; i < 3; i++) {
try {
await chat(url, instraction, prompt, api_key, res)
await chat(url, instraction, prompt, api_key, port)
return
} catch (err) {
console.error(err)
message = err.message
}
}
res.send(message)
port.postMessage(message)
}

export { ChatGPTApiChat }
17 changes: 6 additions & 11 deletions src/lib/api/chatgpt-web.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import { v4 as uuidv4 } from "uuid"

import type { PlasmoMessaging } from "@plasmohq/messaging"

import { storage } from "~lib/storage"
import { parseSSEResponse } from "~lib/utils/sse"

Expand All @@ -26,14 +24,11 @@ async function getAccessToken(): Promise<string> {
return data.accessToken
}

async function ChatGPTWebChat(
prompt: string,
res: PlasmoMessaging.Response<any>
) {
async function ChatGPTWebChat(prompt: string, port: chrome.runtime.Port) {
let message = ""
for (let i = 0; i < 3; i++) {
try {
await chat(prompt, res)
await chat(prompt, port)
return
} catch (err) {
await storage.remove(CACHE_KEY_TOKEN)
Expand All @@ -42,10 +37,10 @@ async function ChatGPTWebChat(
}
// console.log(message)
}
res.send(message)
port.postMessage(message)
}

async function chat(prompt: string, res: PlasmoMessaging.Response<any>) {
async function chat(prompt: string, port: chrome.runtime.Port) {
const accessToken = await getAccessToken()

const cacheConversationId = await storage.get(CACHE_KEY_CONVERSATION_ID)
Expand Down Expand Up @@ -95,12 +90,12 @@ async function chat(prompt: string, res: PlasmoMessaging.Response<any>) {
const text = data.message?.content?.parts?.[0]
if (text) {
// console.debug("chatgpt sse message", text)
res.send(text)
port.postMessage(text)
conversationId = data.conversation_id
}
} catch (err) {
console.error(err)
res.send(`ChatGPT return error, error: ${err.message}`)
port.postMessage(`ChatGPT return error, error: ${err.message}`)
return
}
})
Expand Down
14 changes: 6 additions & 8 deletions src/lib/api/notion-completion.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
import { v4 as uuidv4 } from "uuid"

import type { PlasmoMessaging } from "@plasmohq/messaging"

import { PromptTypeEnum } from "~lib/enums"
import { processNdjsonResp } from "~lib/utils/ndjson"

const MODEL = "openai-3"
const HOST = "https://www.notion.so"

async function complation(
res: PlasmoMessaging.Response<any>,
port: chrome.runtime.Port,
promptType: string,
context: string,
notionSpaceId: string,
Expand Down Expand Up @@ -77,16 +75,16 @@ async function complation(
// console.log(`msg: ${JSON.stringify(msg)}`)
if (msg.type == "success") {
fullMessage += msg.completion
res.send(fullMessage)
port.postMessage(fullMessage)
} else {
res.send(msg.completion)
port.postMessage(msg.completion)
}
}
await processNdjsonResp(resp, onMessage)
}

async function NotionCompletion(
res: PlasmoMessaging.Response<any>,
port: chrome.runtime.Port,
promptType: string,
context: string,
notionSpaceId: string,
Expand All @@ -95,7 +93,7 @@ async function NotionCompletion(
tone?: string
): Promise<string> {
if (!notionSpaceId) {
res.send("Please set notionSpaceId in options page")
port.postMessage("Please set notionSpaceId in options page")
return
}
let message = ""
Expand All @@ -116,7 +114,7 @@ async function NotionCompletion(
message = err.message
}
}
res.send(message)
port.postMessage(message)
}

export { NotionCompletion }
22 changes: 10 additions & 12 deletions src/background/ports/stream.ts → src/lib/stream.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import type { PlasmoMessaging } from "@plasmohq/messaging"

import { BardChat } from "~lib/api/bard"
import { BingChat } from "~lib/api/bing"
import { ChatGPTApiChat } from "~lib/api/chatgpt-api"
Expand All @@ -15,42 +13,44 @@ import {
const OPENAI_API_URL = "https://api.openai.com/v1/chat/completions"
const NOTIONBOY_API_URL = "https://notionboy.theboys.tech/v1/chat/completions"

const handler: PlasmoMessaging.PortHandler = async (req, res) => {
const body = req.body as RequestBody
export default async function handleStream(
body: RequestBody,
port: chrome.runtime.Port
) {
const instruction: string = buildChatGPTinstruction(body)
const prompt: string = buildChatGPTPrompt(body)

switch (body.engine) {
case EngineEnum.ChatGPTWeb:
await ChatGPTWebChat(`${instruction}\n\n${prompt}`, res)
await ChatGPTWebChat(`${instruction}\n\n${prompt}`, port)
break
case EngineEnum.Bing:
await BingChat(`${instruction}\n\n${prompt}`, res)
await BingChat(`${instruction}\n\n${prompt}`, port)
break
case EngineEnum.ChatGPTAPI:
await ChatGPTApiChat(
OPENAI_API_URL,
instruction,
prompt,
body.chatGPTAPIKey,
res
port
)
break
case EngineEnum.Bard:
await BardChat(`${instruction}\n\n${prompt}`, res)
await BardChat(`${instruction}\n\n${prompt}`, port)
break
case EngineEnum.NotionBoy:
await ChatGPTApiChat(
NOTIONBOY_API_URL,
instruction,
prompt,
body.notionBoyAPIKey,
res
port
)
break
case EngineEnum.NotionAI:
await NotionCompletion(
res,
port,
body.builtinPrompt,
body.context,
body.notionSpaceId,
Expand All @@ -60,5 +60,3 @@ const handler: PlasmoMessaging.PortHandler = async (req, res) => {
)
}
}

export default handler

0 comments on commit 8f38a43

Please sign in to comment.