Skip to content

feat: Adding /file command #118

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

Open
wants to merge 4 commits 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
140 changes: 137 additions & 3 deletions src/chat-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { DEFAULT_CHAT_SYSTEM_PROMPT } from './default-prompts';
import { jupyternautLiteIcon } from './icons';
import { IAIProviderRegistry } from './tokens';
import { AIChatModel } from './types/ai-model';
import { ContentsManager } from '@jupyterlab/services';

/**
* The base64 encoded SVG string of the jupyternaut lite icon.
Expand All @@ -39,12 +40,14 @@ export const welcomeMessage = (providers: string[]) => `
#### Ask JupyterLite AI


The provider to use can be set in the <button data-commandLinker-command="settingeditor:open" data-commandLinker-args='{"query": "AI provider"}' href="#">settings editor</button>, by selecting it from
the <img src="${AI_AVATAR}" width="16" height="16"> _AI provider_ settings.
The provider to use can be set in the <button data-commandLinker-command="settingeditor:open" data-commandLinker-args='{"query": "AI providers"}' href="#">settings editor</button>, by selecting it from
the <img src="${AI_AVATAR}" width="16" height="16"> _AI providers_ settings.

The current providers that are available are _${providers.sort().join('_, _')}_.

To clear the chat, you can use the \`/clear\` command from the chat input.
- To clear the chat, you can use the \`/clear\` command from the chat input.

- To insert file contents into the chat, use the \`/file\` command.
`;

export type ConnectionMessage = {
Expand Down Expand Up @@ -252,6 +255,137 @@ export namespace ChatHandler {
}
}

export class FileCommandProvider implements IChatCommandProvider {
public id: string = '@jupyterlite/ai:file-commands';
private _contents = new ContentsManager();

private _slash_commands: ChatCommand[] = [
{
name: '/file',
providerId: this.id,
replaceWith: '/file',
description: 'Include contents of a selected file'
}
];

async listCommandCompletions(inputModel: IInputModel) {
const match = inputModel.currentWord?.match(/^\/\w*/)?.[0];
return match
? this._slash_commands.filter(cmd => cmd.name.startsWith(match))
: [];
}

async onSubmit(inputModel: IInputModel): Promise<void> {
const inputText = inputModel.value?.trim() ?? '';

const fileMentioned = inputText.match(/\/file\s+`[^`]+`/);
const hasFollowUp = inputText.replace(fileMentioned?.[0] || '', '').trim();

if (inputText.startsWith('/file') && !fileMentioned) {
await this._showFileBrowser(inputModel);
} else {
return;
}

if (fileMentioned && hasFollowUp) {
console.log(inputText);
} else {
console.log('Waiting for follow-up text.');
throw new Error('Incomplete /file command');
}
}

private async _showFileBrowser(inputModel: IInputModel): Promise<void> {
return new Promise(resolve => {
const modal = document.createElement('div');
modal.className = 'file-browser-modal';
modal.innerHTML = `
<div class="file-browser-panel">
<h3>Select a File</h3>
<ul class="file-list"></ul>
<div class="button-row">
<button class="back-btn">Back</button>
<button class="close-btn">Close</button>
</div>
</div>
`;
document.body.appendChild(modal);

const fileList = modal.querySelector('.file-list')!;
const closeBtn = modal.querySelector('.close-btn') as HTMLButtonElement;
const backBtn = modal.querySelector('.back-btn') as HTMLButtonElement;
let currentPath = '';

const listDir = async (path = '') => {
try {
const dir = await this._contents.get(path, { content: true });

fileList.innerHTML = '';

for (const item of dir.content) {
const li = document.createElement('li');
if (item.type === 'directory') {
li.textContent = `${item.name}/`;
li.className = 'directory';
} else if (item.type === 'file' || item.type === 'notebook') {
li.textContent = item.name;
li.className = 'file';
}

fileList.appendChild(li);

li.onclick = async () => {
try {
if (item.type === 'directory') {
currentPath = item.path;
await listDir(item.path);
} else if (item.type === 'file' || item.type === 'notebook') {
const existingText = inputModel.value?.trim();
const updatedText =
existingText === '/file'
? `/file \`${item.path}\` `
: `${existingText} \`${item.path}\``;

inputModel.value = updatedText.trim();
li.style.backgroundColor = '#d2f8d2';

document.body.removeChild(modal);
resolve();
}
} catch (error) {
console.error(error);
document.body.removeChild(modal);
resolve();
}
};

fileList.appendChild(li);
}
} catch (err) {
console.error(err);
}
};

closeBtn.onclick = () => {
document.body.removeChild(modal);
resolve();
};
backBtn.onclick = () => {
if (!currentPath || currentPath === '') {
return;
}

const parts = currentPath.split('/');
parts.pop();
currentPath = parts.join('/');
listDir(currentPath);
};

listDir();
});
}
}

namespace Private {
/**
* Return the current timestamp in milliseconds.
Expand Down
7 changes: 6 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ import { IFormRendererRegistry } from '@jupyterlab/ui-components';
import { ReadonlyPartialJSONObject } from '@lumino/coreutils';
import { ISecretsManager, SecretsManager } from 'jupyter-secrets-manager';

import { ChatHandler, welcomeMessage } from './chat-handler';
import {
ChatHandler,
welcomeMessage,
FileCommandProvider
} from './chat-handler';
import { CompletionProvider } from './completion-provider';
import { defaultProviderPlugins } from './default-providers';
import { AIProviderRegistry } from './provider';
Expand All @@ -37,6 +41,7 @@ const chatCommandRegistryPlugin: JupyterFrontEndPlugin<IChatCommandRegistry> = {
activate: () => {
const registry = new ChatCommandRegistry();
registry.addProvider(new ChatHandler.ClearCommandProvider());
registry.addProvider(new FileCommandProvider());
return registry;
}
};
Expand Down
96 changes: 96 additions & 0 deletions style/base.css
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,99 @@
border-color: var(--jp-brand-color1);
color: var(--jp-brand-color1);
}

.file-browser-modal {
position: fixed;
top: 20%;
left: 30%;
width: 40%;
background: #fff;
border: 1px solid #414040;
padding: 1em;
z-index: 9999;
box-shadow: 0 0 10px #0003;
border-radius: 8px;
font-family: sans-serif;
}

.file-browser-panel {
display: flex;
flex-direction: column;
}

.file-list {
list-style: none;
padding-left: 0;
max-height: 200px;
overflow-y: auto;
margin: 1em 0;
}

.file-list li {
padding: 6px 8px;
cursor: pointer;
border-bottom: 1px solid #eee;
}

.file-list li:hover {
background-color: #f5f5f5;
}

.file-browser-panel .button-row {
display: flex;
justify-content: space-between;
margin-top: 1rem;
gap: 0.5rem;
}

.back-btn,
.close-btn {
background: #f9f9f9;
border: 1px solid #888;
padding: 6px 12px;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
color: #333;
}

.back-btn:hover {
background-color: #e6e6e6;
color: #111;
border-color: #666;
}

.close-btn {
color: #a00;
border-color: #a00;
}

.close-btn:hover {
background-color: #fcecec;
color: #700;
border-color: #700;
}

.file {
color: #145196;
font-weight: bold;
position: relative;
}

.file::after {
content: ' —— File';
font-weight: normal;
color: #867f7fda;
}

.directory {
color: #0f9145;
font-weight: bold;
position: relative;
}

.directory::after {
content: ' —— Directory';
font-weight: normal;
color: #867f7fda;
}