This commit is contained in:
ali 2025-10-31 15:43:29 +02:00
parent 369e59d01f
commit f233017045
No known key found for this signature in database
GPG key ID: 44F9B42770617B9B
11 changed files with 114 additions and 67 deletions

View file

@ -45,31 +45,30 @@ if TYPE_CHECKING:
optimizations_json = [
{
"source_code": 'from __future__ import annotations\n\n\ndef find_common_tags(articles: list[dict[str, list[str]]]) -> set[str]:\n if not articles:\n return set()\n\n common_tags = set(articles[0].get("tags", []))\n for article in articles[1:]:\n common_tags.intersection_update(article.get("tags", []))\n return common_tags\n',
"explanation": "The original algorithm repeatedly filters the `common_tags` list for every article, which can be slow. We can use Python sets to improve efficiency, especially with large lists.\n\nHere's the optimized version of your function.\n\n\n\n### Explanation of Optimizations.\n1. **Use of Sets**: Convert the initial list of tags to a set, which allows for more efficient intersection operations compared to list comprehensions.\n2. **Intersection Update**: Use the `intersection_update` method on sets which modifies the set in place, making it more memory efficient and faster than creating new lists and converting them to sets repeatedly.\n\nThis optimized version should perform significantly better, especially as the number of articles and tags increases.",
"optimization_id": str(uuid.uuid4()),
},
{
"source_code": 'from __future__ import annotations\n\n\ndef find_common_tags(articles: list[dict[str, list[str]]]) -> set[str]:\n if not articles:\n return set()\n\n common_tags = set(articles[0].get("tags", []))\n for article in articles[1:]:\n common_tags.intersection_update(article.get("tags", []))\n if not common_tags:\n break\n return common_tags\n',
"explanation": "To make the `find_common_tags` function run faster, we can leverage sets, which provide average O(1) time complexity for membership checks and O(n) for intersections. Here\u2019s a refactored version of your program.\n\n\n\nThis version initializes `common_tags` as a set and then iteratively intersects it with the tags of each subsequent article. The `intersection_update` method is used to update `common_tags` in place, which is more efficient. Additionally, it breaks early if `common_tags` becomes empty, which can save unnecessary computation.",
"optimization_id": str(uuid.uuid4()),
},
# {
# "source_code": 'from __future__ import annotations\n\n\ndef find_common_tags(articles: list[dict[str, list[str]]]) -> set[str]:\n if not articles:\n return set()\n\n common_tags = set(articles[0].get("tags", []))\n for article in articles[1:]:\n common_tags.intersection_update(article.get("tags", []))\n return common_tags\n',
# "explanation": "The original algorithm repeatedly filters the `common_tags` list for every article, which can be slow. We can use Python sets to improve efficiency, especially with large lists.\n\nHere's the optimized version of your function.\n\n\n\n### Explanation of Optimizations.\n1. **Use of Sets**: Convert the initial list of tags to a set, which allows for more efficient intersection operations compared to list comprehensions.\n2. **Intersection Update**: Use the `intersection_update` method on sets which modifies the set in place, making it more memory efficient and faster than creating new lists and converting them to sets repeatedly.\n\nThis optimized version should perform significantly better, especially as the number of articles and tags increases.",
# "optimization_id": str(uuid.uuid4()),
# },
# {
# "source_code": 'from __future__ import annotations\n\n\ndef find_common_tags(articles: list[dict[str, list[str]]]) -> set[str]:\n if not articles:\n return set()\n\n common_tags = set(articles[0].get("tags", []))\n for article in articles[1:]:\n common_tags.intersection_update(article.get("tags", []))\n if not common_tags:\n break\n return common_tags\n',
# "explanation": "To make the `find_common_tags` function run faster, we can leverage sets, which provide average O(1) time complexity for membership checks and O(n) for intersections. Here\u2019s a refactored version of your program.\n\n\n\nThis version initializes `common_tags` as a set and then iteratively intersects it with the tags of each subsequent article. The `intersection_update` method is used to update `common_tags` in place, which is more efficient. Additionally, it breaks early if `common_tags` becomes empty, which can save unnecessary computation.",
# "optimization_id": str(uuid.uuid4()),
# },
{
"source_code": 'def find_common_tags(articles: list[dict[str, list[str]]]) -> set[str]:\n if not articles:\n return set()\n\n common_tags = set(articles[0].get("tags", []))\n for article in articles[1:]:\n common_tags.intersection_update(article.get("tags", []))\n if not common_tags: # Early exit if no common tags left\n break\n return common_tags\n',
"explanation": "To optimize the runtime of this function, we can leverage set operations which are generally faster than list comprehensions for membership checks. By converting the tags to sets initially, the intersection operation becomes more efficient. Here's a faster version.\n\n\n\nChanges made.\n1. Convert the tags list of the first article to a set.\n2. Use `intersection_update` method to update the `common_tags` set with the intersection of the current tags and the next article's tags.\n3. Include an early exit condition to break the loop if no common tags remain, further optimizing runtime.",
"optimization_id": str(uuid.uuid4()),
},
{
"source_code": 'from __future__ import annotations\n\n\ndef find_common_tags(articles: list[dict[str, list[str]]]) -> set[str]:\n if not articles:\n return set()\n\n common_tags = set(articles[0].get("tags", []))\n for article in articles[1:]:\n common_tags &= set(article.get("tags", []))\n if not common_tags: # Early exit if no common tags.\n break\n return common_tags\n',
"explanation": "To optimize the provided function, we could enhance its efficiency by using set operations which are typically faster for membership checks compared to list comprehensions.\n\nHere\u2019s the optimized version.\n\n\n\nExplanation.\n1. Convert the tags of the first article into a set to take advantage of fast membership checks and intersection operations.\n2. Use the `&=` operation to find the intersection with the tags of each subsequent article.\n3. Introduce an early exit condition: if `common_tags` becomes empty, it's immediately returned since no further intersection can result in common tags.",
"optimization_id": str(uuid.uuid4()),
},
# {
# "source_code": 'from __future__ import annotations\n\n\ndef find_common_tags(articles: list[dict[str, list[str]]]) -> set[str]:\n if not articles:\n return set()\n\n common_tags = set(articles[0].get("tags", []))\n for article in articles[1:]:\n common_tags &= set(article.get("tags", []))\n if not common_tags: # Early exit if no common tags.\n break\n return common_tags\n',
# "explanation": "To optimize the provided function, we could enhance its efficiency by using set operations which are typically faster for membership checks compared to list comprehensions.\n\nHere\u2019s the optimized version.\n\n\n\nExplanation.\n1. Convert the tags of the first article into a set to take advantage of fast membership checks and intersection operations.\n2. Use the `&=` operation to find the intersection with the tags of each subsequent article.\n3. Introduce an early exit condition: if `common_tags` becomes empty, it's immediately returned since no further intersection can result in common tags.",
# "optimization_id": str(uuid.uuid4()),
# },
]
async def hack_for_demo(ctx: BaseOptimizerContext) -> OptimizeResponseSchema:
print("Hacking for demo baby!!")
response_list: list[OptimizeResponseItemSchema] = [
OptimizeResponseItemSchema(
explanation=optimization["explanation"],

View file

@ -13,11 +13,12 @@ const DemoOptimization = () => {
currentOptimizationTask={demoTask}
forDemo
/>
<TaskLogging task={demoTask} />
<TaskLogging task={demoTask} onDemoSuccess={() => {}} />
</>
);
}
// should display a nice UI with welcom screen where user can trigger a demo task
return <h1>Demo</h1>;
};

View file

@ -105,7 +105,13 @@ const LogItem = memo(
},
);
const TaskLogging = ({ task }: { task: QueueTaskItem }) => {
const TaskLogging = ({
task,
onDemoSuccess,
}: {
task: QueueTaskItem;
onDemoSuccess?: () => void;
}) => {
const listRef = useRef<VirtuosoHandle>(null);
const scrollerRef = useRef<HTMLElement>(null);
@ -125,6 +131,49 @@ const TaskLogging = ({ task }: { task: QueueTaskItem }) => {
listRef.current?.scrollToIndex({ index: task.logs.length - 1 });
}, []);
const getFooterOnSuccess = () => {
return onDemoSuccess ? (
// completed the demo optimization
<div>
<h2>Start using codeflash</h2>
</div>
) : (
<div className={styles.logEntry}>
<div className={styles.logContent}>
<div
style={{
...footerContainerStyles,
color: "var(--vscode-foreground)",
background: "rgba(34, 134, 58, 0.15)",
}}
>
<MemoMarkdownBlock
markdown={`✅ Optimization completed successfully.`}
/>
<button
className={styles.queueTaskPatch}
onClick={() => {
const msg: ViewPatchMessage = {
type: "viewPatch",
payload: {
id: task.id,
functionName: task.functionName,
patchFile: task.patchFile!,
explanation: task.explanation || "",
speedupStr: task.speedupStr || "",
},
};
vscode.postMessage(msg);
}}
>
<span className="codicon codicon-eye"></span>
<span>View Optimization</span>
</button>
</div>
</div>
</div>
);
};
return (
<div className={styles.messagesContainer}>
<Virtuoso
@ -181,42 +230,7 @@ const TaskLogging = ({ task }: { task: QueueTaskItem }) => {
</div>
</div>
)}
{task.status === "completed" && (
<div className={styles.logEntry}>
<div className={styles.logContent}>
<div
style={{
...footerContainerStyles,
color: "var(--vscode-foreground)",
background: "rgba(34, 134, 58, 0.15)",
}}
>
<MemoMarkdownBlock
markdown={`✅ Optimization completed successfully.`}
/>
<button
className={styles.queueTaskPatch}
onClick={() => {
const msg: ViewPatchMessage = {
type: "viewPatch",
payload: {
id: task.id,
functionName: task.functionName,
patchFile: task.patchFile!,
explanation: task.explanation || "",
speedupStr: task.speedupStr || "",
},
};
vscode.postMessage(msg);
}}
>
<span className="codicon codicon-eye"></span>
<span>View Optimization</span>
</button>
</div>
</div>
</div>
)}
{task.status === "completed" && getFooterOnSuccess()}
</div>
);
};

View file

@ -0,0 +1,14 @@
import type { UpdateDemoOptimizationTaskMessage } from "@codeflash/types";
import type { State } from "../root";
export const updateDemoTask = (
oldState: State,
payload: UpdateDemoOptimizationTaskMessage["payload"],
): State => {
return {
...oldState,
demoOptTask: oldState.demoOptTask
? { ...oldState.demoOptTask, ...payload }
: null,
};
};

View file

@ -14,6 +14,7 @@ import { handleUpdateQueueTasks } from "./actions/updateQueueTasks";
import { handleRestoreStateFromCache } from "./actions/restoreStateFromMemory";
import { handleAddLog } from "./actions/addLog";
import { handleAddLogForDemo } from "./actions/addLogForDemo";
import { updateDemoTask } from "./actions/updateDemoTask";
export type State = {
moduleRoot: string;
@ -48,6 +49,7 @@ export type Action = {
initDemoOptTask: (task: QueueTaskItem) => void;
addLog: (log: LogEntry) => void;
addLogForDemo: (log: LogEntry) => void;
updateDemoOptTask: (taskUpdate: Partial<QueueTaskItem>) => void;
};
const initialState: State = {
@ -96,4 +98,6 @@ export const useStore = create<State & Action>((_set) => ({
_set((oldState) => ({ ...oldState, demoOptTask: task })),
addLogForDemo: (log: LogEntry) =>
_set((oldState) => handleAddLogForDemo(oldState, log)),
updateDemoOptTask: (payload: Partial<QueueTaskItem>) =>
_set((oldState) => updateDemoTask(oldState, payload)),
}));

View file

@ -8,6 +8,7 @@ import type {
SetActiveSidebarTabMessage,
SetApiKeyLoadingStateMessage,
StartDemoOptimizationMessage,
UpdateDemoOptimizationTaskMessage,
UpdateQueueTasksMessage,
UpdateStateMessage,
WebviewMessage,
@ -66,6 +67,11 @@ export const messageHandler = (event: MessageEvent, store: State & Action) => {
const { task } = (webviewMessage as StartDemoOptimizationMessage).payload;
store.initDemoOptTask(task);
break;
case "updateDemoOptimizationTask":
const payload = (webviewMessage as UpdateDemoOptimizationTaskMessage)
.payload;
store.updateDemoOptTask(payload);
break;
case "appendLogToDemoOptimizationTask":
const { log: demoLog } = (
webviewMessage as AppendLogToDemoOptimizationTaskMessage

View file

@ -28,7 +28,8 @@ export type MessageType =
| "cancelTask"
| "submitInitForm"
| "appendLogToDemoOptimizationTask"
| "startDemoOptimization";
| "startDemoOptimization"
| "updateDemoOptimizationTask";
export type QueueTaskItemStatus =
| "queued"
@ -114,6 +115,11 @@ export interface AppendLogToDemoOptimizationTaskMessage extends WebviewMessage {
log: LogEntry;
};
}
export interface UpdateDemoOptimizationTaskMessage extends WebviewMessage {
type: "updateDemoOptimizationTask";
payload: Partial<QueueTaskItem>;
}
export interface StartDemoOptimizationMessage extends WebviewMessage {
type: "startDemoOptimization";
payload: {
@ -346,7 +352,8 @@ export type OutgoingWebviewMessage =
| SetActiveSidebarTabMessage
| SetApiKeyLoadingStateMessage
| AppendLogToDemoOptimizationTaskMessage
| StartDemoOptimizationMessage;
| StartDemoOptimizationMessage
| UpdateDemoOptimizationTaskMessage;
export type Suggestion = {
choices: string[];

View file

@ -91,9 +91,6 @@ export async function activate(
if (!globalState.get(GlobalStateKey.IsExtensionInstalled, false)) {
globalState.set(GlobalStateKey.IsExtensionInstalled, true);
await Telemetry.capture("extension_installed", {});
// vscode.window.showInformationMessage(
// "Thank you for installing Codeflash! 🎉\n\nGet started by opening the Codeflash sidebar from the Activity Bar on the left. If you need any help, check out our documentation at https://docs.codeflash.dev/",
// );
}
const optimizationEventEmitter = new LogsEventEmitter(globalState); // for emitting events from the lsp server logs to the sidebar, for tracking the running optimization progress
const showGlobalStateCommand = vscode.commands.registerCommand(

View file

@ -461,7 +461,16 @@ export class SidebarProvider
},
});
await this._optimizationService.runDemoOptimizationTask(functionName);
const result =
await this._optimizationService.runDemoOptimizationTask(functionName);
if (result.status === "success") {
this.sendMessage({
type: "updateDemoOptimizationTask",
payload: {
status: "completed",
},
});
}
} finally {
this.runningDemo = false;
}

View file

@ -63,7 +63,7 @@ export class LspService {
env: {
...process.env,
CODEFLASH_LSP: "true",
// CODEFLASH_CFAPI_SERVER: "local",
CODEFLASH_CFAPI_SERVER: "local",
CODEFLASH_AIS_SERVER: "local",
},
},
@ -76,7 +76,7 @@ export class LspService {
env: {
...process.env,
CODEFLASH_LSP: "true",
// CODEFLASH_CFAPI_SERVER: "local",
CODEFLASH_CFAPI_SERVER: "local",
CODEFLASH_AIS_SERVER: "local",
},
},

View file

@ -38,11 +38,7 @@ export function createInterceptingOutputChannel(
id: uuid,
});
}
} catch (err) {
this.logger.info(
"Failed to parse LSP message " + chunk + " with error " + err,
);
}
} catch {}
});
}