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

Add chatgpt chat person set magisk #498

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,4 @@ dist-ssr
*.sw?

.env
.lh*
11 changes: 9 additions & 2 deletions src/app/bots/chatgpt-api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,26 @@ import { parseSSEResponse } from '~utils/sse'
import { AbstractBot, SendMessageParams } from '../abstract-bot'
import { CHATGPT_SYSTEM_MESSAGE, ChatMessage } from './consts'
import { updateTokenUsage } from './usage'
import { loadUsedMagisk } from '~services/magisk'


interface ConversationContext {
messages: ChatMessage[]
}

const SYSTEM_MESSAGE: ChatMessage = { role: 'system', content: CHATGPT_SYSTEM_MESSAGE }
const getChatGptSystemMessage = () => {
const magiskInfo = loadUsedMagisk()
const magisk = magiskInfo.magisk ?? CHATGPT_SYSTEM_MESSAGE
return magisk
}
const CONTEXT_SIZE = 10

export class ChatGPTApiBot extends AbstractBot {
private conversationContext?: ConversationContext

buildMessages(): ChatMessage[] {
return [SYSTEM_MESSAGE, ...this.conversationContext!.messages.slice(-(CONTEXT_SIZE + 1))]
const systemMessage: ChatMessage = { role: 'system', content: getChatGptSystemMessage() }
return [systemMessage, ...this.conversationContext!.messages.slice(-(CONTEXT_SIZE + 1))]
}

async fetchAzureCompletionApi(userConfig: UserConfig, signal?: AbortSignal) {
Expand Down
17 changes: 16 additions & 1 deletion src/app/components/Chat/ChatMessageInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,12 @@ import cx from 'classnames'
import { FC, memo, ReactNode, useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { GoBook } from 'react-icons/go'
import { SiMagisk } from 'react-icons/si'
import { trackEvent } from '~app/plausible'
import { Prompt } from '~services/prompts'
import Button from '../Button'
import PromptCombobox, { ComboboxContext } from '../PromptCombobox'
import PromptLibraryDialog from '../PromptLibrary/Dialog'
import { PromptLibraryDialog, MagiskLibraryDialog} from '../PromptLibrary/Dialog'
import TextInput from './TextInput'

interface Props {
Expand All @@ -40,6 +41,7 @@ const ChatMessageInput: FC<Props> = (props) => {
const formRef = useRef<HTMLFormElement>(null)
const inputRef = useRef<HTMLTextAreaElement>(null)
const [isPromptLibraryDialogOpen, setIsPromptLibraryDialogOpen] = useState(false)
const [isMagiskLibraryDialogOpen, setIsMagiskLibraryDialogOpen] = useState(false)

const [activeIndex, setActiveIndex] = useState<number | null>(null)
const [isComboboxOpen, setIsComboboxOpen] = useState(false)
Expand Down Expand Up @@ -136,6 +138,11 @@ const ChatMessageInput: FC<Props> = (props) => {
trackEvent('open_prompt_library')
}, [])

const openMagiskLibrary = useCallback(() => {
setIsMagiskLibraryDialogOpen(true)
trackEvent('open_magisk_library')
}, [])

return (
<form className={cx('flex flex-row items-center gap-3', props.className)} onSubmit={onFormSubmit} ref={formRef}>
{props.mode === 'full' && (
Expand All @@ -148,6 +155,14 @@ const ChatMessageInput: FC<Props> = (props) => {
insertPrompt={insertTextAtCursor}
/>
)}
<SiMagisk size={22} color="#707070" className="cursor-pointer" onClick={openMagiskLibrary} />
{isMagiskLibraryDialogOpen && (
<MagiskLibraryDialog
isOpen={true}
onClose={() => setIsMagiskLibraryDialogOpen(false)}
insertMagisk={insertTextAtCursor}
/>
)}
<ComboboxContext.Provider value={comboboxContext}>
{isComboboxOpen && (
<FloatingFocusManager context={context} modal={false} initialFocus={-1}>
Expand Down
23 changes: 18 additions & 5 deletions src/app/components/PromptLibrary/Dialog.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import PromptLibrary from './Library'
import PromptLibrary, { MagiskLibrary } from './Library'
import Dialog from '../Dialog'

interface Props {
interface PromptProps {
isOpen: boolean
onClose: () => void
insertPrompt: (text: string) => void
}

const PromptLibraryDialog = (props: Props) => {
interface MagiskProps {
isOpen: boolean
onClose: () => void
insertMagisk: (text: string) => void
}
export const PromptLibraryDialog = (props: PromptProps) => {
return (
<Dialog title="Prompt Library" open={props.isOpen} onClose={props.onClose} className="w-[800px] min-h-[400px]">
<div className="p-5 overflow-auto">
Expand All @@ -17,4 +21,13 @@ const PromptLibraryDialog = (props: Props) => {
)
}

export default PromptLibraryDialog
export const MagiskLibraryDialog = (props: MagiskProps) => {
return (
<Dialog title="Magisk Library" open={props.isOpen} onClose={props.onClose} className="w-[800px] min-h-[400px]">
<div className="p-5 overflow-auto">
<MagiskLibrary />
</div>
</Dialog>
)
}

225 changes: 224 additions & 1 deletion src/app/components/PromptLibrary/Library.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import useSWR from 'swr'
import closeIcon from '~/assets/icons/close.svg'
import { trackEvent } from '~app/plausible'
import { Prompt, loadLocalPrompts, loadRemotePrompts, removeLocalPrompt, saveLocalPrompt } from '~services/prompts'
import { Magisk, loadUsedMagisk, useMagisk, loadLocalMagiskList, loadRemoteMagiskList, removeLocalMagisk, saveLocalMagisk } from '~services/magisk'
import { uuid } from '~utils'
import Button from '../Button'
import { Input, Textarea } from '../Input'
Expand Down Expand Up @@ -231,4 +232,226 @@ const PromptLibrary = (props: { insertPrompt: (text: string) => void }) => {
)
}

export default PromptLibrary
const MagiskItem = (props: {
id: string
title: string
magisk: string
edit?: () => void
remove?: () => void
copyToLocal?: () => void
setUseMagisk: (magisk: Magisk) => void
}) => {
const { t } = useTranslation()
const [saved, setSaved] = useState(false)
const usedMagiskQuery = useSWR('used-magisk', () => loadUsedMagisk(), { suspense: true })
const copyToLocal = useCallback(() => {
props.copyToLocal?.()
setSaved(true)
}, [props])
const emptyMagisk = {
id: '',
title: '',
magisk: ''
}
return (
<div className="group relative flex items-center space-x-3 rounded-lg border border-primary-border bg-primary-background px-5 py-4 shadow-sm hover:border-gray-400">
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-primary-text">{props.title}</p>
</div>
<div className="flex flex-row gap-1">
{props.edit && <ActionButton text={t('Edit')} onClick={props.edit} />}
{props.copyToLocal && <ActionButton text={t(saved ? 'Saved' : 'Save')} onClick={copyToLocal} />}
{!props.copyToLocal && !(usedMagiskQuery.data.id === props.id) && <ActionButton text={t('Use')} onClick={() => {props.setUseMagisk(props)}} />}
{!props.copyToLocal && (usedMagiskQuery.data.id === props.id) && <ActionButton text={t('Cancel use')} onClick={() => {props.setUseMagisk(emptyMagisk)}} />}
</div>
{props.remove && (
<img
src={closeIcon}
className="hidden group-hover:block absolute right-[-8px] top-[-8px] cursor-pointer w-4 h-4 rounded-full bg-primary-background"
onClick={props.remove}
/>
)}
</div>
)
}

function MagiskForm(props: { initialData: Magisk; onSubmit: (data: Magisk) => void }) {
const { t } = useTranslation()
const onSubmit = useCallback(
(e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
e.stopPropagation()
const formdata = new FormData(e.currentTarget)

const json = Object.fromEntries(formdata.entries())

if (json.title && json.magisk) {
props.onSubmit({
id: props.initialData.id,
title: json.title as string,
magisk: json.magisk as string,
})
}
},
[props],
)
return (
<form className="flex flex-col gap-2 w-full" onSubmit={onSubmit}>
<div className="w-full">
<span className="text-sm font-semibold block mb-1 text-primary-text">Magisk {t('Title')}</span>
<Input className="w-full" name="title" defaultValue={props.initialData.title} />
</div>
<div className="w-full">
<span className="text-sm font-semibold block mb-1 text-primary-text">Magisk {t('Content')}</span>
<Textarea className="w-full" name="magisk" defaultValue={props.initialData.magisk} />
</div>
<Button color="primary" text={t('Save')} className="w-fit" size="small" type="submit" />
</form>
)
}


function LocalMagisk() {
const { t } = useTranslation()
const [formData, setFormData] = useState<Magisk | null>(null)
const localMagiskListQuery = useSWR('local-magisk-list', () => loadLocalMagiskList(), { suspense: true })
const usedMagiskQuery = useSWR('used-magisk', () => loadUsedMagisk(), { suspense: true })
const saveMagisk = useCallback(
async (magisk: Magisk) => {
const existed = await saveLocalMagisk(magisk)
localMagiskListQuery.mutate()
setFormData(null)
trackEvent(existed ? 'edit_local_magisk' : 'add_local_magisk')
},
[localMagiskListQuery],
)

const setUseMagisk = useCallback(
async (magisk: Magisk) => {
await useMagisk(magisk)
usedMagiskQuery.mutate()
trackEvent(magisk.id === '' ? 'used_magisk' : 'cancel_used_magisk')
},
[usedMagiskQuery]
)

const removeMagisk = useCallback(
async (id: string) => {
await removeLocalMagisk(id)
localMagiskListQuery.mutate()
trackEvent('remove_local_magisk')
},
[localMagiskListQuery],
)

const create = useCallback(() => {
setFormData({ id: uuid(), title: '', magisk: '' })
}, [])

return (
<>
{localMagiskListQuery.data.length ? (
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 pt-2">
{localMagiskListQuery.data.map((magisk) => (
<MagiskItem
key={magisk.id}
id={magisk.id}
title={magisk.title}
magisk={magisk.magisk}
edit={() => setFormData(magisk)}
setUseMagisk={(magisk: Magisk) => setUseMagisk(magisk)}
remove={() => removeMagisk(magisk.id)}
/>
))}
</div>
) : (
<div className="relative block w-full rounded-lg border-2 border-dashed border-gray-300 p-3 text-center text-sm mt-5 text-primary-text">
You have no magisk.
</div>
)}
<div className="mt-5">
{formData ? (
<MagiskForm initialData={formData} onSubmit={saveMagisk} />
) : (
<Button text={t('Create new magisk')} size="small" onClick={create} />
)}
</div>
</>
)
}

function CommunityMagiskList() {
const magiskListQuery = useSWR('community-magisk-list', () => loadRemoteMagiskList(), { suspense: true })

const copyToLocal = useCallback(async (magisk: Magisk) => {
await saveLocalMagisk({ ...magisk, id: uuid() })
}, [])

return (
<>
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 pt-2">
{magiskListQuery.data.map((magisk, index) => (
<MagiskItem
id=''
key={index + ''}
title={magisk.title}
magisk={magisk.magisk}
setUseMagisk={(magisk: Magisk) => {}}
copyToLocal={() => copyToLocal(magisk)}
/>
))}
</div>
<span className="text-sm mt-5 block text-primary-text">
Contribute on{' '}
<a
href="https://github.com/chathub-dev/community-prompts"
target="_blank"
rel="noreferrer"
className="underline"
>
GitHub
</a>{' '}
or{' '}
<a href="https://openprompt.co/?utm_source=chathub" target="_blank" rel="noreferrer" className="underline">
OpenMagisk
</a>
</span>
</>
)
}

export const MagiskLibrary = () => {
const { t } = useTranslation()

const tabs = useMemo<Tab[]>(
() => [
{ name: t('Your Magisk'), value: 'local' },
// { name: t('Community Magisk'), value: 'community' },
],
[t],
)

return (
<Tabs
tabs={tabs}
renderTab={(tab: (typeof tabs)[0]['value']) => {
if (tab === 'local') {
return (
<Suspense fallback={<BeatLoader size={10} className="mt-5" color="rgb(var(--primary-text))" />}>
<LocalMagisk />
</Suspense>
)
}
// if (tab === 'community') {
// return (
// <Suspense fallback={<BeatLoader size={10} className="mt-5" color="rgb(var(--primary-text))" />}>
// <CommunityMagisk />
// </Suspense>
// )
// }
}}
/>
)
}

export default PromptLibrary
4 changes: 4 additions & 0 deletions src/app/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const resources = {
'Data includes all your settings, chat histories, and local prompts': '数据包括所有设置、聊天记录和本地prompts',
Edit: '编辑',
Use: '使用',
"Cancel use": '取消使用',
Send: '发送',
Stop: '停止',
Title: '标题',
Expand Down Expand Up @@ -63,6 +64,9 @@ const resources = {
'Your Prompts': '你的提示词',
'Community Prompts': '提示词社区',
'Create new prompt': '创建提示词',
'Your Magisk': '你的预设',
'Create new magisk': '创建预设',
'Community Magisk': '预设社区',
},
},
de: {
Expand Down
Loading