Skip to content

Commit 09d5af6

Browse files
committed
Refactor prompt construction and file collection to use a standardized content builder for provider-specific payloads
- FilesCollector should return object: {other_files: string, recent_files: string} - when the provider is Anthropic, messages should follow the structure: [Pasted text] - move anthropic/other provider 'user content' handling to `apps/editor/src/utils` for reusability - remove unused variables
1 parent a4816be commit 09d5af6

10 files changed

Lines changed: 181 additions & 161 deletions

‎apps/editor/src/commands/code-at-cursor-commands.ts‎

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { PanelProvider } from '@/views/panel/backend/panel-provider'
1616
import { dictionary } from '@shared/constants/dictionary'
1717
import { apply_reasoning_effort } from '../utils/apply-reasoning-effort'
1818
import { t } from '@/i18n'
19+
import { build_user_content } from '../utils/build-user-content'
1920

2021
const show_ghost_text = async (params: {
2122
editor: vscode.TextEditor
@@ -405,25 +406,27 @@ const perform_code_at_cursor = async (params: {
405406
open_editors_provider: params.open_editors_provider
406407
})
407408

408-
const context_text = await files_collector.collect_files()
409+
const collected = await files_collector.collect_files()
409410

410-
const payload = {
411-
before: `<files>\n${context_text}<file path="${vscode.workspace.asRelativePath(
412-
document.uri
413-
)}">\n<![CDATA[\n${text_before_cursor}`,
414-
after: `${text_after_cursor}\n]]>\n</file>\n</files>`
415-
}
416-
417-
const content = `${payload.before}${
411+
const part1 = `<files>\n${collected.other_files}`
412+
const part2 = `${collected.recent_files}<file path="${vscode.workspace.asRelativePath(
413+
document.uri
414+
)}">\n<![CDATA[\n${text_before_cursor}${
418415
completion_instructions
419416
? `<missing_text>${completion_instructions}</missing_text>`
420417
: '<missing_text>'
421-
}${payload.after}\n${code_at_cursor_instructions}`
418+
}${text_after_cursor}\n]]>\n</file>\n</files>\n${code_at_cursor_instructions}`
419+
420+
const user_content = build_user_content({
421+
provider_name: provider.name,
422+
part1,
423+
part2
424+
})
422425

423426
const messages = [
424427
{
425428
role: 'user',
426-
content
429+
content: user_content
427430
}
428431
]
429432

‎apps/editor/src/context/context-initialization.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,8 @@ export const context_initialization = async (
203203
let context_text = ''
204204

205205
try {
206-
context_text = await files_collector.collect_files()
206+
const collected = await files_collector.collect_files()
207+
context_text = collected.other_files + collected.recent_files
207208
} catch (error: any) {
208209
console.error('Error collecting files:', error)
209210
vscode.window.showErrorMessage(
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
export const build_user_content = (params: {
2+
provider_name: string
3+
part1: string
4+
part2: string
5+
}): any => {
6+
const parse_text_with_images = (text: string) => {
7+
if (!text.includes('<cwc-image>')) {
8+
return [{ type: 'text', text }]
9+
}
10+
const parsed: any[] = []
11+
const parts = text.split(/<cwc-image>([\s\S]*?)<\/cwc-image>/)
12+
for (let i = 0; i < parts.length; i++) {
13+
const part = parts[i]
14+
if (i % 2 == 0) {
15+
if (part.length > 0) {
16+
parsed.push({ type: 'text', text: part.trim() })
17+
}
18+
} else {
19+
parsed.push({
20+
type: 'image_url',
21+
image_url: {
22+
url: `data:image/png;base64,${part}`
23+
}
24+
})
25+
}
26+
}
27+
return parsed
28+
}
29+
30+
if (params.provider_name == 'Anthropic') {
31+
const user_content: any[] = [
32+
{
33+
type: 'text',
34+
text: params.part1,
35+
cache_control: { type: 'ephemeral' }
36+
}
37+
]
38+
39+
if (!params.part2.includes('<cwc-image>')) {
40+
user_content.push({ type: 'text', text: params.part2 })
41+
} else {
42+
user_content.push(...parse_text_with_images(params.part2))
43+
}
44+
45+
return user_content
46+
} else {
47+
const content = params.part1 + params.part2
48+
if (content.includes('<cwc-image>')) {
49+
return parse_text_with_images(content)
50+
}
51+
return content
52+
}
53+
}

‎apps/editor/src/utils/files-collector.ts‎

Lines changed: 67 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ export class FilesCollector {
2424
additional_paths?: string[]
2525
no_context?: boolean
2626
compact?: boolean
27-
}): Promise<string> {
27+
}): Promise<{ other_files: string; recent_files: string }> {
2828
const additional_paths = (params?.additional_paths ?? []).map((p) => {
2929
if (this.workspace_roots.length > 0) {
3030
return path.join(this.workspace_roots[0], p)
@@ -50,69 +50,78 @@ export class FilesCollector {
5050
const context_files = [...new Set(context_files_list)]
5151

5252
// Sort context files based on modification time and selection timestamp
53-
const sorted_context_files = this._sort_context_files({
54-
files: context_files
55-
})
56-
57-
let collected_text = ''
58-
59-
for (const file_path of sorted_context_files) {
60-
try {
61-
if (!fs.existsSync(file_path)) continue
62-
const stats = fs.statSync(file_path)
63-
64-
if (stats.isDirectory()) continue
65-
66-
let content = fs.readFileSync(file_path, 'utf8')
67-
68-
const range = this.workspace_provider.get_range(file_path)
69-
if (range) {
70-
content = this.workspace_provider.apply_range_to_content(
71-
content,
72-
range
73-
)
74-
}
75-
76-
if (params?.compact) {
77-
content = compact_file(content, path.extname(file_path))
78-
}
79-
80-
const workspace_root = this._get_workspace_root_for_file(file_path)
81-
82-
if (!workspace_root) {
83-
collected_text += `<file path="${file_path.replace(
84-
/\\/g,
85-
'/'
86-
)}">\n<![CDATA[\n${content}\n]]>\n</file>\n`
87-
continue
53+
const { other_files: other_paths, recent_files: recent_paths } =
54+
this._sort_context_files({
55+
files: context_files
56+
})
57+
58+
const process_paths = (paths: string[]) => {
59+
let collected_text = ''
60+
for (const file_path of paths) {
61+
try {
62+
if (!fs.existsSync(file_path)) continue
63+
const stats = fs.statSync(file_path)
64+
65+
if (stats.isDirectory()) continue
66+
67+
let content = fs.readFileSync(file_path, 'utf8')
68+
69+
const range = this.workspace_provider.get_range(file_path)
70+
if (range) {
71+
content = this.workspace_provider.apply_range_to_content(
72+
content,
73+
range
74+
)
75+
}
76+
77+
if (params?.compact) {
78+
content = compact_file(content, path.extname(file_path))
79+
}
80+
81+
const workspace_root = this._get_workspace_root_for_file(file_path)
82+
83+
if (!workspace_root) {
84+
collected_text += `<file path="${file_path.replace(
85+
/\\/g,
86+
'/'
87+
)}">\n<![CDATA[\n${content}\n]]>\n</file>\n`
88+
continue
89+
}
90+
91+
const relative_path = path
92+
.relative(workspace_root, file_path)
93+
.replace(/\\/g, '/')
94+
95+
// Get the workspace name to prefix the path if there are multiple workspaces
96+
let display_path = relative_path
97+
if (this.workspace_roots.length > 1) {
98+
const workspace_name =
99+
this.workspace_provider.get_workspace_name(workspace_root)
100+
display_path = `${workspace_name}/${relative_path}`
101+
}
102+
103+
collected_text += `<file path="${display_path}">\n<![CDATA[\n${content}\n]]>\n</file>\n`
104+
} catch (error) {
105+
console.error(`Error reading file ${file_path}:`, error)
88106
}
89-
90-
const relative_path = path
91-
.relative(workspace_root, file_path)
92-
.replace(/\\/g, '/')
93-
94-
// Get the workspace name to prefix the path if there are multiple workspaces
95-
let display_path = relative_path
96-
if (this.workspace_roots.length > 1) {
97-
const workspace_name =
98-
this.workspace_provider.get_workspace_name(workspace_root)
99-
display_path = `${workspace_name}/${relative_path}`
100-
}
101-
102-
collected_text += `<file path="${display_path}">\n<![CDATA[\n${content}\n]]>\n</file>\n`
103-
} catch (error) {
104-
console.error(`Error reading file ${file_path}:`, error)
105107
}
108+
return collected_text
106109
}
107110

108-
return collected_text
111+
return {
112+
other_files: process_paths(other_paths),
113+
recent_files: process_paths(recent_paths)
114+
}
109115
}
110116

111117
private _get_workspace_root_for_file(file_path: string): string | undefined {
112118
return this.workspace_provider.get_workspace_root_for_file(file_path)
113119
}
114120

115-
private _sort_context_files(params: { files: string[] }): string[] {
121+
private _sort_context_files(params: { files: string[] }): {
122+
other_files: string[]
123+
recent_files: string[]
124+
} {
116125
const recently_modified: Array<{ path: string; mtime: number }> = []
117126
const older_files: Array<{ path: string; timestamp: number }> = []
118127
const now = Date.now()
@@ -153,9 +162,9 @@ export class FilesCollector {
153162

154163
recently_modified.sort((a, b) => a.mtime - b.mtime)
155164

156-
return [
157-
...older_files.map((f) => f.path),
158-
...recently_modified.map((f) => f.path)
159-
]
165+
return {
166+
other_files: older_files.map((f) => f.path),
167+
recent_files: recently_modified.map((f) => f.path)
168+
}
160169
}
161170
}

‎apps/editor/src/views/panel/backend/message-handlers/handle-code-at-cursor.ts‎

Lines changed: 10 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { replace_image_symbol } from '../utils/replace-image-symbol'
2727
import { replace_pasted_text_symbol } from '../utils/replace-pasted-text-symbol'
2828
import { replace_website_symbol } from '../utils/replace-website-symbol'
2929
import { replace_fragment_symbol } from '../utils/replace-fragment-symbol'
30+
import { build_user_content } from '@/utils/build-user-content'
3031

3132
const get_code_at_cursor_config = async (
3233
api_providers_manager: ModelProvidersManager,
@@ -415,41 +416,20 @@ export const handle_code_at_cursor = async (
415416
open_editors_provider: panel_provider.open_editors_provider
416417
})
417418

418-
const context_text = await files_collector.collect_files()
419+
const collected = await files_collector.collect_files()
419420

420-
const payload = {
421-
before: `<files>\n${context_text}<file path="${relative_path}">\n<![CDATA[\n${text_before_cursor}`,
422-
after: `${text_after_cursor}\n]]>\n</file>\n</files>`
423-
}
424-
425-
const content = `${payload.before}${
421+
const part1 = `<files>\n${collected.other_files}`
422+
const part2 = `${collected.recent_files}<file path="${relative_path}">\n<![CDATA[\n${text_before_cursor}${
426423
processed_completion_instructions
427424
? `<missing_text>${processed_completion_instructions}</missing_text>`
428425
: '<missing_text>'
429-
}${payload.after}\n${skill_definitions}${main_instructions}`
430-
431-
let user_content: any = content
426+
}${text_after_cursor}\n]]>\n</file>\n</files>\n${skill_definitions}${main_instructions}`
432427

433-
if (content.includes('<cwc-image>')) {
434-
user_content = []
435-
const parts = content.split(/<cwc-image>([\s\S]*?)<\/cwc-image>/)
436-
437-
for (let i = 0; i < parts.length; i++) {
438-
const part = parts[i]
439-
if (i % 2 == 0) {
440-
if (part.length > 0) {
441-
user_content.push({ type: 'text', text: part.trim() })
442-
}
443-
} else {
444-
user_content.push({
445-
type: 'image_url',
446-
image_url: {
447-
url: `data:image/png;base64,${part}`
448-
}
449-
})
450-
}
451-
}
452-
}
428+
const user_content = build_user_content({
429+
provider_name: provider.name,
430+
part1,
431+
part2
432+
})
453433

454434
const messages = [
455435
{

‎apps/editor/src/views/panel/backend/message-handlers/handle-copy-prompt.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,8 @@ export const handle_copy_prompt = async (params: {
7979
new vscode.Range(position, document.positionAt(document.getText().length))
8080
)
8181

82-
const context_text = await files_collector.collect_files()
82+
const collected = await files_collector.collect_files()
83+
const context_text = collected.other_files + collected.recent_files
8384

8485
const workspace_folder = vscode.workspace.workspaceFolders?.[0].uri.fsPath
8586
const relative_path = active_path.replace(workspace_folder + '/', '')
@@ -180,10 +181,11 @@ export const handle_copy_prompt = async (params: {
180181
(params.panel_provider.mode == MODE.API &&
181182
params.panel_provider.api_prompt_type == 'prune-context')
182183

183-
const context_text = await files_collector.collect_files({
184+
const collected = await files_collector.collect_files({
184185
no_context: params.panel_provider.web_prompt_type == 'no-context',
185186
compact: is_in_prune_context_prompt_type
186187
})
188+
const context_text = collected.other_files + collected.recent_files
187189

188190
const instructions = replace_selection_symbol(final_instruction)
189191

0 commit comments

Comments
 (0)